{"text": "function points = getSpacedPoints(X1, X2, N, spacing)\n%GETSPACEDPOINTS Create vector of log or linear spaced points.\n%\n% DESCRIPTION:\n% getSpacedPoints generates a row vector of either logarithmically\n% or linearly spaced points between X1 and X2. When spacing is set to\n% 'linear', the function is identical to the inbuilt linspace\n% function. When spacing is set to 'log', the function is similar to\n% the inbuilt logspace function, except that X1 and X2 define the\n% start and end numbers, not decades. For logarithmically spaced\n% points, X1 must be > 0. If N < 2, X2 is returned. \n%\n% USAGE:\n% points = getSpacedPoints(X1, X2)\n% points = getSpacedPoints(X1, X2, N)\n% points = getSpacedPoints(X1, X2, N, spacing)\n%\n% INPUTS:\n% X1 - starting points value\n% X2 - ending points value (where X2 > X1)\n%\n% OPTIONAL INPUTS:\n% N - number of points in the vector (default = 100)\n% spacing - 'log' or 'linear' spaced values (default = 'linear')\n%\n% OUTPUTS:\n% points - row vector of equally spaced points\n%\n% ABOUT:\n% author - Bradley E. Treeby\n% date - 14th July 2005\n% last update - 1st December 2012\n%\n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n% check for number of points input\nif nargin < 3\n N = 100;\nend\n\n% check for spacing input\nif nargin < 4\n spacing = 'linear';\nend\n\n% check if the end point is larger than the start point\nif X2 <= X1\n error('X2 must be larger than X1');\nend\n\n% force N to be an integer\nN = round(N);\n\nif (N < 2)\n % return the end point if N < 2\n points = X2;\nelseif (N == 2)\n % return the start and end points if N = 2\n points(1) = X1;\n points(2) = X2;\nelse\n\n % update X1 and X2 values for log spaced variables\n if (strcmp(spacing, 'log'))\n \n % check that X1 is greater than 0\n if X1 <= 0\n error('X1 must be > 0 for log spaced points');\n end\n \n X1 = log10(X1);\n X2 = log10(X2);\n end\n \n % create step variable and points range\n step = (X2 - X1)/(N - 1);\n points = X1:step:X2;\n \n % update log spaced points\n if (strcmp(spacing, 'log'))\n points = 10.^(points);\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/getSpacedPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.7999857850280055}} {"text": "%\n% This is the main script to finds a (near) optimal solution to the Traveling\n% Salesman Problem (TSP), by setting up a Simulated Annealing (SA) to search \n% for the shortest route (least distance for the salesman to travel to each \n% city exactly once and return to the starting city).\n%\n\nclear;clc;\n\nload china; % geographic information\nplotcities(province, border, city); % draw the map of China\n\nnumberofcities = length(city); % number of cities\n% distance matrix: dis(i,j) is the distance between city i and j.\ndis = distancematrix(city); \n\nglobal h;\ntemperature = 1000; % Initialize the temperature.\ncooling_rate = 0.94; % cooling rate\niterations = 1; % Initialize the iteration number.\n\n% Initialize random number generator with \"seed\". \nrand('seed',0); \n\n% Initialize the route by generate a sequence of random\nroute = randperm(numberofcities);\n% This is objective function, the total distance for the routes.\nprevious_distance = totaldistance(route,dis);\n\n% This is a flag used to cool the current temperature after 100 iterations\ntemperature_iterations = 1;\n% This is a flag used to plot the current route after 200 iterations\nplot_iterations = 1;\n\n% plot the current route\nplotroute(city, route, previous_distance, temperature);\n\nwhile 1.0 < temperature\n % generate randomly a neighbouring solution\n temp_route = perturb(route,'reverse');\n % compute total distance of the temp_route\n current_distance = totaldistance(temp_route, dis);\n % compute change of distance\n diff = current_distance - previous_distance;\n \n % Metropolis Algorithm\n if (diff < 0) || (rand < exp(-diff/(temperature)))\n route = temp_route; %accept new route\n previous_distance = current_distance;\n \n % update iterations\n temperature_iterations = temperature_iterations + 1;\n plot_iterations = plot_iterations + 1;\n iterations = iterations + 1;\n end\n \n % reduce the temperature every 100 iterations\n if temperature_iterations >= 100\n temperature = cooling_rate*temperature;\n temperature_iterations = 0;\n end\n \n % plot the current route every 200 iterations\n if plot_iterations >= 200\n plotroute(city, route, previous_distance, temperature);\n plot_iterations = 0;\n end\nend\n\n% plot and output final solution\nplotroute(city, route, previous_distance, temperature);\n% sth. wrong with function fpdfprinter\nfpdfprinter('Final Solution')\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/HeuristicAlgorithm(补分启发式算法,包括神经网络、模拟退火、遗传算法)/模拟退火算法/TSP(SA)/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.943347579470196, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7999283341466931}} {"text": "function [mu ul ll] = circ_mean(alpha, w, dim)\n%\n% mu = circ_mean(alpha, w)\n% Computes the mean direction for circular data.\n%\n% Input:\n% alpha\tsample of angles in radians\n% [w\t\tweightings in case of binned angle data]\n% [dim compute along this dimension, default is 1]\n%\n% If dim argument is specified, all other optional arguments can be\n% left empty: circ_mean(alpha, [], dim)\n%\n% Output:\n% mu\t\tmean direction\n% ul upper 95% confidence limit\n% ll lower 95% confidence limit \n%\n% PHB 7/6/2008\n%\n% References:\n% Statistical analysis of circular data, N. I. Fisher\n% Topics in circular statistics, S. R. Jammalamadaka et al. \n% Biostatistical Analysis, J. H. Zar\n%\n% Circular Statistics Toolbox for Matlab\n\n% By Philipp Berens, 2009\n% berens@tuebingen.mpg.de - www.kyb.mpg.de/~berens/circStat.html\n\nif nargin < 3\n dim = 1;\nend\n\nif nargin < 2 || isempty(w)\n % if no specific weighting has been specified\n % assume no binning has taken place\n\tw = ones(size(alpha));\nelse\n if size(w,2) ~= size(alpha,2) || size(w,1) ~= size(alpha,1) \n error('Input dimensions do not match');\n end \nend\n\n% compute weighted sum of cos and sin of angles\nr = sum(w.*exp(1i*alpha),dim);\n\n% obtain mean by\nmu = angle(r);\n\n% confidence limits if desired\nif nargout > 1\n t = circ_confmean(alpha,0.05,w,[],dim);\n ul = mu + t;\n ll = mu - t;\nend", "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/CircStat2012a/circ_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7999283251199748}} {"text": "function y = r8vec_sct ( n, x )\n\n%*****************************************************************************80\n%\n%% R8VEC_SCT computes a \"slow\" cosine transform of an R8VEC.\n%\n% Discussion:\n%\n% This routine is provided for illustration and testing. It is inefficient\n% relative to optimized routines that use fast Fourier techniques.\n%\n% Y(1) = Sum ( 1 <= J <= N ) X(J)\n%\n% For 2 <= I <= N-1:\n%\n% Y(I) = 2 * Sum ( 1 <= J <= N ) X(J)\n% * cos ( PI * ( I - 1 ) * ( J - 1 ) / ( N - 1 ) )\n%\n% Y(N) = Sum ( X(1:N:2) ) - Sum ( X(2:N:2) )\n%\n% Applying the routine twice in succession should yield the original data,\n% multiplied by 2 * ( N + 1 ). This is a good check for correctness\n% and accuracy.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of data values.\n%\n% Input, real X(N), the data sequence.\n%\n% Output, real Y(N), the transformed data.\n%\n for i = 1 : n\n\n y(i) = x(1) / 2.0;\n\n for j = 2 : n - 1\n angle = pi * mod ( ( i - 1 ) * ( j - 1 ), 2 * ( n - 1 ) ) / ( n - 1 );\n y(i) = y(i) + x(j) * cos ( angle );\n end\n\n j = n;\n\n angle = pi * mod ( ( i - 1 ) * ( j - 1 ), 2 * ( n - 1 ) ) / ( n - 1 );\n\n y(i) = y(i) + x(n) * cos ( angle ) / 2.0;\n\n end\n\n y(1:n) = 2.0 * y(1:n) * sqrt ( n / ( 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/sftpack/r8vec_sct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7998812386291044}} {"text": "function [ess,m] = spm_mci_ess (x,p)\n% Compute Effective Sample Size\n% FORMAT [ess,m] = spm_mci_ess (x,p)\n%\n% x Univariate time series\n% p Maximum lag for autocovariance estimation\n%\n% ess Effective Sample Size\n% m Number of lags used in ESS estimate\n%\n% This routine is based on the Initial Positive Sequence estimate\n% proposed in C. Geyer (1992) Practical Markov Chain Monte Carlo, \n% Statistical Science, 7(4):473-511.\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_mci_ess.m 6697 2016-01-27 14:57:28Z spm $\n\nN=length(x);\n\ntry, pmax=p; catch, pmax=min(ceil(N/10),256); end\n\nfor i=1:pmax,\n y(:,i)=x(pmax-i+1:end-i);\nend\nC=cov(y);\nc=C(1,:);\ngamma=c(2:end);\ngamma0=c(1);\nr=gamma/gamma0;\n\nG=[];\nfor j=1:floor(pmax/2)-1,\n % Sum of adjacent pairs of autocovariances\n G(j)=gamma(2*j)+gamma(2*j+1);\nend\n\nif ~isempty(G)\n % Find minimum j such that all G's up to j are positive\n Gneg=find(G<0);\n if isempty(Gneg)\n m=length(G);\n else\n m1=min(Gneg);\n m=m1-1;\n end\nelse\n m=0;\nend\n\ness=N/(1+2*sum(r(1:2*m)));\n\n% figure;\n% plot(c);\n% title('Autocovariance');\n% \n% figure\n% plot(G);\n% title('Sum of adjacent covariances');", "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_ess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.799859659063691}} {"text": "function v = haar_1d_inverse ( n, u )\n\n%*****************************************************************************80\n%\n%% HAAR_1D_INVERSE inverts the Haar transform of a vector.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 March 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the length of the vector.\n% N must be a power of 2.\n%\n% Input, real U(N,1), the vector to be transformed.\n%\n% Output, real V(N,1), the transformed vector.\n%\n v = u(:);\n\n s = sqrt ( 2.0 );\n\n w = zeros ( n, 1 );\n\n m = 1;\n\n while ( m * 2 <= n )\n\n w(1:2:2*m-1) = ( v(1:m) + v(1+m:m+m) ) / s;\n w(2:2:2*m) = ( v(1:m) - v(1+m:m+m) ) / s;\n\n v(1:2*m) = w(1:2*m);\n m = m * 2;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/haar/haar_1d_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7998287160386195}} {"text": "function table = p_power_product ( p, e )\n\n%*****************************************************************************80\n%\n%% P_POWER_PRODUCT: power products for Legendre polynomial P(n,x).\n%\n% Discussion:\n%\n% Let P(n,x) represent the Legendre polynomial of degree i. \n%\n% For polynomial chaos applications, it is of interest to know the\n% value of the integrals of products of powers of X with every possible pair\n% of basis functions. That is, we'd like to form\n%\n% Tij = Integral ( -1 <= X <= +1 ) X^E * P(i,x) * P(j,x) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer P, the maximum degree of the polyonomial factors.\n% 0 <= P.\n%\n% Input, integer E, the exponent of X in the integrand.\n% 0 <= E.\n%\n% Output, real TABLE(P+1,P+1), the table of integrals.\n%\n table(1:p+1,1:p+1) = 0.0;\n\n order = p + 1 + floor ( ( e + 1 ) / 2 );\n [ x_table, w_table ] = p_quadrature_rule ( order );\n\n for k = 1 : order\n\n x = x_table(k);\n l_table = p_polynomial_value ( 1, p, x );\n%\n% The following formula is an outer product in L_TABLE.\n%\n if ( e == 0 )\n table(1:p+1,1:p+1) = table(1:p+1,1:p+1) ...\n + w_table(k) * l_table(1:p+1)' * l_table(1:p+1);\n else\n table(1:p+1,1:p+1) = table(1:p+1,1:p+1) ...\n + w_table(k) * x^e * l_table(1:p+1)' * l_table(1:p+1);\n end\n\n end\n\n return\nend\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/legendre_polynomial/p_power_product.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7998287108680202}} {"text": "function [coreness,kn] = kcoreness_centrality_bu(CIJ)\n%KCORENESS_CENTRALITY_BU K-coreness centrality\n%\n% [coreness,kn] = kcoreness_centrality_bu(CIJ)\n%\n% The k-core is the largest subgraph comprising nodes of degree at least\n% k. The coreness of a node is k if the node belongs to the k-core but\n% not to the (k+1)-core. This function computes the coreness of all nodes\n% for a given binary undirected connection matrix.\n%\n% input: CIJ, connection/adjacency matrix (binary, undirected)\n%\n% output: coreness, node coreness.\n% kn, size of k-core\n%\n% References: e.g. Hagmann et al. (2008) PLoS Biology\n%\n% Olaf Sporns, Indiana University, 2007/2008/2010/2012\n\nN = size(CIJ,1);\n\n% determine if the network is undirected - if not, compute coreness on the\n% corresponding undirected network\nCIJund = CIJ+CIJ';\nif (any(CIJund(:)>1))\n CIJ = double(CIJund>0);\nend;\n\ncoreness = zeros(1,N); kn = zeros(1,N);\nfor k=1:N\n [CIJkcore,kn(k)] = kcore_bu(CIJ,k);\n ss = sum(CIJkcore)>0;\n coreness(ss) = k;\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/kcoreness_centrality_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7998287010372985}} {"text": "function [filtered_signal,filtb,filta]=lopass_butterworth(inputsignal,cutoff_freq,Fs,order)\n% Low-pass Butterworth filter\n% [filtered_signal,filtb,filta] = lopass_butterworth(inputsignal,cutoff_freq,Fs,order)\n% \n% This is simply a set of built-in Matlab functions, repackaged for ease of\n% use by Chad Greene, October 2012. \n%\n% INPUTS: \n% inputsignal = input time series\n% cutoff_freq = filter corner frequency\n% Fs = data sampling frequency\n% order = order of Butterworth filter\n% \n% OUTPUTS: \n% filtered_signal = the filtered time series\n% filtb, filta = filter numerator and denominator (optional)\n% \n% EXAMPLE 1: \n% load train\n% t = (1:length(y))/Fs;\n% y_filt = lopass_butterworth(y,900,Fs,4); % cut off at 900 Hz\n% figure\n% plot(t,y,'b',t,y_filt,'r')\n% xlabel('time in seconds')\n% box off\n% legend('unfiltered','filtered')\n% sound(y,Fs) % play original time series\n% pause(2) % pause two seconds\n% sound(y_filt,Fs) % play filtered time series\n% \n% \n% EXAMPLE 2: \n% load train\n% t = (1:length(y))/Fs;\n% [y_filt,filtb,filta] = lopass_butterworth(y,900,Fs,4); % cut off at 900 Hz\n% [h1,f1] = freqz(filtb,filta,256,Fs);\n% \n% figure\n% subplot(3,1,1)\n% plot(t,y,'b',t,y_filt,'r')\n% xlabel('time in seconds')\n% box off\n% text(0,.1,' time series','units','normalized')\n% \n% subplot(3,1,2)\n% AX = plotyy(f1,10*log10(abs(h1)),f1,angle(h1),'semilogx');\n% set(get(AX(1),'ylabel'),'string','gain (dB)')\n% set(get(AX(2),'ylabel'),'string','phase (rad)')\n% xlim(AX(1),[min(f1) max(f1)])\n% xlim(AX(2),[min(f1) max(f1)])\n% text(0,.1,' filter response','units','normalized')\n% box off\n% \n% [Pxx,f] = pwelch(y,512,256,[],Fs,'onesided');\n% [Pxxf,f_f]= pwelch(y_filt,512,256,[],Fs,'onesided');\n% subplot(3,1,3)\n% semilogx(f,10*log10(Pxx))\n% hold on\n% semilogx(f_f,10*log10(Pxxf),'r')\n% xlabel('frequency (Hz)')\n% ylabel('PSD (dB)')\n% xlim([min(f1) max(f1)])\n% box off\n% legend('unfiltered','filtered','location','northwest')\n% legend boxoff\n\nnyquist_freq = Fs/2; % Nyquist frequency\nWn=cutoff_freq/nyquist_freq; % non-dimensional frequency\n[filtb,filta]=butter(order,Wn,'low'); % construct the filter\nfiltered_signal=filtfilt(filtb,filta,inputsignal); % filter the data with zero phase ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38584-butterworth-filters/Butterworth Filters/lopass_butterworth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8740772335247531, "lm_q1q2_score": 0.7996940956894184}} {"text": "function [is,os,str] = strengths_dir(CIJ)\n%STRENGTHS_DIR In-strength and out-strength\n%\n% [is,os,str] = strengths_dir(CIJ);\n%\n% Node strength is the sum of weights of links connected to the node. The\n% instrength is the sum of inward link weights and the outstrength is the\n% sum of outward link weights.\n%\n% Input: CIJ, directed weighted connection matrix\n%\n% Output: is, node instrength\n% os, node outstrength\n% str, node strength (instrength + outstrength)\n%\n% Notes: Inputs are assumed to be on the columns of the CIJ matrix.\n%\n%\n% Olaf Sporns, Indiana University, 2002/2006/2008\n\n\n% compute strengths\nis = sum(CIJ,1); % instrength = column sum of CIJ\nos = sum(CIJ,2)'; % outstrength = row sum of CIJ\nstr = is+os; % strength = instrength+outstrength\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/2019_03_03_BCT/strengths_dir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.799631736472321}} {"text": "function [T, Eps] = estimateRigidTransform(x, y)\n% ESTIMATERIGIDTRANSFORM\n% [T, EPS] = ESTIMATERIGIDTRANSFORM(X, Y) estimates the rigid transformation\n% that best aligns x with y (in the least-squares sense).\n% \n% Reference: \"Estimating Rigid Transformations\" in \n% \"Computer Vision, a modern approach\" by Forsyth and Ponce (1993), page 480\n% (page 717(?) of the newer edition)\n%\n% Input:\n% X: 3xN, N 3-D points (N>=3)\n% Y: 3xN, N 3-D points (N>=3)\n%\n% Output\n% T: the rigid transformation that aligns x and y as: xh = T * yh\n% (h denotes homogenous coordinates) \n% (corrspondence between points x(:,i) and y(:,i) is assumed)\n% \n% EPS: the smallest singular value. The closer this value it is \n% to 0, the better the estimate is. (large values mean that the \n% transform between the two data sets cannot be approximated\n% well with a rigid transform.\n%\n% Babak Taati, 2003\n% (revised 2009)\n\nif nargin ~= 2\n error('Requires two input arguments.')\nend\n\nif size(x,1)~=3 || size(y,1)~=3\n error('Input point clouds must be a 3xN matrix.');\nend\n\nif size(x, 2) ~= size(y,2)\n error('Input point clouds must be of the same size');\nend \n\nif size(x,2)<3 || size(y,2)<3\n error('At least 3 point matches are needed');\nend \n \npointCount = length(x); % since x has N=3+ points, length shows the number of points\n \nx_centroid = sum(x,2) / pointCount;\ny_centroid = sum(y,2) / pointCount; \n\nx_centrized = [x(1,:)-x_centroid(1) ; x(2,:)-x_centroid(2); x(3,:)-x_centroid(3)];\ny_centrized = [y(1,:)-y_centroid(1) ; y(2,:)-y_centroid(2); y(3,:)-y_centroid(3)];\n\nR12 = y_centrized' - x_centrized';\nR21 = x_centrized - y_centrized;\nR22_1 = y_centrized + x_centrized;\nR22 = crossTimesMatrix(R22_1(1:3,:));\n\nB = zeros(4, 4);\nA = zeros(4, 4, pointCount);\nfor ii=1:pointCount\n A(1:4,1:4,ii) = [0, R12(ii,1:3); R21(1:3,ii), R22(1:3,1:3,ii)];\n B = B + A(:,:,ii)' * A(:,:,ii);\nend\n\n[~, S, V] = svd(B);\nquat = V(:,4);\nrot = quat2rot(quat);\n\nT1 = [eye(3,3), -y_centroid ; 0 0 0 1];\nT2 = [rot, [0; 0; 0]; 0 0 0 1];\nT3 = [eye(3,3), x_centroid ; 0 0 0 1];\n\nT = T3 * T2 * T1;\nEps = S(4,4);\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/28305-estimaterigidtransform/estimateRigidTransform/estimateRigidTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7996264050728802}} {"text": "function theta = circle_segment_angle_from_chord_angles ( omega1, omega2 )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_ANGLE_FROM_CHORD_ANGLES computes the angle of a circle segment.\n%\n% Discussion:\n%\n% Begin with a circle of radius R. Choose two points P1 and P2 on the\n% circle, and draw the chord P1:P2. This chord divides the circle\n% into two pieces, each of which is called a circle segment.\n% Consider one of the pieces. The \"angle\" of this segment is the angle \n% P1:C:P2, where C is the center of the circle. Let Q be the point on \n% the chord P1:P2 which is closest to C. The \"height\" of the segment\n% is the distance from Q to the perimeter of the circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 17 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real OMEGA1, OMEGA2, the angles of the points P1 and P2.\n% OMEGA1 <= OMEGA2.\n%\n% Output, real THETA, the angle of the circle segment.\n% Essentially, THETA = OMEGA2 - OMEGA1.\n%\n while ( omega2 < omega1 )\n omega2 = omega2 + 2.0 * pi;\n end\n\n theta = omega2 - omega1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/circle_segment_angle_from_chord_angles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7995897679971797}} {"text": "function yp = p07_fun ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P07_FUN evaluates the function for problem P07.\n%\n% Discussion:\n%\n% y1' = -y1 + y2\n% y2' = y1 - 2 y2 + y3\n% y3' = y2 - y3\n% y1(0) = 2\n% y2(0) = 0\n% y3(0) = 1\n%\n% 3 equations.\n% Enright and Pryce nonstiff problem #B2.\n% Autonomous.\n%\n% Note that the quantity (y1+y2+y3) is conserved by the exact solution.\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% 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(1) + y(2);\n yp(2) = y(1) - 2.0 * y(2) + y(3);\n yp(3) = y(2) - y(3);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_ode/p07_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.7995390356374538}} {"text": "%% Rotational Approximation and Interpolation\n%\n%%\n% On this page, we want to cover the topic of function approximation from\n% discrete values on the Rotation group. To simulate this, we have stored some\n% nodes and corresponding function values which we can load. The csv-file\n% contains the Euler angles $\\phi_1$, $\\Phi$ and $\\phi_2$ of the nodes and the function\n% value in the fourth column. Lets import these data using the function\n% \n\nfname = fullfile(mtexDataPath, 'orientation', 'dubna.csv');\n[nodes, S] = orientation.load(fname,'columnNames',{'phi1','Phi','phi2','values'});\n\n%%\n% The second output |S| is a struct that contains a field |S.values| with\n% the function values from the fourth column. Next, we can make a section\n% plot to see, what we are dealing with\n\nplotSection(nodes, S.values,'all');\n\n%%\n% Now, we want to find a function which coincides with the given function\n% values in the nodes reasonably well.\n\n%% Interpolation\n%\n%%\n% Interpolation is done by the command\n% of class \n\nSO3F = SO3Fun.interpolate(nodes, S.values,'exact');\nplot(SO3F)\n\n%% \n% The interpolation is done by lsqr. Hence the error is not in machine\n% precision.\nnorm(SO3F.eval(nodes) - S.values)\n\n%%\n% If we don't restrict ourselfs to the given function values in the nodes, we have more\n% freedom, which can be seen in the case of approximation.\n\n%% Approximation\n%\n% In contrast to interpolation we are now not restricted to the function\n% values in the nodes but still want to keep the error reasonably small.\n%\n%%\n% One way is to interpolate the function similary as before, without the \n% option |'exact'|.\n%\n%%\n% Another way is to approximate the rotational function with a series of \n% (Harmonic series). \n% We don't take as many Wigner-D functions as there are nodes,\n% such that we are in the overdetermined case. In that way we don't have a\n% chance of getting the error in the nodes zero but hope for a smoother\n% approximation. This can be achieved by the \n% command of the class \n\nSO3F2 = SO3FunHarmonic.approximation(nodes, S.values);\nplot(SO3F2)\n\n%%\n% Plotting this function, we can immidiately see, that we have a much\n% smoother function. But one has to keep in mind that the error in the data\n% nodes is not zero as in the case of interpolation.\n\nnorm(eval(SO3F, nodes) - S.values)\n\n%%\n% But this may not be of great importance like in the case of function\n% approximation from noisy function values, where we don't know the exact\n% function values anyways.\n\n%%\n%\n% The strategy underlying the |approximation|-command\n% to obtain such an approximation works via Wigner-D functions\n% (). For that,\n% we seek for so-called Fourier-coefficients ${\\bf \\hat f} = (\\hat\n% f^{0,0}_0,\\dots,\\hat f^{N,N}_N)^T$ such that\n%\n% $$ g(x) = \\sum_{n=0}^N\\sum_{k,l = -n}^n \\hat f_n^{k,l} D_n^{k,l}(x) $$\n%\n% approximates our function. A basic strategy to achieve this is through\n% least squares, where we minimize the functional \n%\n% $$ \\sum_{m=1}^M|f(x_m)-g(x_m)|^2 $$\n%\n% for the data nodes $x_m$, $m=1,\\dots,M$, $f(x_m)$ the target function\n% values and $g(x_m)$ our approximation evaluated in the given data nodes.\n%\n% This can be done by the |lsqr| function of Matlab, which efficiently\n% seeks for roots of the derivative of the given functional (also known as\n% normal equation). In the process we compute the matrix-vector product\n% with the Fourier-matrix multible times, where the Fourier-matrix is given\n% by\n%\n% $$ F = [D_n^{k,l}(x_m)]_{m = 1,\\dots,M;~n = 0,\\dots,N,\\,k,l = -n,\\dots,n}. $$\n%\n% This matrix-vector product can be computed efficiently with the use of\n% the nonequispaced SO(3) Fourier transform\n% \n% or faster by the combination of an Wigner-transform together with a \n% .\n%\n% We end up with the Fourier-coefficients of our approximation $g$, which\n% describe our approximation.\n%\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/SO3Functions/SO3FunApproximationInterpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.7995390325715506}} {"text": "function [U, R, V] = cod(A, tol)\n%COD Complete orthogonal decomposition.\n% [U, R, V] = COD(A, TOL) computes a decomposition A = U*T*V,\n% where U and V are unitary, T = [R 0; 0 0] has the same dimensions as\n% A, and R is upper triangular and nonsingular of dimension rank(A).\n% Rank decisions are made using TOL, which defaults to approximately\n% LENGTH(A)*NORM(A)*EPS.\n% By itself, COD(A, TOL) returns R.\n\n% Reference:\n% G. H. Golub and C. F. Van Loan, Matrix Computations, third\n% edition, Johns Hopkins University Press, Baltimore, Maryland,\n% 1996; sec. 5.4.2.\n\n[m, n] = size(A);\n\n% QR decomposition.\n[U, R, P] = qr(A); % AP = UR\nV = P'; % A = URV;\nif nargin == 1, tol = max(m,n)*eps*abs(R(1,1)); end % |R(1,1)| approx NORM(A).\n\n% Determine r = effective rank.\nr = sum(abs(diag(R)) > tol);\nr = r(1); % Fix for case where R is vector.\nR = R(1:r,:); % Throw away negligible rows (incl. all zero rows, m>n).\n\nif r ~= n\n\n % Reduce nxr R' = r [L] to lower triangular form: QR' = [Lbar].\n % n-r [M] [0]\n\n [Q, R] = trap2tri(R');\n V = Q*V;\n R = R';\n\nend\n\nif nargout <= 1, U = R; end\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/utilities/matrixcomp/cod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7994902267765951}} {"text": "function [ti,fi]=midpoint(t1,f1,t2,f2,k)\n%MIDPOINT Mid-point construction used in the interference diagram. \n%\t[TI,FI]=MIDPOINT(T1,F1,T2,F2,K) gives the coordinates in the\n%\ttime-frequency plane of the interference-term corresponding to\n%\tthe points (T1,F1) and (T2,F2), for a distribution in the\n%\taffine class perfectly localized on power-law group-delays of \n%\tthe form : tx(nu)=t0+c nu^(K-1).\n%\n%\tT1 : time-coordinate of the first point\n%\tF1 : frequency-coordinate of the first point (>0)\n%\tT2 : time-coordinate of the second point\n%\tF2 : frequency-coordinate of the second point (>0)\n%\tK : power of the group-delay law\n%\t K = 2 : Wigner-Ville \n%\t K = 1/2 : D-Flandrin\n%\t K = 0 : Bertrand (unitary) \n%\t K = -1 : Unterberger (active)\n%\t K = inf : Margenau-Hill-Rihaczek\n%\tTI : time-coordinate of the interference term\n%\tFI : frequency-coordinate of the interference term\n%\n%\tSee also PLOTSID.\n\n%\tP. Flandrin, September 1995 - F. Auger, April 1996.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif f1<=0 | f2<=0,\n error('F1 and F2 must be >0');\nend\n[rt1,ct1]=size(t1);\n[rt2,ct2]=size(t2);\n[rf1,cf1]=size(f1);\n[rf2,cf2]=size(f2);\nif (rt1~=rt2|rt1~=rf1|rt1~=rf2) | (ct1~=ct2|ct1~=cf1|ct1~=cf2), \n error('T1, T2, F1 and F2 must have the same size');\nend\nif rt1>ct1,\n error('T1 must be a row-vector');\nelseif rt2>ct2,\n error('T2 must be a row-vector');\nelseif rf2>cf2,\n error('F2 must be a row-vector');\nelseif rf1>cf1,\n error('F1 must be a row-vector');\nend\n \nif (k==2),\n fi=(f1+f2)/2;\n ti=(t1+t2)/2;\nelseif (k==inf),\n ti=[t1;t2];\n fi=[f2;f1];\nelse\n I=find(abs(f1-f2)>sqrt(eps));\n if length(I)~=0, \n if (k==1),\n fi(I)=exp( (f1(I).*(log(f1(I))-1)-f2(I).*(log(f2(I))-1)) ./ ...\n \t(f1(I)-f2(I))); \n ti(I)=(t1(I).*f1(I)-t2(I).*f2(I)) ./ (f1(I)-f2(I)) - ...\n \t(t1(I)-t2(I)) ./ (log(f1(I))-log(f2(I)));\n elseif (k==0),\n fi(I)=(f1(I)-f2(I))./(log(f1(I))-log(f2(I)));\n ti(I)=(t1(I).*f1(I)-t2(I).*f2(I)) ./ (f1(I)-f2(I)) + ...\n f1(I) .* f2(I) .* (t2(I)-t1(I)) .* ...\n \t(log(f1(I))-log(f2(I))) ./ (f2(I)-f1(I)).^2; \n else\n t0(I)=(t1(I).*f2(I).^(k-1)-t2(I).*f1(I).^(k-1)) ./ ...\n \t(f2(I).^(k-1)-f1(I).^(k-1));\n fi(I)=((f1(I).^k-f2(I).^k) ./ (f1(I)-f2(I))/k).^(1/(k-1));\n ti(I)=t0(I)+(t2(I)-t1(I)) ./ (f2(I).^(k-1)-f1(I).^(k-1)) .*fi(I).^(k-1);\n end\n end\nend\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/midpoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7994111367417014}} {"text": "% KM_DEMO_KCCA Demo file for kernel canonical correlation analysis\n% algorithm.\n%\n% This script takes two multi-dimensional variables and uses kernel CCA to\n% map them onto a single latent 1-D variable. The kernel matrices are \n% decomposed using incomplete Cholesky decomposition in order to allow \n% large data sets. This demo includes 3 flavors of the KCCA generalized\n% eigenvalue problem, all yielding very similar results.\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2012.\n%\n% The algorithm in this file is based on the following publications: \n% D. R. Hardoon, S. Szedmak and J. Shawe-Taylor, \"Canonical Correlation \n% Analysis: An Overview with Application to Learning Methods\", Neural \n% Computation, Volume 16 (12), Pages 2639--2664, 2004.\n% F. R. Bach, M. I. Jordan, \"Kernel Independent Component Analysis\", Journal \n% of Machine Learning Research, 3, 1-48, 2002.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\nclose all; clear\nrs = 1; % seed for random generator\nrng('default')\nrng(rs)\n\n%% PARAMETERS\nN = 1000;\t% number of samples. method's complexity is O(NM^2)\nMmax = 50; % max. M (number of components in incomplete Cholesky decomp.)\nreg = 1E-5; % regularization\nkerneltype = 'gauss'; % kernel type\nkernelpar = 1; % kernel parameter\n\n%% PROGRAM\ntic\n\n% generate data\ns = randn(N,1);\t% latent signal\nr1 = randn(N,1); r2 = randn(N,1);\t% random (helper) variables\n\n% option 1: two multi-dimensional variables that are mappable onto s\nx1 = [tanh(r1-s)+0.1*r1 r1+3*s-1/10*(sin(3*s))];\nx2 = [s - 2*(1-exp(-r2))./(1+exp(-r2)) r2.*s tanh(r2+s)];\n\n% option 2: two invertible 1D nonlinear transformations\n% x1 = tanh(0.8*s)+0.1*s;\t% moderate saturation\n% x2 = -1/10*(sin(s*3)+1.1*s*3); % stairway\n\n% clean up: remove mean\nx1 = x1-repmat(mean(x1),N,1);\nx2 = x2-repmat(mean(x2),N,1);\n\n% normalize variance (to improve anisotropy) or any other preprocessing\nx1 = x1*sqrt(diag(1./diag(x1'*x1)));\nx2 = x2*sqrt(diag(1./diag(x2'*x2)));\n\n% KCCA\n[y1,y2,beta] = km_kcca(x1,x2,kerneltype,kernelpar,reg,1,'ICD',Mmax);\n\n% scale the estimated signals to compare without the scalar ambiguity\nscaling = sqrt(var(s))/sqrt(var(y1))*sign(s(1))*sign(y1(1));\n\n% mean square errors\nerror1 = s-scaling*y1;\nerror2 = s-scaling*y2;\nMSE1 = sum(error1.^2)/N;\nMSE2 = sum(error2.^2)/N;\n\ntoc\n%% OUTPUT\n\nfigure; hold all\nplot(s)\nplot(scaling*y1);\nplot(scaling*y2);\nlegend('latent variable','projection 1','projection 2')\n\nfprintf('2x %d data points\\n',N)\nfprintf('Canonical correlation: %f\\n',beta)\nfprintf('MSE1: %f\\n',MSE1);\nfprintf('MSE2: %f\\n',MSE2);\nfprintf('\\n')\n\n% figure;plot(sort(diag(real(betas)))) % check eigenvalues\n% figure;plot(sort(diag(betas))); % imaginary part due to numerical error\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_kcca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.7993391974567866}} {"text": "%HOMLINE Homogeneous line from two points\n%\n% L = HOMLINE(X1, Y1, X2, Y2) is a vector (3x1) which describes a line in\n% homogeneous form that contains the two Euclidean points (X1,Y1) and (X2,Y2).\n%\n% Homogeneous points X (3x1) on the line must satisfy L'*X = 0.\n%\n% See also PLOT_HOMLINE.\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 .\n%\n% http://www.petercorke.com\n\n% TODO, probably should be part of a HomLine class.\n\nfunction l = homline(x1, y1, x2, y2)\n\n l = cross([x1 y1 1], [x2 y2 1]);\n\n % normalize so that the result of x*l' is the pixel distance\n % from the line\n l = l / norm(l(1:2));\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/homline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.799237388741176}} {"text": "function voronoi_neighbor_test01 ( )\n\n%*****************************************************************************80\n%\n%% VORONOI_NEIGHBOR_TEST01 demonstrates VORONOI_NEIGHBORS\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'VORONOI_NEIGHBORS_TEST01:\\n' );\n fprintf ( 1, ' Select a random set of points in the unit square.\\n' );\n fprintf ( 1, ' Compute the Voronoi diagram.\\n' );\n fprintf ( 1, ' Have VORONOI_NEIGHBORS determine the neighbors.\\n' );\n\n n = 8;\n x = rand ( n, 2 );\n%\n% Compute and display the Voronoi diagram.\n%\n figure ( );\n\n hold on\n voronoi ( x(:,1), x(:,2) );\n for i = 1 : n\n txt = sprintf ( '%d', i );\n text ( x(i,1), x(i,2), txt, 'FontSize', 12 );\n end\n hold off\n\n filename = 'voronoi_neighbors_test01.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Voronoi diagram saved as \"%s\".\\n', filename );\n%\n% Compute and list the finite Voronoi edges.\n%\n [ V, C ] = voronoin ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Voronoi edges:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : length ( C )\n disp ( C{i} )\n end\n%\n% Compute the Voronoi neighbors.\n%\n vn = voronoi_neighbors ( x );\n%\n% To print the matrix, make a full version.\n%\n vn = full ( vn );\n i4mat_print ( n, n, vn, ' Voronoi adjacency:' )\n\n return\nend\n\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/voronoi_neighbors/voronoi_neighbors_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.7991020251672709}} {"text": "function y = trapmf(x, params)\n%TRAPMF Trapezoidal membership function.\n% TRAPMF(X, PARAMS) returns a matrix which is the trapezoidal\n% membership function evaluated at X. PARAMS = [A B C D] is a 4-element\n% vector that determines the break points of this membership function.\n% We require that A <= B and C <= D. If B >= C, this membership\n% function becomes a triangular membership function that could have\n% a height less than unity. (See the example below.)\n%\n% For example:\n%\n% x = (0:0.1:10)';\n% y1 = trapmf(x, [2 3 7 9]);\n% y2 = trapmf(x, [3 4 6 8]);\n% y3 = trapmf(x, [4 5 5 7]);\n% y4 = trapmf(x, [5 6 4 6]);\n% plot(x, [y1 y2 y3 y4]);\n% set(gcf, 'name', 'trapmf', 'numbertitle', 'off');\n%\n% See also DSIGMF, EVALMF, GAUSS2MF, GAUSSMF, GBELLMF, MF2MF, PIMF, PSIGMF,\n% SIGMF, SMF, TRIMF, ZMF.\n\n% Roger Jang, 6-28-93, 10-5-93, 4-14-94.\n% Copyright 1994-2002 The MathWorks, Inc. \n% $Revision: 1.22 $ $Date: 2002/04/14 22:21:13 $\n\nif nargin ~= 2\n error('Two arguments are required by the trapezoidal MF.');\nelseif length(params) < 4\n error('The trapezoidal MF needs at least four parameters.');\nend\n\na = params(1); b = params(2); c = params(3); d = params(4);\n\nif a > b,\n error('Illegal parameter condition: a > b');\nelseif c > d,\n error('Illegal parameter condition: c > d');\nend\n\ny1 = zeros(size(x));\ny2 = zeros(size(x));\n\n% Compute y1\nindex = find(x >= b);\nif ~isempty(index),\n y1(index) = ones(size(index));\nend\nindex = find(x < a);\nif ~isempty(index),\n y1(index) = zeros(size(index));\nend\nindex = find(a <= x & x < b);\nif ~isempty(index) & a ~= b,\n y1(index) = (x(index)-a)/(b-a);\nend\n\n% Compute y2\nindex = find(x <= c);\nif ~isempty(index),\n y2(index) = ones(size(index));\nend\nindex = find(x > d);\nif ~isempty(index),\n y2(index) = zeros(size(index));\nend\nindex = find(c < x & x <= d);\nif ~isempty(index) & c ~= d,\n y2(index) = (d-x(index))/(d-c);\nend\n\n% Compute y\ny = min(y1, y2);\n", "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/External/Matlab/trapmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.799099715351165}} {"text": "function [ w, xy ] = triangle_unit_o03 ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_UNIT_O03 returns a 3 point quadrature rule for the unit triangle.\n%\n% Discussion:\n%\n% This rule is precise for monomials through degree 2.\n%\n% The integration region is:\n%\n% 0 <= X\n% 0 <= Y\n% X + Y <= 1.\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% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Output, real W(3), the weights.\n%\n% Output, real XY(2,3), the abscissas.\n%\n w(1:3,1) = [ ...\n 0.33333333333333333333, ...\n 0.33333333333333333333, ...\n 0.33333333333333333333 ];\n\n xy(1:2,1:3) = [ ...\n 0.66666666666666666667, 0.16666666666666666667; ...\n 0.16666666666666666667, 0.66666666666666666667; ...\n 0.16666666666666666667, 0.16666666666666666667 ]';\n return\nend\n", "meta": {"author": "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_felippa_rule/triangle_unit_o03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7990062334702103}} {"text": "function r = trirnd(varargin)\n%TRIRND Pseudorandom numbers drawn from the triangular distribution\n% \n% R = IOSR.STATISTICS.TRIRND(N) returns an N-by-N matrix containing\n% pseudorandom values drawn from the triangular distribution constrained\n% to (-1,1) and mode = 0.\n% \n% IOSR.STATISTICS.TRIRND(M,N) or IOSR.STATISTICS.TRIRND([M,N]) returns an\n% M-by-N matrix.\n% \n% IOSR.STATISTICS.TRIRND(M,N,P,...) or\n% IOSR.STATISTICS.TRIRND([M,N,P,...]) returns an M-by-N-by-P-by-...\n% array.\n% \n% IOSR.STATISTICS.TRIRND returns a scalar.\n% \n% TRIRND(SIZE(A)) returns an array the same size as A.\n%\n% Note: The size inputs M, N, P, ... should be nonnegative integers.\n% Negative integers are treated as 0.\n%\n% The sequence of numbers produced by TRIRND is determined by the\n% settings of the uniform random number generator that underlies RAND,\n% RANDI, and RANDN. Control that shared random number generator using\n% RNG.\n% \n% See also IOSR.STATISTICS.LAPRND, RAND, RANDN, RANDI, RNG.\n\n% Based on code (Matlab FE File ID: #13705) written by Elvis Chen, 2007.\n\n% Copyright 2016 University of Surrey.\n\n % Generate traingular noise\n u1 = rand(varargin{:})-0.5;\n u2 = rand(varargin{:})-0.5;\n r = u1+u2;\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/+statistics/trirnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7989589198984113}} {"text": "%% Structured grid\n% This is a sample code showing how to use ConstructProjector2D().\n% This example is going to setup a transformation matrix based on forth\n% order polynomials in 2D. \n% Pay attention that no data is needed to construct the interpolator. Only\n% the coordinates of the points on source and destination grid.\nclear;clc;\n%% Initializing Part I\ndisp('- Initializing')\nxMin=0;\nxMax=2*pi;\nyMin=0;\nyMax=2*pi;\n\nnx=40;\nny=40;\n\nnPoly=4; % We gonna fit a fourth order polynomial, \n % i.e. sum_{n,m=0}^{n,m=nPoly} x^n*y^m \nnInterp=30; % nPoly=4 requires 25 points. However, \n % we are going to use 30 points. This would be \n % the least-square fit of the surface.\n % Note that: min(nInterp)=(nPoly+1)^2. Otherwise it won't work.\n%% Turning off the warnings\n% Depending on the parameter that you choose the matrices might be nearly\n% singular. In this example, despite being nearly singular, they are not \n% affecting the final interpolation. Therefore, I set the warning to off. \n% But generally do not turn it off and if you got this warning check if it \n% is going to affect your results or not.\ndisp('- Turning the warnings off')\nwarning('OFF','MATLAB:nearlySingularMatrix');\n\n%% Generating the Source Grid\ndisp('- Generating the source grid.')\n[xn,yn]=meshgrid(linspace(xMin,xMax,nx),linspace(yMin,yMax,ny));\n\n%% Finding the cell centers\ndisp('- Generating the destination grid')\nxc=(xn(1:ny-1,1:nx-1)+xn(2:ny,1:nx-1)+xn(1:ny-1,2:nx)+xn(2:ny,2:nx))*0.25;\nyc=(yn(1:ny-1,1:nx-1)+yn(2:ny,1:nx-1)+yn(1:ny-1,2:nx)+yn(2:ny,2:nx))*0.25;\n\nfigure\nsurface(xn,yn,zeros(size(xn)));\nhold on\nplot(xn,yn,'k.');\nplot(xc,yc,'b.');\naxis tight;\naxis square;\ntitle('Source Grid, black dots, & the destination grid, blue dots.', ...\n 'FontName','Arial','FontSize',12,'FontWeight','Bold');\n%% Constructing the Interpolant\n% Note: that we do not need the data on the source grid to create the\n% interpolant.\ndisp('- Constructing the interpolant')\nP=ConstructProjector2D(xn(:),yn(:),xc(:),yc(:),nPoly,nInterp);\n\n%% Generarting some Data\ndisp('- Generating some data and interpolating')\nF1=@(x,y) (sin(sqrt(x.^2+y.^2)));\nzn=F1(xn,yn);\nzc_interp=reshape(P*zn(:),size(xc));\nzc_Analytic=F1(xc,yc);\nRMSE=sqrt(mean((zc_Analytic(:)-zc_interp(:)).^2));\n\nfigure\nsurface(xc,yc,zc_interp,'EdgeColor','none');\ntitle(['nPoly: ' num2str(nPoly) ', RMSE= ' num2str(RMSE)]);\naxis tight\n\n%% Generating some more data\ndisp('- Generating multiple data field on the source grid and interpolating them.')\nF2=@(x,y) (sin(x).*cos(y));\nF3=@(x,y) (exp(-sqrt(x.^2+y.^2)));\nF4=@(x,y,x0,y0) (exp(-sqrt((x-x0).^2+(y-y0).^2)));\n\nzn(:,:,1)=F1(xn,yn);\nzn(:,:,2)=F2(xn,yn);\nzn(:,:,3)=F3(xn,yn);\nzn(:,:,4)=F4(xn,yn,mean(mean(xn)),mean(mean(yn)));\n\nzc_Analytic(:,:,1)=F1(xc,yc);\nzc_Analytic(:,:,2)=F2(xc,yc);\nzc_Analytic(:,:,3)=F3(xc,yc);\nzc_Analytic(:,:,4)=F4(xc,yc,mean(mean(xn)),mean(mean(yn)));\n\n% Now interpolating\n% Note that the same interpolant is used for all data fields and they can\n% be all interpolated with one sparse matrix multiplication.\nzc_interp=P*reshape(zn,nx*ny,4); % There are 4 data fields.\nzc_interp=reshape(zc_interp,(nx-1),(ny-1),4); % these two commands can be combined in one.\n % They were separated for clarity.\n\n% calculating the RMSE and plotting\nRMSE=zeros(4,1);\nfigure\nfor i=1:4\n RMSE(i)=sqrt(mean((reshape(zc_Analytic(:,:,i),(nx-1)*(ny-1),1)-reshape(zc_interp(:,:,i),(nx-1)*(ny-1),1)).^2));\n subplot(2,2,i);\n surface(xc,yc,squeeze(zc_interp(:,:,i)),'EdgeColor','none');\n title(['F' num2str(i) ', nPoly: ' num2str(nPoly) ', RMSE:' num2str(RMSE(i))])\n axis tight\n axis square\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/41669-interpolantextrapolant-2d3d-data/Projector/Test_StructuredGrid_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.798958904656929}} {"text": "function values = coeffs2vals(coeffs)\n%COEFFS2VALS Convert Fourier coefficients to values at N equally spaced\n%points between [-1 1), where N is the number of coefficients.\n% V = COEFFS2VALS(C) returns the values of the trignometric polynomial \n% as follows:\n% If N is odd\n% F(x) = C(1)*z^(-(N-1)/2) + C(2)*z^(-(N-1)/2-1) + ... + C(N)*z^((N-1)/2)\n% If N is even\n% F(x) = C(1)*z^(-N/2) + C(2)*z^(-N/2+1) + ... + C(N)*z^(N/2-1)\n% where z = exp(1i*pi*x) and -1 <= x <= 1. \n%\n% If the input C is an (N+1)xM matrix then V = COEFFS2VALS(C) returns the\n% (N+1)xM matrix of values V such that V(i,j) is the ith value of the\n% trignometric polynomial corresponding to the jth column.\n%\n% See also VALS2COEFFS, TRIGPTS.\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 about symmetry*. Some of the code below is designed to\n% enforce two symmetries whose failure might disturb users:\n% COEFFS exactly real ==> VALUES exactly hermitian\n% COEFFS exactly imaginary ==> VALUES exactly skew-hermitian\n% This is necessary because the MATLAB FFT code does not\n% exactly preserve symmetries.\n\n% Get the length of the input:\nn = size(coeffs, 1);\n\n% Trivial case (constant or empty):\nif ( n <= 1 )\n values = coeffs; \n return\nend\n\n% The coefficients are for interpolation defined on [-pi,pi), but the FFT\n% works for values on [0,2*pi). To fix the coefficients for this we just need to\n% assign c_k = (-1)^k c_k, with k=-(N-1)/2:(N-1)/2 for N odd, and \n% k = -N/2:N/2-1 for N even.\nif ( mod(n, 2) ) \n even_odd_fix = (-1).^(-(n-1)/2:(n-1)/2).';\nelse\n even_odd_fix = (-1).^((-n/2):(n/2-1)).';\nend\ncoeffs = bsxfun(@times, coeffs, even_odd_fix);\n\n% test for symmetry\nisHerm = max(abs(imag(coeffs)),[],1) == 0;\nisSkew = max(abs(real(coeffs)),[],1) == 0;\n\n% Shift the coefficients properly.\nvalues = ifft(ifftshift(n*coeffs, 1), [], 1);\n\n% correct if symmetric\nvals = [values;values(1,:)];\nhermvals = (vals+flipud(conj(vals)))/2;\nskewvals = (vals-flipud(conj(vals)))/2;\nvalues(:,isHerm) = hermvals(1:end-1,isHerm);\nvalues(:,isSkew) = skewvals(1:end-1,isSkew);\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/coeffs2vals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.7989541657086147}} {"text": "function OUT = datatreat(DATA,vtreat,nlag)\n% =======================================================================\n% Treat a time series with the specified method. If changes are computed\n% the function assumes 1 lag (unless otherwise specified)\n% =======================================================================\n% OUT = datatreat(DATA,vtreat,lag)\n% -----------------------------------------------------------------------\n% INPUT\n%\t- DATA: matrix DATA(T,N)\n% - vtreat: 0 No treatment \n% 1\tLog\n% 2 Difference\n% 3\tLog Difference\n% 4 Percent change\n% -----------------------------------------------------------------------\n% OPTIONAL INPUT\n% - lag: number of lags for changes\n% -----------------------------------------------------------------------\n% OUTPUT\n%\t- OUT: matrix DATA(T,N) of treated data. The first \"nlag\"\n% observations are NaNs\n% -----------------------------------------------------------------------\n% EXAMPLE\n% x = [1 2; -3 4; 5 6; 7 8; 9 10];\n% OUT = datatreat(x,3)\n% =======================================================================\n% VAR Toolbox 3.0\n% Ambrogio Cesa-Bianchi\n% ambrogiocesabianchi@gmail.com\n% March 2012. Updated November 2020\n% -----------------------------------------------------------------------\n\n% Check input\nif ~exist('nlag','var')\n nlag = 1;\nend\n\n% Set matrices\n[nobs, nvar] = size(DATA);\nOUT = nan(nobs,nvar);\n\n% No treatment\nif vtreat==0\n OUT = DATA;\n\n% Log\nelseif vtreat==1\n if ~isempty(DATA<0), warning('Negative numbers set to NaN before taking logs'), end\n DATA(DATA<0) = NaN;\n OUT = log(DATA);\n \n% Difference\nelseif vtreat==2\n OUT(nlag+1:end,:) = DATA(1+nlag:end,:) - DATA(1:end-nlag,:);\n \n% Log difference\nelseif vtreat==3\n if ~isempty(DATA<0), warning('Negative numbers set to NaN before taking logs'), end\n DATA(DATA<0) = NaN;\n OUT(nlag+1:end,:) = log(DATA(1+nlag:end,:))-log(DATA(1:end-nlag,:));\n\n% Percent change\nelseif vtreat==4\n OUT(nlag+1:end,:) = DATA(1+nlag:end,:)./DATA(1:end-nlag,:)-1;\nend\n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/v3dot0/Utils/datatreat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7988992646177332}} {"text": "function kappa = surfaceCurvature(kappa1, kappa2, theta)\n%SURFACECURVATURE Curvature on a surface from angle and principal curvatures.\n%\n% usage:\n% KAPPA = surfaceCurvature(KAPPA1, KAPPA2, THETA)\n% return the curvature KAPPA of surface with respect to direction THETA.\n\n% KAPPA1 and KAPPA2 are the principal curvatures of the surface at the\n% considered point. THETA is angle of direction relative to angle of\n% first principal curvature KAPPA1.\n%\n% Examples:\n% K = surfaceCurvature(KAPPA1, KAPPA2, 0) returns KAPPA1.\n% K = surfaceCurvature(KAPPA1, KAPPA2, pi/2) returns KAPPA2.\n%\n%\n% ---------\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 07/04/2004.\n%\n\n% HISTORY\n% 20/04/2004 change name and add doc.\n% 14/06/2004 correct creation date\n\nkappa = kappa1 * cos(theta).^2 + kappa2 * sin(theta).^2;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/surfaceCurvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7988778386829933}} {"text": "function [f,P,prob] = lomb(t,h,ofac,hifac)\n% LOMB(T,H,OFAC,HIFAC) computes the Lomb normalized periodogram (spectral\n% power as a function of frequency) of a sequence of N data points H,\n% sampled at times T, which are not necessarily evenly spaced. T and H must\n% be vectors of equal size. The routine will calculate the spectral power\n% for an increasing sequence of frequencies (in reciprocal units of the\n% time array T) up to HIFAC times the average Nyquist frequency, with an\n% oversampling factor of OFAC (typically >= 4).\n% \n% The returned values are arrays of frequencies considered (f), the\n% associated spectral power (P) and estimated significance of the power\n% values (prob). Note: the significance returned is the false alarm\n% probability of the null hypothesis, i.e. that the data is composed of\n% independent gaussian random variables. Low probability values indicate a\n% high degree of significance in the associated periodic signal.\n% \n% Although this implementation is based on that described in Press,\n% Teukolsky, et al. Numerical Recipes In C, section 13.8, rather than using\n% trigonometric rercurrences, this takes advantage of MATALB's array\n% operators to calculate the exact spectral power as defined in equation\n% 13.8.4 on page 577. This may cause memory issues for large data sets and\n% frequency ranges.\n% \n% Example \n% [f,P,prob] = lomb(t,h,4,1); \n% plot(f,P)\n% [Pmax,jmax] = max(P)\n% disp(['Most significant period is ',num2str(1/f(jmax)),...\n% ' with FAP of ',num2str(prob(jmax))])\n% \n% Written by Dmitry Savransky 21 May 2008\n\n%sample length and time span\nN = length(h);\nT = max(t) - min(t);\n\n%mean and variance \nmu = mean(h);\ns2 = var(h);\n\n%calculate sampling frequencies\nf = (1/(T*ofac):1/(T*ofac):hifac*N/(2*T)).';\n\n%angular frequencies and constant offsets\nw = 2*pi*f;\ntau = atan2(sum(sin(2*w*t.'),2),sum(cos(2*w*t.'),2))./(2*w);\n\n%spectral power\ncterm = cos(w*t.' - repmat(w.*tau,1,length(t)));\nsterm = sin(w*t.' - repmat(w.*tau,1,length(t)));\nP = (sum(cterm*diag(h-mu),2).^2./sum(cterm.^2,2) + ...\n sum(sterm*diag(h-mu),2).^2./sum(sterm.^2,2))/(2*s2);\n\n%estimate of the number of independent frequencies\nM=2*length(f)/ofac;\n\n%statistical significane of power\nprob = M*exp(-P);\ninds = prob > 0.01;\nprob(inds) = 1-(1-exp(-P(inds))).^M;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20004-lomb-lomb-scargle-periodogram/lomb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7988778337972019}} {"text": "function value = normal_ms_moment ( order, mu, sigma )\n\n%*****************************************************************************80\n%\n%% NORMAL_MS_MOMENT evaluates moments of the Normal PDF.\n%\n% Discussion:\n%\n% The formula was posted by John D Cook.\n%\n% Order Moment\n% ----- ------\n% 0 1\n% 1 mu\n% 2 mu^2 + sigma^2\n% 3 mu^3 + 3 mu sigma^2\n% 4 mu^4 + 6 mu^2 sigma^2 + 3 sigma^4\n% 5 mu^5 + 10 mu^3 sigma^2 + 15 mu sigma^4\n% 6 mu^6 + 15 mu^4 sigma^2 + 45 mu^2 sigma^4 + 15 sigma^6\n% 7 mu^7 + 21 mu^5 sigma^2 + 105 mu^3 sigma^4 + 105 mu sigma^6\n% 8 mu^8 + 28 mu^6 sigma^2 + 210 mu^4 sigma^4 + 420 mu^2 sigma^6 + 105 sigma^8\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the moment.\n% 0 <= ORDER.\n%\n% Input, real MU, the mean of the distribution.\n%\n% Input, real SIGMA, the standard deviation of the distribution.\n%\n% Output, real VALUE, the value of the central moment.\n%\n j_hi = floor ( order / 2 );\n\n value = 0.0;\n for j = 0 : j_hi\n value = value ...\n + r8_choose ( order, 2 * j ) ...\n * r8_factorial2 ( 2 * j - 1 ) ...\n * mu ^ ( order - 2 * j ) * sigma ^ ( 2 * 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/truncated_normal/normal_ms_moment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331956, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.798877831688011}} {"text": "function corr_coef = RegreesionTID2013(objectiveValues,mos)\n%this script is used to calculate the pearson linear correlation\n%coefficient and root mean sqaured error after regression\n\n%get the objective scores computed by the IQA metric and the subjective\n%scores provided by the dataset\n% matData = load('VSIOnTID2013.mat');\n% VSIOnTID2013 = matData.VSIOnTID2013;\n% objectiveValues = VSIOnTID2013(:,1);\n% mos = VSIOnTID2013(:,2);\n\n%plot objective-subjective score pairs\n% p = plot(objectiveValues,mos,'+');\n% set(p,'Color','blue','LineWidth',1);\n\n%initialize the parameters used by the nonlinear fitting function\nbeta(1) = 10;\nbeta(2) = 0;\nbeta(3) = mean(objectiveValues);\nbeta(4) = 0.1;\nbeta(5) = 0.1;\n%fitting a curve using the data\n[bayta ehat,J] = nlinfit(objectiveValues,mos,@logistic,beta);\n%given an objective value, predict the correspoing mos (ypre) using the fitted curve\n[ypre junk] = nlpredci(@logistic,objectiveValues,bayta,ehat,J);\n\nRMSE = sqrt(sum((ypre - mos).^2) / length(mos));%root meas squared error\ncorr_coef = corr(mos, ypre, 'type','Pearson'); %pearson linear coefficient\n\n%draw the fitted curve\n% t = min(objectiveValues):0.01:max(objectiveValues);\n% [ypre junk] = nlpredci(@logistic,t,bayta,ehat,J);\n% hold on;\n% p = plot(t,ypre);\n% set(p,'Color','black','LineWidth',2);\n% legend('Images in TID2013','Curve fitted with logistic function', 'Location','NorthWest');\n% xlabel('Objective score by VSI');\n% ylabel('MOS');\n\n", "meta": {"author": "HuiZeng", "repo": "BIQA_Toolbox", "sha": "39d606574f0cbfde82ecbc3c208b353d9fa9a450", "save_path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox", "path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox/BIQA_Toolbox-39d606574f0cbfde82ecbc3c208b353d9fa9a450/tools/NonlinearFitting/RegressionTID2013.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7988778306273879}} {"text": "function prob_test094 ( )\n\n%*****************************************************************************80\n%\n%% TEST094 tests INVERSE_GAUSSIAN_MEAN, INVERSE_GAUSSIAN_SAMPLE, INVERSE_GAUSSIAN_VARIANCE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n nsample = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST094\\n' );\n fprintf ( 1, ' For the Inverse Gaussian PDF:\\n' );\n fprintf ( 1, ' INVERSE_GAUSSIAN_MEAN computes the mean;\\n' );\n fprintf ( 1, ' INVERSE_GAUSSIAN_SAMPLE samples;\\n' );\n fprintf ( 1, ' INVERSE_GAUSSIAN_VARIANCE computes the variance.\\n' );\n\n a = 2.0;\n b = 3.0;\n\n check = inverse_gaussian_check ( a, b );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST094 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n mean = inverse_gaussian_mean ( a, b );\n variance = inverse_gaussian_variance ( a, b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF parameter B = %14f\\n', b );\n fprintf ( 1, ' PDF mean = %14f\\n', mean );\n fprintf ( 1, ' PDF variance = %14f\\n', variance );\n\n for i = 1 : nsample\n [ x(i), seed ] = inverse_gaussian_sample ( a, b, seed );\n end\n\n mean = r8vec_mean ( nsample, x );\n variance = r8vec_variance ( nsample, x );\n xmax = max ( x(1:nsample) );\n xmin = min ( x(1:nsample) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sample size = %6d\\n', nsample );\n fprintf ( 1, ' Sample mean = %14f\\n', mean );\n fprintf ( 1, ' Sample variance = %14f\\n', variance );\n fprintf ( 1, ' Sample maximum = %14f\\n', xmax );\n fprintf ( 1, ' Sample minimum = %14f\\n', xmin );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/prob_test094.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7988778233702638}} {"text": "function interp_Function_Coeffs(x1,x2)\n\n\nmat1 = [1 0 0 0 0 0 0 0 0 0 0 0];\nmat2 = [0 1 0 0 0 0 0 0 0 0 0 0];\nmat3 = [0 0 1 0 0 0 0 0 0 0 0 0];\nmat4 = [1 x1 x1^2 x1^3 -1 -x1 -x1^2 -x1^3 0 0 0 0];\nmat5 = [0 1 2*x1 3*x1^2 0 -1 -2*x1 -3*x1^2 0 0 0 0];\nmat6 = [0 0 2 6*x1 0 0 -2 -6*x1 0 0 0 0];\n\nmat7 = [0 0 0 0 1 x2 x2^2 x2^3 -1 -x2 -x2^2 -x2^3];\nmat8 = [0 0 0 0 0 1 2*x2 3*x2^2 0 -1 -2*x2 -3*x2^2];\nmat9 = [0 0 0 0 0 0 2 6*x2 0 0 -2 -6*x2];\n\nmat10= [0 0 0 0 0 0 0 0 1 1 1 1];\nmat11= [0 0 0 0 0 0 0 0 0 1 2 3];\nmat12= [0 0 0 0 0 0 0 0 0 0 2 6];\n\nmat = [mat1; mat2; mat3; mat4; mat5; mat6; mat7; mat8; mat9; mat10; mat11; mat12];\n\nrhs = [0 0 0 0 0 0 0 0 0 1 0 0]';\n\n%mat1 = [-x1^2 0 x1^3 x1^2 x1 1];\n%mat2 = [-2*x1 0 3*x1^2 2*x1 1 0];\n%mat3 = [-2 0 6*x1 2 0 0];\n%mat4 = [0 (x2-1)^2 x2^3 x2^2 x2 1];\n%mat5 = [0 2*(x2-1) 3*x2^2 2*x2 1 0];\n%mat6 = [0 2 6*x2 2 0 0];\n%mat = [mat1; mat2; mat3; mat4; mat5; mat6];\n%rhs = [0 0 0 1 0 0]';\n\ncoeffs = mat\\rhs\n\n\n\na0 = coeffs(1);\na1 = coeffs(2); \na2 = coeffs(3);\na3 = coeffs(4);\nb0 = coeffs(5); \nb1 = coeffs(6);\nb2 = coeffs(7);\nb3 = coeffs(8); \nc0 = coeffs(9);\nc1 = coeffs(10);\nc2 = coeffs(11); \nc3 = coeffs(12);\n\nds = 0.01;\nx = 0:ds:1;\n\nfigure(1)\nfor i=1:length(x)\n plot(x(i),g(coeffs,x(i),x1,x2),'*'); hold on;\nend\n\n\nfigure(2)\nfor i=1:length(x)\n plot(x(i),gP(coeffs,x(i),x1,x2),'*'); hold on;\nend\n\nfigure(3)\nfor i=1:length(x)\n plot(x(i),gPP(coeffs,x(i),x1,x2),'*'); hold on;\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = g(coeffs,x,x1,x2)\n\nif x<=x1\n val = coeffs(1) + coeffs(2)*x + coeffs(3)*x^2 + coeffs(4)*x^3;\nelseif x<=x2\n val = coeffs(5) + coeffs(6)*x + coeffs(7)*x^2 + coeffs(8)*x^3;\nelse\n val = coeffs(9) + coeffs(10)*x + coeffs(11)*x^2 + coeffs(12)*x^3;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial 1st derivative\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = gP(coeffs,x,x1,x2)\n\nif x<=x1\n val = coeffs(2) + 2*coeffs(3)*x + 3*coeffs(4)*x^2;\nelseif x<=x2\n val = coeffs(6) + 2*coeffs(7)*x + 3*coeffs(8)*x^2;\nelse\n val = coeffs(10) + 2*coeffs(11)*x + 3*coeffs(12)*x^2;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial 2nd derivative\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = gPP(coeffs,x,x1,x2)\n\nif x<=x1\n val = 2*coeffs(3) + 6*coeffs(4)*x;\nelseif x<=x2\n val = 2*coeffs(7) + 6*coeffs(8)*x;\nelse\n val = 2*coeffs(11) + 6*coeffs(12)*x;\nend\n\n% \n% figure(1)\n% for i=1:length(x1_part)\n% x = x1_part(i);\n% plot(x,a*x^2,'ro'); hold on;\n% end\n% \n% for i=1:length(x2_part)\n% x = x2_part(i);\n% plot(x,c*x^3+d*x^2+g*x+h,'*'); hold on;\n% end\n% \n% for i=1:length(x3_part)\n% x = x3_part(i);\n% plot(x,-b*(x-1)^2+1,'go'); hold on;\n% end\n% \n% xtotal = 0:ds:1;\n% for i=1:length(xtotal)\n% x = xtotal(i);\n% plot(x,0.5*(1+tanh(4.3*(x-0.5))),'m*'); hold on;\n% end\n% title('function vals');\n% \n% \n% figure(2)\n% for i=1:length(x1_part)\n% x = x1_part(i);\n% plot(x,2*a*x,'ro'); hold on;\n% end\n% \n% for i=1:length(x2_part)\n% x = x2_part(i);\n% plot(x,3*c*x^2+2*d*x+g,'*'); hold on;\n% end\n% \n% for i=1:length(x3_part)\n% x = x3_part(i);\n% plot(x,-2*b*(x-1),'go'); hold on;\n% end\n% title('1st deriv');\n% \n% \n% figure(3)\n% for i=1:length(x1_part)\n% x = x1_part(i);\n% plot(x,2*a,'ro'); hold on;\n% end\n% \n% for i=1:length(x2_part)\n% x = x2_part(i);\n% plot(x,6*c*x+2*d,'*'); hold on;\n% end\n% \n% for i=1:length(x3_part)\n% x = x3_part(i);\n% plot(x,-2*b,'go'); hold on;\n% end\n% title('2nd deriv');\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_Jellyfish_Swimming/Tethered_Jellyfish/600x400/interp_Function_Coeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.7988357708667638}} {"text": "function histmat = hist2D(x, y, xedges, yedges)\n% function histmat = hist2D(x, y, xedges, yedges)\n%\n% Extract 2D histogram data containing the number of events\n% of [x , y] pairs that fall in each bin of the grid defined by \n% xedges and yedges. The edges are vectors with monotonically \n% non-decreasing values. \n%\n%EXAMPLE \n%\n% events = 1000000;\n% x1 = sqrt(0.05)*randn(events,1)-0.5; x2 = sqrt(0.05)*randn(events,1)+0.5;\n% y1 = sqrt(0.05)*randn(events,1)+0.5; y2 = sqrt(0.05)*randn(events,1)-0.5;\n% x= [x1;x2]; y = [y1;y2];\n%\n%For linearly spaced edges:\n% xedges = linspace(-1,1,64); yedges = linspace(-1,1,64);\n% histmat = hist2(x, y, xedges, yedges);\n% figure; pcolor(xedges,yedges,histmat'); colorbar ; axis square tight ;\n%\n%For nonlinearly spaced edges:\n% xedges_ = logspace(0,log10(3),64)-2; yedges_ = linspace(-1,1,64);\n% histmat_ = hist2(x, y, xedges_, yedges_);\n% figure; pcolor(xedges_,yedges_,histmat_'); colorbar ; axis square tight ;\n\n% University of Debrecen, PET Center/Laszlo Balkay 2006\n% email: balkay@pet.dote.hu\n\nif nargin ~= 4\n error ('The four input arguments are required!');\n return;\nend\nif any(size(x) ~= size(y)) \n error ('The size of the two first input vectors should be same!');\n return;\nend\n\n[xn, xbin] = histc(x,xedges);\n[yn, ybin] = histc(y,yedges);\n\n%xbin, ybin zero for out of range values \n% (see the help of histc) force this event to the \n% first bins\nxbin(find(xbin == 0)) = inf;\nybin(find(ybin == 0)) = inf;\n\nxnbin = length(xedges);\nynbin = length(yedges);\n\nif xnbin >= ynbin\n xy = ybin*(xnbin) + xbin;\n indexshift = xnbin; \nelse\n xy = xbin*(ynbin) + ybin;\n indexshift = ynbin; \nend\n\n%[xyuni, m, n] = unique(xy);\nxyuni = unique(xy);\nxyuni(end) = []; \nhstres = histc(xy,xyuni);\nclear xy;\n\nhistmat = zeros(ynbin,xnbin);\nhistmat(xyuni-indexshift) = hstres;\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/utilities/hist2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7988357671527053}} {"text": "\n% Averaging Quaternions\n% Since quaternions are not regular vectors, but rather representations \n% of orientation, an average quaternion cannot just be obtained by taking \n% a weighted mean. This function implements the work done by paper by \n% F. Landis Merkley to calculate the average quaternion. The algorithm \n% explained by F. Landis Markley at: \n% http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf\n% For this particular implementation, I would also like to reference Mandar\n% Harshe:\n% http://www-sop.inria.fr/members/Mandar.Harshe/knee-joint/html/index.html\n%\n% This algorithm is compared by rotqrmean from VoiceBox and found to \n% produce quite similar results, yet it is more elegant, much simpler to \n% implement and follow. (Though, there might be difference in signs)\n%\n% Usage : \n% Q is an Mx4 matrix, where each row stores a quaternion to be averaged.\n% In return, the function outputs Qavg, which is a single quaternion\n% corresponding to the average.\n%\n% Tolga Birdal\n\nfunction [Qwavg]=weighted_avg_quat(Q, weights)\n\n% Form the symmetric accumulator matrix\nA=zeros(4,4);\nM=size(Q,1);\n\nfor i=1:M\n q=Q(i,:)';\n A=q*q'*weights(i)+A; % rank 1 update\nend\n\n% scale\nA=A/sum(weights);\n\n% Get the eigenvector corresponding to largest eigen value\n[Qwavg, Eval]=eigs(A,1);\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/ekfmonoslam/kinematics/weighted_avg_quat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.798822889149316}} {"text": "function M=axisAng2RotMat(u,theta,handed)\n%%AXISANG2ROTMAT Get a rotation matrix to rotate a 3D vector an angle of\n% theta counterlockwise (right-handed) or clockwise\n% (left-handed) about an axis given by the unit vector u.\n%\n%INPUTS: u A unit vector representing the axis about which a vector should\n% be rotated using the rotation matrix.\n% theta The angle in radians by which a vector is to be rotated is to be\n% rotated about the axis u when multiplied by the rotation matrix.\n% handed The handedness of the rotation angle. If omitted, it is assumed\n% that the rotation is right-handed (the standard). Possible\n% values are\n% 'right' The default if omitted. The rotation is right-handed.\n% 'left' The rotation is left-handed. The rotation angle is\n% counterclockwise when one is looking in the same\n% direction that the rotation axis points.\n%\n%OUTPUTS: M The rotation matrix such that M*v rotates the vector v by the\n% desired rotation.\n%\n%To rotate a 3D vector x an angle of theta about the axis u, simply\n%evaluate M*x.\n%\n%The rotation matrix is obtained by obtaining the unit quaternion for the\n%rotation and turning it into the corresponding rotation matrix as\n%described in [1].\n%\n%REFERENCES:\n%[1] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems\n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%December 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(handed))\n handed='right';\nend\n\nq=axisAng2Quat(u,theta);\nM=quat2RotMat(q,handed);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Rotations/axisAng2RotMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8791467690927439, "lm_q1q2_score": 0.7988084884283401}} {"text": "function [ a, more ] = compnz_next ( n, k, a, more )\n\n%*****************************************************************************80\n%\n%% COMPNZ_NEXT computes the compositions of the integer N into K nonzero parts.\n%\n% Discussion:\n%\n% A composition of the integer N into K nonzero parts is an ordered sequence\n% of K positive integers which sum to N. The compositions (1,2,1)\n% and (1,1,2) are considered to be distinct.\n%\n% The routine computes one composition on each call until there are no more.\n% For instance, one composition of 6 into 3 parts is 3+2+1, another would\n% be 4+1+1 but 5+1+0 is not allowed since it includes a zero part.\n%\n% On the first call to this routine, set MORE = FALSE. The routine\n% will compute the first element in the sequence of compositions, and\n% return it, as well as setting MORE = TRUE. If more compositions\n% are desired, call again, and again. Each time, the routine will\n% return with a new composition.\n%\n% However, when the LAST composition in the sequence is computed\n% and returned, the routine will reset MORE to FALSE, signaling that\n% the end of the sequence has been reached.\n%\n% Example:\n%\n% The 10 compositions of 6 into three nonzero parts are:\n%\n% 4 1 1, 3 2 1, 3 1 2, 2 3 1, 2 2 2, 2 1 3,\n% 1 4 1, 1 3 2, 1 2 3, 1 1 4.\n%\n% Modified:\n%\n% 01 December 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Albert Nijenhuis and Herbert Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, the integer whose compositions are desired.\n%\n% Input, integer K, the number of parts in the composition.\n% K must be no greater than N.\n%\n% Input, integer A(K), the previous composition. On the first call,\n% with MORE = FALSE, set A = []. Thereafter, A should be the \n% value of A output from the previous call.\n%\n% Input, logical MORE. The input value of MORE on the first\n% call should be FALSE, which tells the program to initialize.\n% On subsequent calls, MORE should be TRUE, or simply the\n% output value of MORE from the previous call.\n%\n% Output, integer A(K), the next composition.\n%\n% Output, logical MORE, will be TRUE unless the composition \n% that is being returned is the final one in the sequence.\n%\n persistent h;\n persistent t;\n%\n% We use the trick of computing ordinary compositions of (N-K)\n% into K parts, and adding 1 to each part.\n%\n if ( n < k )\n more = 0;\n a(1:k) = -1;\n return\n end\n\n if ( ~more )\n\n t = n - k;\n h = 0;\n a(1) = n - k;\n a(2:k) = 0;\n\n else\n\n a(1:k) = a(1:k) - 1;\n\n if ( 1 < t )\n h = 0;\n end\n\n h = h + 1;\n t = a(h);\n a(h) = 0;\n a(1) = t - 1;\n a(h+1) = a(h+1) + 1;\n\n end\n\n more = ( a(k) ~= ( n - k ) );\n\n a(1:k) = a(1:k) + 1;\n", "meta": {"author": "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/compnz_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.9086178895092415, "lm_q1q2_score": 0.7988084862175283}} {"text": "function c=cross7(a,b)\n%%CROSS7 Find the cross product of two 7-dimensional vectors. The cross\n% product has the properties:\n% 1) cross7(a,b) is a bilinear function of a and b.\n% 2) cross7(a,b) is perpendicular to both a and b.\n% Thus, dot(cross7(a,b),a)=0 and dot(cross7(a,b),b)=0\n% 3) norm(cross7(a,b))^2=norm(a)^2*norm(b)^2-dot(a,b)^2\n% Just as two forms of the 3D cross product exist (left-handed and\n% right-handed) 480 forms of the 7-dimensional cross product exist.\n% This function implements a cross product defined in terms of an\n% orthonormal basis using asymmetry as in [1].\n%\n%INPUTS: a A 7 by numVecs matrix of numVecs vectors.\n% b A 7 by numVecs matrix of numVecs vectors.\n%\n%OUTPUTS: c The 7 by numVecs cross products of a and b, aXb, for each of\n% the vectors in a and b.\n%\n%As noted in [2], it is only possible for a cross product between two\n%vectors to have all of the properties listed above in three and seven\n%dimensions. \n%\n%As noted in 1, the Jacobi identity does not hold. This means that\n%cross7(cross7(a,b),c)+cross7(cross7(b,c),a)+cross7(cross7(c,a),b) does\n%not necessarily equal zero. However, the following identities can be\n%proven:\n%cross7(a,b)=-cross7(b,a)\n%dot(a,cross7(b,c))=dot(b,cross7(c,a))=dot(c,cross7(a,b))\n%cross7(a,cross7(a,b))=dot(a,b)*a-norm(a)^2*b\n%cross7(cross7(a,b),cross7(a,c))=cross7(cross7(cross7(a,b),c),a)+cross7(cross7(cross7(b,c),a),a)+cross7(cross7(cross7(c,a),a),b)\n%\n%REFERENCES:\n%[1] P. Lounesto, \"Octonians and triality,\" Advances in Clifford Algebras,\n% vol. 11, no. 2, pp. 191-213, Dec. 2001.\n%[2] W. S. Massey, \"Cross products of vectors in higher dimensional\n% Euclidean spaces,\" The American Mathematical Monthly, vol. 90, no. 10,\n% pp. 697-701, Dec. 1983.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumVecs=size(a,2);\nc=zeros(7,numVecs);\n\nc(1,:)=+0 +a(2,:).*b(4,:) +a(3,:).*b(7,:) -a(4,:).*b(2,:) +a(5,:).*b(6,:) -a(6,:).*b(5,:) -a(7,:).*b(3,:);\nc(2,:)=-a(1,:).*b(4,:) +0 +a(3,:).*b(5,:) +a(4,:).*b(1,:) -a(5,:).*b(3,:) +a(6,:).*b(7,:) -a(7,:).*b(6,:);\nc(3,:)=-a(1,:).*b(7,:) -a(2,:).*b(5,:) +0 +a(4,:).*b(6,:) +a(5,:).*b(2,:) -a(6,:).*b(4,:) +a(7,:).*b(1,:);\nc(4,:)=+a(1,:).*b(2,:) -a(2,:).*b(1,:) -a(3,:).*b(6,:) +0 +a(5,:).*b(7,:) +a(6,:).*b(3,:) -a(7,:).*b(5,:);\nc(5,:)=-a(1,:).*b(6,:) +a(2,:).*b(3,:) -a(3,:).*b(2,:) -a(4,:).*b(7,:) +0 +a(6,:).*b(1,:) +a(7,:).*b(4,:);\nc(6,:)=+a(1,:).*b(5,:) -a(2,:).*b(7,:) +a(3,:).*b(4,:) -a(4,:).*b(3,:) -a(5,:).*b(1,:) +0 +a(7,:).*b(2,:);\nc(7,:)=+a(1,:).*b(3,:) +a(2,:).*b(6,:) -a(3,:).*b(1,:) +a(4,:).*b(5,:) -a(5,:).*b(4,:) -a(6,:).*b(2,:) +0;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/cross7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7987192772252717}} {"text": "function [snrdB,ptotdB,psigdB,pnoisedB] = calcSNR(vout,f,fB,w,N)\n% SNR calculation in the time domain (P. Malcovati, S. Brigati)\n% function [snrdB,ptotdB,psigdB,pnoisedB] = calcSNR(vout,f,fB,w,N)\n% vout: Sigma-Delta bit-stream taken at the modulator output\n% f: Normalized signal frequency (fs -> 1)\n% fB:\tBase-band frequency bins\n% w:\twindowing vector\n% N: samples number\n%\n% snrdB: SNR in dB\n% ptotdB: Bit-stream power spectral density (vector)\n% psigdB: Extracted signal power spectral density (vector)\n% pnoisedB: Noise power spectral density (vector)\n%\nfB=ceil(fB);\nsignal=(N/sum(w))*sinusx(vout(1:N).*w,f,N);\t% Extracts sinusoidal signal\nnoise=vout(1:N)-signal;\t\t\t % Extracts noise components\nstot=((abs(fft((vout(1:N).*w)'))).^2);\t\t% Bit-stream PSD\nssignal=(abs(fft((signal(1:N).*w)'))).^2;\t% Signal PSD\nsnoise=(abs(fft((noise(1:N).*w)'))).^2;\t\t% Noise PSD\npwsignal=sum(ssignal(1:fB)); % Signal power\npwnoise=sum(snoise(1:fB));\t\t % Noise power\nsnr=pwsignal/pwnoise;\nsnrdB=dbp(snr);\nnorm=sum(stot)/sum(vout(1:N).^2)*N;\t\t\t\t\t\t\t\t% PSD normalization\nif nargout > 1\n\tptot=stot/norm;\n\tptotdB=dbp(ptot);\nend\n\nif nargout > 2\n\tpsig=ssignal/norm;\n\tpsigdB=dbp(psig);\nend\n\nif nargout > 3\n\tpnoise=snoise/norm;\n\tpnoisedB=dbp(pnoise);\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/15417-successive-approximation-adc/calcSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.798704324754136}} {"text": "% Filter design\n% FIR Filter Design via Spectral Factorization and Convex Optimization\n% EE364 lecture, Filter design and equalization\n%\n% fir_chebychev_design.m - Chebychev design of an FIR filter given a desired H(w)\n% one_over_f_filter.m - Design a 1/f spectrum shaping (pink-noise) filter\n% equalizer_design.m - Equalizer design example\n% iir_mag_design_bandpass_max_atten.m - Maximize stopband attenuation of a bandpass IIR filter\n% fir_lin_phase_lowpass_max_atten.m - Maximize stopband attenuation of a linear phase lowpass FIR filter\n% fir_mag_design_lowpass_max_atten.m - Maximize stopband attenuation of a lowpass FIR filter (magnitude design)\n% iir_mag_design_lowpass_max_atten.m - Maximize stopband attenuation of a lowpass IIR filter\n% fir_lin_phase_lowpass_min_order.m - Minimize order of a linear phase lowpass FIR filter\n% fir_mag_design_lowpass_min_order.m - Minimize order of a lowpass FIR filter (magnitude design)\n% fir_lin_phase_lowpass_min_ripple.m - Minimize stopband ripple of a linear phase lowpass FIR filter\n% fir_lin_phase_lowpass_min_trans.m - Minimize transition bandwidth of a linear phase lowpass FIR filter\n% spectral_fact.m - Spectral factorization using Kolmogorov 1939 approach.\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/filter_design/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7987043147215103}} {"text": "function varargout = createDodecahedron()\n%CREATEDODECAHEDRON Create a 3D mesh representing a dodecahedron.\n%\n% [V, E, F] = createDodecahedron;\n% Create a 3D mesh representing a dodecahedron\n% V is the 20-by-3 array of vertex coordinates\n% E is the 30-by-2 array of edge vertex indices\n% F is the 12-by-5 array of face vertex indices\n%\n% [V, F] = createDodecahedron;\n% Returns only the vertices and the face vertex indices.\n%\n% MESH = createDodecahedron;\n% Returns the data as a mesh structure, with fields 'vertices', 'edges'\n% and 'faces'.\n%\n% Example\n% [v, e, f] = createDodecahedron;\n% drawMesh(v, f);\n%\n% Use values given by P. Bourke, see:\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/platonic/\n% faces are re-oriented to have normals pointing outwards.\n%\n% See also\n% meshes3d, drawMesh\n% createCube, createOctahedron, createIcosahedron, createTetrahedron\n%\n\n% ---------\n% author : David Legland \n% e-mail: david.legland@inra.fr\n% INRA - TPV URPOI - BIA IMASTE\n% created the 29/07/2010.\n%\n\n% HISTORY\n\n% golden ratio\nphi = (1+sqrt(5))/2;\n\n% coordinates pre-computations\nb = 1 / phi ; \nc = 2 - phi ;\n\n% use values given by P. Bourke, see:\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/platonic/\ntmp = [ ...\n c 0 1 ; b b b ; 0 1 c ; -b b b ; -c 0 1 ; ...\n-c 0 1 ; -b -b b ; 0 -1 c ; b -b b ; c 0 1 ; ...\n c 0 -1 ; b -b -b ; 0 -1 -c ; -b -b -b ; -c 0 -1 ; ...\n-c 0 -1 ; -b b -b ; 0 1 -c ; b b -b ; c 0 -1 ; ...\n 0 1 -c ; 0 1 c ; b b b ; 1 c 0 ; b b -b ; ...\n 0 1 c ; 0 1 -c ; -b b -b ; -1 c 0 ; -b b b ; ...\n 0 -1 -c ; 0 -1 c ; -b -b b ; -1 -c 0 ; -b -b -b ; ...\n 0 -1 c ; 0 -1 -c ; b -b -b ; 1 -c 0 ; b -b b ; ...\n 1 c 0 ; b b b ; c 0 1 ; b -b b ; 1 -c 0 ; ...\n 1 -c 0 ; b -b -b ; c 0 -1 ; b b -b ; 1 c 0 ; ...\n-1 c 0 ; -b b -b ; -c 0 -1 ; -b -b -b ; -1 -c 0 ; ...\n-1 -c 0 ; -b -b b ; -c 0 1 ; -b b b ; -1 c 0 ; ...\n];\n\n% extract coordinates of unique vertices\n[verts, M, N] = unique(tmp, 'rows', 'first'); %#ok\n\n% compute indices of face vertices, put result in a 12-by-5 index array\nind0 = reshape((1:60), [5 12])';\nfaces = N(ind0);\n\n% extract edges from faces\nedges = [reshape(faces(:, 1:5), [60 1]) reshape(faces(:, [2:5 1]), [60 1])];\nedges = unique(sort(edges, 2), 'rows');\n\n\n% format output\nvarargout = formatMeshOutput(nargout, verts, edges, faces);\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/createDodecahedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.798623842483888}} {"text": "function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...\n num_features, lambda)\n%COFICOSTFUNC Collaborative filtering cost function\n% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...\n% num_features, lambda) returns the cost and gradient for the\n% collaborative filtering problem.\n%\n\n% Unfold the U and W matrices from params\nX = reshape(params(1:num_movies*num_features), num_movies, num_features);\nTheta = reshape(params(num_movies*num_features+1:end), ...\n num_users, num_features);\n\n \n% You need to return the following values correctly\nJ = 0;\nX_grad = zeros(size(X));\nTheta_grad = zeros(size(Theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost function and gradient for collaborative\n% filtering. Concretely, you should first implement the cost\n% function (without regularization) and make sure it is\n% matches our costs. After that, you should implement the \n% gradient and use the checkCostFunction routine to check\n% that the gradient is correct. Finally, you should implement\n% regularization.\n%\n% Notes: X - num_movies x num_features matrix of movie features\n% Theta - num_users x num_features matrix of user features\n% Y - num_movies x num_users matrix of user ratings of movies\n% R - num_movies x num_users matrix, where R(i, j) = 1 if the \n% i-th movie was rated by the j-th user\n%\n% You should set the following variables correctly:\n%\n% X_grad - num_movies x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of X\n% Theta_grad - num_users x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of Theta\n%\n\n%sum(R .* (((X * Theta') .- Y) .^ 2)) 1*4 matrix\nJ = 1 / 2 * sum(sum(R .* (((X * Theta') .- Y) .^ 2)));\nJ = J + lambda / 2 * sum(sum(X .^ 2)) + lambda / 2 * sum(sum(Theta .^ 2));\n\n% (((X * Theta') .- Y) * Theta)\n\nX_grad = (R .* ((X * Theta') .- Y)) * Theta;\nX_grad = X_grad + lambda .* X;\nTheta_grad = (R .* ((X * Theta') .- Y))' * X;\nTheta_grad = Theta_grad + lambda .* Theta;\n\n\n\n\n\n% =============================================================\n\ngrad = [X_grad(:); Theta_grad(:)];\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-ex8/ex8/cofiCostFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.798623838930782}} {"text": "function [ ns, xyz ] = sphere_cubed_grid_points_face ( n, i1, j1, k1, i2, ...\n j2, k2, ns, xyz )\n\n%*****************************************************************************80\n%\n%% SPHERE_CUBED_GRID_POINTS_FACE: points on a face of a cubed sphere grid.\n%\n% Discussion:\n%\n% This function generates points on a face of a cubed sphere grid, and\n% appneds them to a growing list.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sections into which each face of\n% the cube is to be divided.\n%\n% Input, integer I1, J1, K1, I2, J2, K2, the logical indices, between 0 \n% and N, of two corners of the face grid. It is guaranteed that I1 <= I2,\n% J1 <= J2, and K1 <= K2. \n%\n% Input, integer NS, the initial number of points.\n%\n% Input, real XYZ(NS,3), distinct points on the unit sphere\n% generated by a cubed sphere grid.\n%\n% Output, integer NS, the final number of points.\n%\n% Output, real XYZ(NS,3), distinct points on the unit sphere\n% generated by a cubed sphere grid, including the points just genereated.\n%\n for i = i1 : i2\n\n if ( i1 < i2 )\n xc = tan ( ( 2 * i - n ) * 0.25 * pi / n );\n elseif ( i1 == 0 )\n xc = -1.0;\n elseif ( i1 == n )\n xc = +1.0;\n else\n xc = 0.0;\n end\n\n for j = j1 : j2\n\n if ( j1 < j2 )\n yc = tan ( ( 2 * j - n ) * 0.25 * pi / n );\n elseif ( j1 == 0 )\n yc = -1.0;\n elseif ( j1 == n )\n yc = +1.0;\n else\n yc = 0.0;\n end\n\n for k = k1 : k2\n\n if ( k1 < k2 )\n zc = tan ( ( 2 * k - n ) * 0.25 * pi / n );\n elseif ( k1 == 0 )\n zc = -1.0;\n elseif ( k1 == n )\n zc = +1.0;\n else\n zc = 0.0;\n end\n\n xyzn = sqrt ( xc^2 + yc^2 + zc^2 );\n\n ns = ns + 1;\n xyz(ns,1) = xc / xyzn;\n xyz(ns,2) = yc / xyzn;\n xyz(ns,3) = zc / xyzn;\n\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_cubed_grid/sphere_cubed_grid_points_face.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.7986012059947017}} {"text": "function a = diagonal ( m, n, x )\n\n%*****************************************************************************80\n%\n%% DIAGONAL returns the DIAGONAL matrix.\n%\n% Formula:\n%\n% if ( I = J )\n% A(I,J) = X(I)\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% M = 5, N = 5, X = ( 1, 2, 3, 4, 5 )\n%\n% 1 0 0 0 0\n% 0 2 0 0 0\n% 0 0 3 0 0\n% 0 0 0 4 0\n% 0 0 0 0 5\n%\n% Square Properties:\n%\n% A is banded, with bandwidth 1.\n%\n% A is nonsingular if, and only if, each X(I) is nonzero.\n%\n% The inverse of A is a diagonal matrix with diagonal values 1/X(I).\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% LAMBDA(1:N) = X(1:N).\n%\n% The matrix of eigenvectors of A is the identity matrix.\n%\n% det ( A ) = product ( 1 <= I <= N ) X(I).\n%\n% Because A is diagonal, it has property A (bipartite).\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of A.\n%\n% Input, real X(min(M,N)), the diagonal entries of A.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n\n if ( i == j )\n a(i,j) = x(i);\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/diagonal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.870597271765821, "lm_q1q2_score": 0.7986011888824383}} {"text": "function h = p28_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P28_H evaluates the Hessian for problem 28.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n r = sqrt ( x(1)^2 + x(2)^2 );\n\n rx1 = x(1) / r;\n rx2 = x(2) / r;\n\n rx1x1 = x(2)^2 / r^3;\n rx1x2 = - x(1) * x(2) / r^3;\n rx2x1 = - x(1) * x(2) / r^3;\n rx2x2 = x(1)^2 / r^3;\n%\n% F = A * B\n% dFdX1 = ( Ar * B + A * Br ) * Rx1\n% d2FdX1dX1 = ( Arr * B + Ar * Br ) * Rx1^2 + ( Ar * B + A * Br ) * Rx1x1\n% etc\n%\n a = sqrt ( r );\n ar = 0.5 / sqrt ( r );\n arr = - 0.25 / sqrt ( r^3 );\n\n b = 1.0 + ( sin ( 50.0 * r^0.2 ) )^2;\n br = 10.0 * sin ( 100.0 * r^0.2 ) * r^(-0.8);\n brr = 200.0 * cos ( 100.0 * r^0.2 ) * r^(-1.6) ...\n - 10.0 * sin ( 100.0 * r^0.2 ) * 0.8 * r^(-1.8);\n\n h(1,1) = ( arr * b + 2.0 * ar * br + a * brr ) * rx1 * rx1 ...\n + ( ar * b + a * br ) * rx1x1;\n\n h(1,2) = ( arr * b + 2.0 * ar * br + a * brr ) * rx1 * rx2 ...\n + ( ar * b + a * br ) * rx1x2;\n\n h(2,1) = ( arr * b + 2.0 * ar * br + a * brr ) * rx2 * rx1 ...\n + ( ar * b + a * br ) * rx2x1;\n\n h(2,2) = ( arr * b + 2.0 * ar * br + a * brr ) * rx2 * rx2 ...\n + ( ar * b + a * br ) * rx2x2;\n\n return\nend\n", "meta": {"author": "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/p28_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.798492367124167}} {"text": "function [v]=tetVolMeanEst(F,V)\n\n% function [v]=tetVolMeanEst(F,V)\n% ------------------------------------------------------------------------\n%\n% This function calculates the volume of an ideal regular tetrahedron with\n% edge lengths (all equal) that match the mean edge lengths occuring for\n% the input surface defined by F (faces) and V (vertices). \n\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2014/10/17\n%------------------------------------------------------------------------\n%%\n\n[edgeLengths]=patchEdgeLengths(F,V);\nedgeLengthsMean=mean(edgeLengths);\nmeanProposedVolume=edgeLengthsMean^3./(6*sqrt(2)); %For a regular tetrahedron\nv=meanProposedVolume;\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/tetVolMeanEst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7984822026866151}} {"text": "function hEllipse = ellipsedraw(hand,a,b,x0,y0,phi,lineStyle)\n%ELLIPSEDRAW can draw an arbitrary ellipse with given parameters.\n% The properties of that ellipse plot can be customized \n% by setting the ellipse handle. \n%\n% hEllipse = ellipsedraw(hand,a,b,x0,y0,phi,lineStyle)\n%\n% Input parameters:\n% hand Parent handle for ellipse\n% a Value of the major axis\n% b Value of the minor axis\n% x0 Abscissa of the center point of the ellipse\n% y0 Ordinate of the center point of the ellipse\n% phi Angle between x-axis and the major axis\n% lineStyle Definition of the plotted line style\n%\n% Output:\n% hEllipse Handle of the ellipse\n%\n% Simple usage:\n% ellipsedraw(5,3);\n% ellipsedraw(5,3,'g--');\n% ellipsedraw(5,3,pi/4);\n%\n% Complete usage:\n% h = ellipsedraw(5,3,1,-2,pi/4,'r-.');\n% set(h,'LineWidth',2);\n\n% Designed by: Lei Wang, , 25-Mar-2003.\n% Last Revision: 01-Apr-2003.\n% Dept. Mechanical & Aerospace Engineering, NC State University.\n% Copyright (c)2003, Lei Wang \n%$Revision: 1.0 $ $ 4/1/2003 5:42:24 PM $\n\nif (nargin < 3)||(nargin > 7),\n error('Too few or too many arguments.');\n \nelseif nargin == 3\n x0 = 0; y0 = 0;\n phi = 0; lineStyle = 'b-';\n \nelseif nargin == 4\n if ischar(x0) == 1\n lineStyle = x0; \n x0 = 0; y0 = 0;\n phi = 0; \n else\n phi = x0; \n x0 = 0; y0 = 0;\n lineStyle = 'b-';\n end\n \nelseif nargin == 5 \n phi = 0; lineStyle = 'b-';\n \nelseif nargin == 6\n lineStyle = 'b-';\nend\n\n\n\ntheta = [-0.03:0.01:2*pi];\n\n% Parametric equation of the ellipse\n%----------------------------------------\n x = a*cos(theta);\n y = b*sin(theta);\n\n\n\n% Coordinate transform \n%----------------------------------------\n X = cos(phi)*x - sin(phi)*y;\n Y = sin(phi)*x + cos(phi)*y;\n X = X + x0;\n Y = Y + y0;\n\n\n% Plot the ellipse\n%----------------------------------------\n hEllipse = plot(hand,X,Y,lineStyle);\n \n \n %axis equal;", "meta": {"author": "jramshur", "repo": "HRVAS", "sha": "ffe2465a0b8f8bf21bc78db474e5da4890761a44", "save_path": "github-repos/MATLAB/jramshur-HRVAS", "path": "github-repos/MATLAB/jramshur-HRVAS/HRVAS-ffe2465a0b8f8bf21bc78db474e5da4890761a44/ellipsedraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.7983575791148918}} {"text": "function a = gk323 ( m, n )\n\n%*****************************************************************************80\n%\n%% GK323 returns the GK323 matrix.\n%\n% Discussion:\n%\n% This matrix is occasionally known as the \"Todd\" matrix.\n%\n% Formula:\n%\n% A(I,J) = abs ( I - J )\n%\n% Example:\n%\n% N = 5\n%\n% 0 1 2 3 4\n% 1 0 1 2 3\n% 2 1 0 1 2\n% 3 2 1 0 1\n% 4 3 2 1 0\n%\n% Rectangular Properties:\n%\n% A is integral: int ( A ) = A.\n%\n% A is a special case of the Fiedler matrix.\n%\n% Square Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% det ( A ) = (-1)^(N-1) * 2^(N-2) * ( N - 1 ).\n%\n% A has a dominant positive eigenvalue, and N-1 real negative eigenvalues.\n%\n% If N = 2 mod 4, then -1 is an eigenvalue, with an eigenvector\n% of the form ( 1, -1, -1, 1, 1, -1, -1, 1, ... ).\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% Example 3.23,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, New York, 1969, page 51, \n% LC: QA263.G68.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns \n% of the matrix.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n a(i,j) = abs ( i - j );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/gk323.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.7982888536344362}} {"text": "%function chol_comparison\n% Test what is the best way to evaluate Cholesky(-like) decomposition.\n\nn = 1000;\n\n% Large and ill-conditioned covariance matrix\nC = gpcov(log(100), 1:n, 1:n);\n\n% Regular Cholesky with diagonal addition\ntic\nLchol = chol(C + 100*eps*eye(n), 'lower');\nLchol(1:10, 1:10)\ntoc\n\n% LDL with negative values to zero\ntic\n[Lldl, Dldl] = ldl(C);\n%Dldl(Dldl<0) = 0;\n%Lldl = Lldl * sqrt(Dldl);\nd = diag(Dldl);\nd(d<0) = 0;\nLldl(1:10,1:10)\nLldl = bsxfun(@times, Lldl, sqrt(d(:))');\ntoc\n\n% My LDL with negative values to zero\ntic\n[Lmyldl, Dmyldl] = ldl(C);\n%Dldl(Dldl<0) = 0;\n%Lldl = Lldl * sqrt(Dldl);\nd = diag(Dmyldl);\nd(d<0) = 0;\nLmyldl(1:10,1:10)\nLmyldl = bsxfun(@times, Lmyldl, sqrt(d(:))');\ntoc\n%return\n\n% Matlab's cholcov based on eigenvalue decomposition\n% Note that this solution does not, in general, give triangular matrix!!!\n% Also, this is very slow!\ntic\nLcholcov = cholcov(C)';\nLcholcov = [Lcholcov, zeros(n, n-cols(Lcholcov))];\ntoc\n\n\n% Errors:\nerror_chol = norm(C - Lchol*Lchol')\nerror_ldl = norm(C - Lldl*Lldl')\nerror_myldl = norm(C - Lmyldl*Lmyldl')\n%error_ldl = norm(C - Lldl*Dldl*Lldl')\nerror_cholcov = norm(C - Lcholcov*Lcholcov')\n\n% What other measures could be used?\n% How accurate these methods are in solving linear equations?\n\nx = randn(n,1);\ny = C * x;\n\nopts.LT = true;\nopts.TRANSA = false;\nx_chol = linsolve(Lchol, y, opts);\nopts.TRANSA = true;\nx_chol = linsolve(Lchol, x_chol, opts);\n\nopts.LT = true;\nopts.TRANSA = false;\nx_ldl = linsolve(Lldl, y, opts);\nopts.TRANSA = true;\nx_ldl = linsolve(Lldl, x_ldl, opts);\n\nopts.LT = true;\nopts.TRANSA = false;\nx_myldl = linsolve(Lmyldl, y, opts);\nopts.TRANSA = true;\nx_myldl = linsolve(Lmyldl, x_myldl, opts);\n\nopts.LT = false;\nopts.TRANSA = false;\nx_cholcov = linsolve(Lcholcov, y, opts);\nopts.TRANSA = true;\nx_cholcov = linsolve(Lcholcov, x_cholcov, opts);\n\nerror_chol = norm(x - x_chol)\nerror_ldl = norm(x - x_ldl)\nerror_myldl = norm(x - x_myldl)\nerror_cholcov = norm(x - x_cholcov)\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/chol_comparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7981534028856445}} {"text": "function z = cumint3(x,y)\n%\n% z = cumint3(x,y)\n%\n% This returns a vector z the same size as x and y\n% which is the cumulative integral of y with respect\n% to x, with the lower integration limit set to x(1) and\n% the upper limit ranging from x(1) to x(n). The\n% successive intervals in x need not be of equal lengths, \n% though none should be of zero length. A third order\n% approximation is made so that for up to cubic polynomials\n% the values will be exact except for rounding. \n% x and y must be column vectors of the same length\n% and have at least four elements. Note that with only \n% z = b.*g below, this would be computing matlab's\n% 'cumtrapz' trapezoidal integration, the rest of the\n% expression in z serving to carry out the additional\n% third order approximation. RAS - 03/11/08\n\n% Test arguments\n[n,m] = size(x);\nif any([n,m]~=size(y)) | m~=1\n error('x and y must be column vectors of equal length.')\nend\nif n<4\n error('There must be at least four points.')\nend\n\n% Compute third order integral\nxe = [x(4);x;x(n-3)]; ye = [y(4);y;y(n-3)]; % Provide for endpoints\nx0 = xe(1:n-1); x1 = xe(2:n); x2 = xe(3:n+1); x3 = xe(4:n+2);\ny0 = ye(1:n-1); y1 = ye(2:n); y2 = ye(3:n+1); y3 = ye(4:n+2);\na = x1-x0; b = x2-x1; c = x3-x2;\nd = y1-y0; e = y2-y1; f = y3-y2;\ng = (y1+y2)/2;\n\n% Each z value will be the integral from x1 to x2 of a cubic\n% polynomial running through (x0,y0),(x1,y1),(x2,y2),(x3,y3).\nz = b.*g+1/12*b.^2.*(+c.*b.*(2*c+b).*(c+b).*d ...\n -a.*c.*(c-a).*(2*c+2*a+3*b).*e-a.*b.*(2*a+b).*(a+b).*f) ...\n ./(a.*c.*(a+b).*(c+b).*(c+a+b));\n\t\n% Obtain cumulative integral values\nz = [0;cumsum(z)];\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/19152-cumulative-cubic-integration/cumint3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7981440294918475}} {"text": "% Synthesis of a stationary time signal given sinusoids parameters\n%\n% Octave compatible\n% \n% Inputs\n% sins : matrix of size(3,N) [freq;amp;phase]\n% fs : [Hz] Sampling frequency\n% winlen : length of the time signal to synthesize\n% derive : if deriv=1, synthesize the derivative of the signal\n%\n% Outputs\n% s : The synthesized signal\n%\n% Copyright (c) 2012 University of Crete - Computer Science Department\n% \n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction [s t] = sin2sig(sins, fs, winlen, deriv)\n if nargin<4; deriv=0; end\n\n% t = (0:winlen-1)/fs;\n% t = (0:winlen-1)/fs;\n % The time reference used for the phase in sins is in the window center\n t = (-(winlen-1)/2:(winlen-1)/2)/fs;\n\n if deriv==0\n A = cos(2*pi*t'*sins(1,:) + ones(length(t),1)*sins(3,:));\n A = ones(length(t),1)*sins(2,:).*A;\n s = sum(A,2);\n elseif deriv==1\n A = -sin(2*pi*t'*sins(1,:) + ones(length(t),1)*sins(3,:));\n A = ones(length(t),1)*(sins(2,:).*(2*pi*partials(1,:))).*A;\n s = sum(A,2);\n end\n\nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/sinusoidal/sin2sig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7981440284900129}} {"text": "function varargout = zettl(X)\n% Zettl function\n%\n% ZETTL([x1, x2]) returns the value of the Zettle function at the\n% specified points. [x1] and [x2] may be vectors. The search domain \n% is \n%\n% -5 < x_i < 5\n%\n% The global minimum is \n%\n% f(x1, x2) = f(-0.0299, 0) = -0.003791\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-5, -5]; % LB\n varargout{3} = [+5, +5]; % UB\n varargout{4} = [-2.989597760285287e-002, 0]; % solution\n varargout{5} = -3.791237220468656e-003; % function value at solution\n \n % otherwise, output function value\n else\n % keep all values in the search domain\n X(X < -5) = inf; X(X > 5) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = (x1.^2 + x2.^2 - 2*x1).^2 + x1/4;\n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23147-many-testfunctions-for-global-optimizers/single-objective/zettl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7981440283754032}} {"text": "function [varargout]=ellipsefit(x,y)\n%ELLIPSEFIT Stable Direct Least Squares Ellipse Fit to Data.\n% [Xc,Yc,A,B,Phi,P]=ELLIPSEFIT(X,Y) finds the least squares ellipse that\n% best fits the data in X and Y. X and Y must have at least 5 data points.\n% Xc and Yc are the x- and y-axis center of the ellipse respectively.\n% A and B are the major and minor axis of the ellipse respectively.\n% Phi is the radian angle of the major axis with respect to the x-axis.\n% P is a vector containing the general conic parameters of the ellipse.\n% The conic representation of the ellipse is given by:\n%\n% P(1)*x^2 + P(2)*x*y + P(3)*y^2 + P(4)*x + P(5)*y + P(6) = 0\n%\n% S=ELLIPSEFIT(X,Y) returns the output data in a structure with field names\n% equal to the variable names given above, e.g., S.Xc, S.Yc, S.A, S.B,\n% S.Phi and S.P\n%\n% Reference: R. Halif and J. Flusser, \"Numerically Stable Direct Least\n% Squares FItting of Ellipses,\" Department of Software Engineering, Charles\n% University, Czech Republic, 2000.\n\n% Conversion from conic to conventional ellipse equation inspired by\n% fit_ellipse.m on MATLAB Central\n\n% D.C. Hanselman, University of Maine, Orono, ME 04469\n% Mastering MATLAB 7\n% 2005-02-28\n% Rotation angle fixed 2005-08-09\n\n%--------------------------------------------------------------------------\nx=x(:); % convert data to column vectors\ny=y(:);\nif numel(x)~=numel(y) || numel(x)<5\n error('X and Y Must be the Same Length and Contain at Least 5 Values.')\nend\n\nD1=[x.*x x.*y y.*y]; % quadratic terms\nD2=[x y ones(size(x))]; % linear terms\nS1=D1'*D1;\nS2=D1'*D2;\n\n[Q2,R2]=qr(D2,0);\nif condest(R2)>1.0e10\n warning('ellipsefit',...\n 'Data is Poorly Conditioned and May Not Represent an Ellipse.')\nend\nT=-R2\\(R2'\\S2'); % -inv(S3) * S2'\n\nM=S1+S2*T;\nCinvM=[M(3,:)/2; -M(2,:); M(1,:)/2];\n[V,na]=eig(CinvM);\nc=4*V(1,:).*V(3,:) - V(2,:).^2;\nA1=V(:,c>0);\nP=[A1; T*A1];\n\n% correct signs if needed\nif ~isempty(P),\n P=sign(P(1))*P;\n \n Phi=atan(P(2)/(P(3)-P(1)))/2;\n c=cos(Phi);\n s=sin(Phi);\n \n % rotate the ellipse parallel to x-axis\n Pr=zeros(6,1);\n Pr(1)=P(1)*c*c - P(2)*c*s + P(3)*s*s;\n Pr(2)=2*(P(1)-P(3))*c*s + (c^2-s^2)*P(2);\n Pr(3)=P(1)*s*s + P(2)*s*c + P(3)*c*c;\n Pr(4)=P(4)*c - P(5)*s;\n Pr(5)=P(4)*s + P(5)*c;\n Pr(6)=P(6);\n \n % extract other data\n XcYc=[c s;-s c]*[-Pr(4)/(2*Pr(1));-Pr(5)/(2*Pr(3))];\n Xc=XcYc(1);\n Yc=XcYc(2);\n F=-Pr(6) + Pr(4)^2/(4*Pr(1)) + Pr(5)^2/(4*Pr(3));\n AB=sqrt(F./Pr(1:2:3));\n A=AB(1);\n B=AB(2);\n Phi=-Phi;\n if A.\n%\n% Reference:\n%\n% Guowei Cai et al. Unmanned Rotorcraft Systems. Springer. 2011. \n% Eq. 2.22, p. 31.\n%\n% Version: 001\n% Date: 2019/01/16\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\n% Preallocate\n\necef = zeros(size(llh));\n\nlat = llh(:,1);\nlon = llh(:,2);\nh = llh(:,3);\n\n[~,RN] = radius(lat);\n\ne = 0.0818191908426; % Eccentricity \n\nslat = sin(lat);\nclat = cos(lat);\nclon = cos(lon);\nslon = sin(lon);\n\necef(:,1) = (RN + h) .* clat .* clon;\necef(:,2) = (RN + h) .* clat .* slon;\necef(:,3) = (RN *(1-e^2) + h) .* slat;\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/conversions/llh2ecef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657921, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.7981174129335308}} {"text": " function [alphas, beta] = nufft_alpha_kb_fit(N, J, K, L, beta, chat)\n%\n% return the alpha and beta corresponding to LS fit of L components\n% to optimized Kaiser-Bessel scaling factors (m=0, alpha=2.34J).\n% This is the best method I know currently for choosing alpha!\n%\n% Copyright 2002-7-16, Jeff Fessler, The University of Michigan\n\nif nargin < 3, help(mfilename), error(mfilename), end\nif ~isvar('L') | isempty(L)\n\tif N > 40\n\t\tL = 13;\t\t% empirically found to be reasonable\n\telse\n\t\tL = ceil(N/3);\t% a kludge to avoid \"rank deficient\" complaints\n\tend\nend\nif ~isvar('beta') | isempty(beta),\tbeta = 1; end\nif ~isvar('chat') | isempty(chat),\tchat = 0; end\n\nkb_alf = 2.34 * J;\t% KB shape parameter\nkb_m = 0;\t\t% KB order\n\n[tmp, sn_kaiser] = nufft1_error(0, N, J, K, 'kaiser', 'ft');\nsn_kaiser = reale(sn_kaiser);\n\n%\n% use regression to match NUFFT with BEST kaiser scaling's\n%\ngam = 2*pi/K;\nnlist = [0:(N-1)]' - (N-1)/2;\nX = cos(beta*gam*nlist*[0:L]);\t% [N,L]\ncoef = (X \\ sn_kaiser)';\t% regress(sn_kaiser, X)';\nalphas = [reale(coef(1)) coef(2:end)/2];\n\nif chat\n\tprintf('cond # for LS fit to KB scale factors: %g', cond(X))\nend\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@NUFFT/private/nufft_alpha_kb_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7981174096627688}} {"text": "function [bcUx, bcUy, bcPR, bcdUndt] = KovasznayBC2D(x, y, nx, ny, mapI, mapO, mapW, mapC, time, nu)\n\n% function [bcUx, bcUy, bcPR, bcdUndt] = KovasznayBC2D(x, y, nx, ny, mapI, mapO, mapW, mapC, time, nu)\n% Purpose: evaluate boundary conditions for Kovasznay flow \n\nzer = zeros(size(x)); bcUx = zer; bcUy = zer; bcPR = zer; bcdUndt = zer;\n\nlam = (0.5/nu) - sqrt( (0.25/(nu^2)) + 4*pi^2 );\n\n% inflow\nxI = x(mapI); yI = y(mapI);\nbcUx(mapI)= 1-exp(lam*xI).*cos(2*pi*yI);\nbcUy(mapI)= (0.5*lam/pi)*exp(lam*xI).*sin(2*pi*yI);\n\n% outflow\nxO = x(mapO); yO = y(mapO);\n\nif(0)\n bcPR(mapO) = .5*(1-exp(2*lam*xO));\n bcUx(mapO)= 1-exp(lam*xO).*cos(2*pi*yO);\n bcUy(mapO)= (0.5*lam/pi)*exp(lam*xO).*sin(2*pi*yO);\nelse\n bcPR(mapO) = .5*(1-exp(2*lam*xO));\n\n % Neumann data for each velocity\n bcUx(mapO) = -lam*exp(lam*xO).*cos(2*pi*yO);\n bcUy(mapO) = lam*(0.5*lam/pi)*exp(lam*xO).*sin(2*pi*yO);\nend\nreturn\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD2D/KovasznayBC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.798092391084662}} {"text": "function dist=KLDiv(P,Q)\n% dist = KLDiv(P,Q) Kullback-Leibler divergence of two discrete probability\n% distributions\n% P and Q are automatically normalised to have the sum of one on rows\n% have the length of one at each \n% P = n x nbins\n% Q = 1 x nbins or n x nbins(one to one)\n% dist = n x 1\n\n\n\nif size(P,2)~=size(Q,2)\n error('the number of columns in P and Q should be the same');\nend\n\nif sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))\n error('the inputs contain non-finite values!') \nend\n\n% normalizing the P and Q\nif size(Q,1)==1\n Q = Q ./sum(Q);\n P = P ./repmat(sum(P,2),[1 size(P,2)]);\n dist = sum(P.*log(P./repmat(Q,[size(P,1) 1])),2);\n \nelseif size(Q,1)==size(P,1)\n \n Q = Q ./repmat(sum(Q,2),[1 size(Q,2)]);\n P = P ./repmat(sum(P,2),[1 size(P,2)]);\n dist = sum(P.*log(P./Q),2);\nend\n\n% resolving the case when P(i)==0\ndist(isnan(dist))=0;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20689-jensen-shannon-divergence/home/nrazavi/Desktop/KLDiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.798046062126425}} {"text": "% MORLET_2D_NODC computes the 2-D elliptic Morlet filter given a set of \n% parameters in Fourier domain\n%\n% Usage\n% gab = MORLET_2D_NODC(N, M, sigma, slant, xi, theta, offset)\n%\n% Input\n% N (numeric): Width of the filter.\n% M (numeric): Height of the filter.\n% sigma (numeric): Standard deviation of the envelope.\n% slant (numeric): Eccentricity of the elliptic envelope.\n% (the smaller slant, the larger angular resolution).\n% xi (numeric): The frequency peak.\n% theta (numeric): Orientation in radians of the filter.\n% offset (numeric, optional): 2-D vector reprensting the offset location \n% (default [0 0]).\n% \n% Output\n% gab (numeric): N-by-M matrix representing the gabor filter in spatial\n% domain.\n%\n% Description\n% Compute a Morlet wavelet in Fourier domain. \n%\n% Morlet wavelets have a 0 DC component.\n%\n% See also\n% GABOR_2D, MORLET_2D_PYRAMID\n\nfunction gab = morlet_2d_noDC(N, M, sigma, slant, xi, theta, offset)\n\t\n\tif ~exist('offset','var')\n\t\toffset = [0, 0];\n\tend\n\t[x , y] = meshgrid(1:M, 1:N);\n\t\n\tx = x - ceil(M/2) - 1 - offset(1);\n\ty = y - ceil(N/2) - 1 - offset(2);\n\t\n\tRth = rotation_matrix_2d(theta);\n\tA = Rth\\ [1/sigma^2, 0 ; 0 slant^2/sigma^2] * Rth ;\n\ts = x.* ( A(1,1)*x + A(1,2)*y) + y.*(A(2,1)*x + A(2,2)*y ) ;\n\t\n\t%normalize sucht that the maximum of fourier modulus is 1\n\t\n\tgaussian_envelope = exp( - s/2);\n\toscilating_part = gaussian_envelope .* exp(1i*(x*xi*cos(theta) + y*xi*sin(theta)));\n\tK = sum(oscilating_part(:)) ./ sum(gaussian_envelope(:));\n\tgabc = oscilating_part - K.*gaussian_envelope;\n\t\n\tgab=1/(2*pi*sigma^2/slant^2)*fftshift(gabc);\n\t\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/filters/morlet_2d_noDC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7980460503880874}} {"text": "function [La,dLa,lambda0] = lagrange(U,s,b,more)\n%LAGRANGE Plot the Lagrange function for Tikhonov regularization.\n%\n% [La,dLa,lambda0] = lagrange(U,s,b,more)\n% [La,dLa,lambda0] = lagrange(U,sm,b,more) , sm = [sigma,mu]\n%\n% Plots the Lagrange function\n% La(lambda) = || A x - b ||^2 + lambda^2*|| L x ||^2\n% and its first derivative dLa = dLa/dlambda versus lambda.\n% Here, x is the Tikhonov regularized solution.\n%\n% If nargin = 4, || A x - b || and || L x || are also plotted.\n%\n% Returns La, dLa, and the value lambda0 of lambda for which\n% dLa has its minimum.\n\n% Per Christian Hansen, IMM, Feb. 21, 2001.\n\n% Set default number of points.\nnpoints = 200;\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\nxi = beta(1:p)./s;\n\n% Compute the L-curve.\neta = zeros(npoints,1); rho = eta;\nlambda(npoints,1) = s(p);\nratio = (s(1)/s(p))^(1/(npoints-1));\nfor i=npoints-1:-1:1, lambda(i) = ratio*lambda(i+1); end\nfor i=1:npoints\n f = fil_fac(s,lambda(i));\n eta(i) = norm(f.*xi);\n rho(i) = norm((1-f).*beta(1:p));\nend\nif (m > n && beta2 > 0), rho = sqrt(rho.^2 + beta2); end\n\n% Compute the Lagrange function and its derivative.\nLa = rho.^2 + (lambda.^2).*(eta.^2);\ndLa = 2*lambda.*(eta.^2);\n[mindLa,mindLi] = min(dLa); lambda0 = lambda(mindLi);\n\n% Plot the functions.\nif (nargin==3)\n loglog(lambda,La,'-',lambda,dLa,'--',lambda0,mindLa,'o')\n legend('La','dLa/d\\lambda')\nelse\n loglog(lambda,La,'-',lambda,dLa,'--',lambda,eta,':',lambda,rho,'-.',...\n lambda0,mindLa,'o')\n legend('La','dLa/d\\lambda','|| L x ||_2','|| A x - b ||_2')\nend\nxlabel('\\lambda')\ntitle('Lagrange function La and its derivative')", "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/lagrange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8558511524823262, "lm_q1q2_score": 0.7980412358111157}} {"text": "function probVal=trivarNormCDF(b,mu,R)\n%%TRIVARNORMCDF Evaluate the cumulative density function of the trivariate\n% normal distribution with a specified mean and covariance\n% matrix. This evaluates Pr{x1r % need to find additional vectors\n g=chol(w);\n v=g\\null(c'*g');\n [p,l,q]=svd(v'*b*v);\n a(:,r+1:n)=v*p(:,1:n-r);\n a(:,1:r)=c;\n else\n a=c; % no new vectors to find\n end\n if nargout>1\n ari=a/triu(qr(chol(a'*w*a))); % matrix a must be of full rank\n f=diag(ari'*b*ari);\n end\nelse\n [g,d]=eig(b,w,'qz');\n [ds,is]=sort(-diag(d));\n a=g(:,is(1:n));\n if nargout>1\n f=-ds(1:n);\n end\nend\nif nargout > 2\n B=a'*b*a;\n if nargout > 3\n W=a'*w*a;\n end\n \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_ldatrace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7978919452363069}} {"text": "function varargout = carromtable(X)\n% Carrom table function\n%\n% CARROMTABLE([x1, x2]) returns the value of the Carrom table\n% function at the specified points. [x1] and [x2] may be vectors. \n% The search domain is\n%\n% -10 < x_i < 10\n%\n% The four global minimum are found near the corners of the interval,\n% with\n%\n% fmin = 24.1568155.\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-10, -10]; % LB\n varargout{3} = [+10, +10]; % UB\n varargout{4} = [+9.646157266348881e+000, +9.646134286497169e+000\n -9.646157266348881e+000, +9.646134286497169e+000\n +9.646157266348881e+000, -9.646134286497169e+000\n -9.646157266348881e+000, -9.646134286497169e+000]; % solution\n varargout{5} = -2.415681551650653e+001; % function value at solution\n\n % otherwise, output function value\n else\n \n % keep values in the serach interval\n X(X < -10) = inf; X(X > 10) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = -((cos(x1).*cos(x2).*exp(abs(1 - sqrt(x1.^2 + x2.^2)/pi))).^2)/30;\n \n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23147-many-testfunctions-for-global-optimizers/single-objective/carromtable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7977593747837486}} {"text": "function [kl1,kl2] = mvnkl(Mu1,Sigma1,Mu2,Sigma2)\n%MVNKL Kullback-Leibler divergence between two multivariate normal pdfs.\n\nD = numel(Mu1);\n\nMu1 = Mu1(:);\nMu2 = Mu2(:);\n\ndmu = Mu2 - Mu1;\ndetq1 = det(Sigma1);\ndetq2 = det(Sigma2);\nlndet = log(detq2 / detq1);\n\nkl1 = 0.5*(trace(Sigma2\\Sigma1) + dmu'*(Sigma2\\dmu) - D + lndet);\nif nargout > 1\n kl2 = 0.5*(trace(Sigma1\\Sigma2) + dmu'*(Sigma1\\dmu) - D - lndet);\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/shared/mvnkl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7975921987745835}} {"text": "function yp = fpcube ( x )\n\n%*****************************************************************************80\n%\n%% FPCUBE sets the derivative of the cubic function.\n%\n% Discussion:\n%\n% Y(X) = ( ( X + 2 ) * X + 3 ) * X + 4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real YP, the value of the derivative of the cubic function.\n%\n yp = ( 3.0E+00 * x + 4.0E+00 ) * x + 3.0E+00;\n\n return\nend\n", "meta": {"author": "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/fpcube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7975625348430915}} {"text": "function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)\n%GRADIENTDESCENT Performs gradient descent to learn theta\n% theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by \n% taking num_iters gradient steps with learning rate alpha\n\n% Initialize some useful values\nm = length(y); % number of training examples\nJ_history = zeros(num_iters, 1);\n\nfor iter = 1:num_iters\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCost) and gradient here.\n %\n theta_temp = theta;\n for j = 1:size(X, 2)\n theta_temp(j) = theta(j)-alpha*(1/m)*(X*theta - y)' * X(:, j);\n end\n theta = theta_temp;\n\n\n\n\n\n % ============================================================\n\n % Save the cost J in every iteration \n J_history(iter) = computeCost(X, y, theta);\n\nend\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex1/gradientDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.797562522539886}} {"text": "function x = tuple_next_fast ( m, n, rank )\n\n%*****************************************************************************80\n%\n%% TUPLE_NEXT_FAST computes the next element of a tuple space, \"fast\".\n%\n% Discussion:\n%\n% The elements are N vectors. Each entry is constrained to lie\n% between 1 and M. The elements are produced one at a time.\n% The first element is\n% (1,1,...,1)\n% and the last element is\n% (M,M,...,M)\n% Intermediate elements are produced in lexicographic order.\n%\n% This code was written as a possibly faster version of TUPLE_NEXT.\n%\n% Example:\n%\n% N = 2,\n% M = 3\n%\n% INPUT OUTPUT\n% ------- -------\n% Rank X\n% ---- ----\n% -1 -1 -1\n%\n% 0 1 1\n% 1 1 2\n% 2 1 3\n% 3 2 1\n% 4 2 2\n% 5 2 3\n% 6 3 1\n% 7 3 2\n% 8 3 3\n% 9 1 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the maximum entry in each component.\n% M must be greater than 0.\n%\n% Input, integer N, the number of components.\n% N must be greater than 0.\n%\n% Input, integer RANK, indicates the rank of the tuples.\n% Typically, 0 <= RANK < N**M; values greater than this are\n% legal and meaningful, being equivalent to the corresponding\n% value mod N**M. RANK < 0 indicates that this is the first\n% call for the given values of (M,N). Initialization is done,\n% and X is set to a dummy value.\n%\n% Output, integer X(N), the next tuple of the given rank,\n% or a dummy value if initialization is being done.\n%\n global tuple_next_fast_BASE\n\n if ( rank < 0 )\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TUPLE_NEXT_FAST - Fatal error!\\n' );\n fprintf ( 1, ' M <= 0 is illegal.\\n' );\n fprintf ( 1, ' M = %d\\n', m );\n error ( 'TUPLE_NEXT_FAST - Fatal error!' );\n end\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TUPLE_NEXT_FAST - Fatal error!\\n' );\n fprintf ( 1, ' N <= 0 is illegal.\\n' );\n fprintf ( 1, ' N = %d\\n', n );\n error ( 'TUPLE_NEXT_FAST - Fatal error!' );\n end\n\n tuple_next_fast_BASE(n) = 1;\n for i = n-1 : -1 : 1\n tuple_next_fast_BASE(i) = tuple_next_fast_BASE(i+1) * m;\n end\n\n x(1:n) = -1;\n\n else\n\n x(1:n) = mod ( floor ( rank ./ tuple_next_fast_BASE(1:n) ), m ) + 1;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ccvt_reflect/tuple_next_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.7975396617761051}} {"text": "function orbEls=state2OrbEls(stateVec,elType,GM,epsVal)\n%%STATE2ORBELS Convert a state vector consisting of at least position and\n% velocity into a set of orbital elements. Such elements are\n% for a simple two-body problem where the satellite (object)\n% in motion has negligible mass. The elements can be found\n% with respect to a given epoch time.\n%\n%INPUTS: stateVec A 6XnumVec matrix of numVec state vectors consisting of\n% position and velocity in a Cartesian (quasi)-inertial\n% coordinate system where the gravitating body is at the\n% origin. Extra state elements are ignored. The units are\n% assumed to be meters and meters per second.\n% elType A value indicating the type of orbital elements. Possible\n% values are:\n% 0 (The default if omitted) The elements are Gooding's\n% universal orbital elements.\n% 2 The elements are direct equinoctial orbital elements.\n% 3 The elements are retrograde equnoctial orbital\n% elements.\n% GM Optionally, the universal gravitation constant times the\n% mass of the body about which the object with the given\n% state vector is orbiting. If this parameter is omitted,\n% the value in Constants.WGS84GMWithAtmosphere is used. The\n% units are m^3/sec^2.\n% epsVal If universal orbital elements are chosen, this is a\n% precision bound used for equality comparisons when\n% determining whether a trajectory is rectilinear,\n% parabolic or circular. If omitted, a default value of\n% eps is used.\n%\n%OUTPUTS: orbEls An 6XnumVec set of vectors of orbital elements, the format\n% of which depends on the elType parameter. The format of\n% the elements is discussed below.\n%\n%Gooding's universal orbital elements are consist of (in order)\n%alpha=GM/a where a is the semi-major axis in meters\n%q=a*(1-e) where e is the eccentricity (unitless). This is the perifocal\n% distance.\n%i inclination in radians\n%Omega longitude (right ascension) of the ascending node in radians\n%omega argument of periapsis/perigee in radians\n%tau the time at pericenter (seconds)\n%\n%The equinoctial orbital elements (for both direct and retrograde elements)\n%are\n%a semi-major axis in meters\n%h first eccentricity vector component (unitless)\n%k second eccentricity vector component (unitless)\n%p first ascending node vector component (unitless)\n%q second ascending node vector component (unitless)\n%lambda mean longitude in radians.\n%\n%The algorithm using Gooding's universal orbital elements is very robust to\n%numerical errors. It is implemented using the algorithm of [1], where the\n%elements are also described.\n%\n%Equinoctial orbital elements are discussed in Section 2 of [2]. and in\n%[3]. The diffference between direct and retrograde elements is essentially\n%a matter of handedness.\n%\n%Orbital elements are discussed in general in Chapter 2.2 of [4].\n%\n%The inverse of this function is orbEls2State, which can also predict the\n%state forward in time. Adding a time interval in seconds to the tau\n%argument also predicts the trajectory forward in terms of universal\n%orbital elements.\n%\n%REFERENCES:\n%[1] R. H. Gooding, \"On universal elements, and conversion procedures to\n% and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n% pp. 283-298, 1988.\n%[2] D. A. Danielson, C. P. Sagovac, B. Neta, and L. W. Early,\n% \"Semianalytic satellite theory,\" Mathematics Department, Naval\n% Postgraduate School, Monterey, CA, Tech. Rep., 1995. [Online].\n% Available: http://oai.dtic.mil/oai/oai?verb=getRecord&metadataPrefix= html&identifier=ADA531136\n%[3] R. A. Broucke and P. J. Cefola, \"On the equinoctial orbit elements,\"\n% Celestial Mechanics, vol. 5, no. 3, pp. 303-310, 1972.\n%[4] O. Montenbruck and E. Gill, Satellite Orbits: Models, Methods\n% Applications. Berlin: Springer, 2000.\n%\n%January 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4)\n epsVal=eps;\nend\n\nif(nargin<3)\n GM=Constants.WGS84GMWithAtmosphere;\nend\n\nif(nargin<2)\n elType=0;\nend\n\nnumVec=size(stateVec,2);\norbEls=zeros(6,numVec);\n\nswitch(elType)\n case 0\n for curVec=1:numVec\n orbEls(:,curVec)=state2OrbElsUniv(stateVec(1:6,curVec),GM,epsVal);\n end\n case 1\n for curVec=1:numVec\n orbEls(:,curVec)=state2OrbElsEquinoctial(stateVec(1:6,curVec),1,GM);\n end\n case 2\n for curVec=1:numVec\n orbEls(:,curVec)=state2OrbElsEquinoctial(stateVec(1:6,curVec),-1,GM);\n end\n otherwise\n error('Invalid element type provided.')\nend\n\nend\n\nfunction elEqui=state2OrbElsEquinoctial(state,I,GM)\n%%STATE2ORBELSEQUINOCTIAL An algorithm to convert from a target state to a\n% set of equinoctial orbital elements.\n%\n%The input I is the retrograde factor ond is +1 for direct equinoctial\n%elements and -1 for retrograde equinoctial elements.\n%\n%The algorithm is taken from Section 2.1.5 of\n%D. A. Danielson, C. P. Sagovac, B. Neta, and L. W. Early, \"Semianalytic\n%satellite theory,\" Mathematics Department, Naval Postgraduate School,\n%Monterey, CA, Tech. Rep., 1995. [Online]. Available:\n%http://oai.dtic.mil/oai/oai?verb=getRecord&metadataPrefix= html&identifier=ADA531136\n%\n%January 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n%position\nr=state(1:3);\n%velocity\nrDot=state(4:6);\n\n%Equation 1\na=1/(2/norm(r)-norm(rDot)^2/GM);%Semi-major axis.\n%Equation 2\nw=cross(r,rDot)/norm(cross(r,rDot));\n\n%Equation 3\np=w(1)/(1+I*w(3));%First ascending node vector component.\nq=-w(2)/(1+I*w(3));%Second ascending node vector component.\n\n%Equation 4\ne=-r/norm(r)+cross(rDot,cross(r,rDot))/GM;\n\n%Equation 2.1.4-1\ncoeff=(1/(1+p^2+q^2));\nf=coeff*[1-p^2+q^2;\n 2*p*q;\n -2*I*p];\ng=coeff*[2*I*p*q;\n (1+p^2-q^2)*I;\n 2*q];\n \n%Equation 5\nh=dot(e,g);%First eccentricity vector component.\nk=dot(e,f);%Second eccentricity vector component.\n\n%Equation 6\nX=dot(r,f);\nY=dot(r,g);\n\n%Equation 2.1.4-4\nb=1/(1+sqrt(1-h^2-k^2));\n%Equation 7\ndenom=a*sqrt(1-h^2-k^2);\nsinF=h+((1-h^2*b)*Y-h*k*b*X)/denom;\ncosF=k+((1-k^2*b)*X-h*k*b*Y)/denom;\nF=atan2(sinF,cosF);\n\nlambda=F+h*cosF-k*sinF;%Mean longitude\n\nelEqui=[a;h;k;p;q;lambda];\n\nend\n\n\nfunction elUniv=state2OrbElsUniv(state,GM,epsVal)\n%%STATE2ORBELSUNIV An implementation of Gooding's conversion from a target\n% state to universal orbital elements. This implements the\n% PV3ELS function.\n%\n%The implementation is taken from Appendix D of\n%R. H. Gooding, \"On universal elements, and conversion procedures to\n%and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n%pp. 283-298, 1988.\n%with minor changes so that equality comparisons are replaced with\n%comparisons within a region epsVal.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nrVec=state(1:3);\nvVec=state(4:6);\nx=rVec(1);\ny=rVec(2);\nz=rVec(3);\n\nxyMag=norm(rVec(1:2));\nr=norm(rVec);\n\n%The projection of the velocity onto the radial component.\nVR=dot(rVec,vVec)/r;%Radial velocity\n\n%The angular momentum vector.\nhVec=cross(rVec,vVec);\n\nif(norm(hVec)^2=0.\n% r Radial distance.\n% u Angle from assumed reference direction.\n% GM Universal gravitational constant times the mass of the\n% gravitating body.\n% epsVal A small number for determining equality within finite\n% precision bounds.\n%\n%The algorithm is taken from Appendix C of\n%R. H. Gooding, \"On universal elements, and conversion procedures to\n%and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n%pp. 283-298, 1988.\n%with minor changes so that equality comparisons are not performed. \n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nsw=0.25;\n\nVMag2=VR^2+VT^2;\nalpha=2*GM/r-VMag2;\n\nd=r*VR;\nh=r*VT;\np=h^2;\n\nesq1=p*alpha;\nes=d*sqrt(abs(alpha));\nec=r*VMag2-GM;\nif(alpha>0)%One formula superior for the ellipse\n e=sqrt(ec^2+es^2);\nelse%Different formula superior for the hyperbola\n e=sqrt(GM^2-esq1);\nend\n\nq=p/(GM+e);\nif(abs(alpha)<=epsVal)%Parabola\n tau=d*(2*q+r)/(3*GM);\n v=2*atan2(VR,VT);%The true anomaly\nelseif(abs(e)<=epsVal)%Circle\n tau=0;\n v=0;%The true anomaly\nelse%Ellipse or hyperbola\n e1=alpha*q;\n \n if(alpha>0)%Ellipse\n eh=atan2(es,ec);\n if(GM*eh^2/6+e1>GM*sw)%General case\n em=GM*eh-es;\n ecesq=GM*ec-e^2;\n else%For e1 and eh both near zero\n em=GM*GoodingSinDiffFun(e1/GM,eh);\n ecesq=(esq1*ec^2-e^2*es^2)/(e^2+GM*ec);\n end\n else%Hyperbola\n eh=asinh(es/e);\n \n if(GM*eh^2/6-e1>GM*sw)%General case\n em=es-GM*eh;\n ecesq=e^2-GM*ec;\n else%For e1 and eh both near zero\n em=e*GoodingHyperSinDiffFun(-e1/e,es/e);\n ecesq=-(esq1*ec^2+e^2*es^2)/(e^2+GM*ec);\n end\n end\n %Still ellipse or hyperbola\n en=abs(alpha)^(3/2);\n tau=em/en;\n v=atan2(es*h*sqrt(abs(alpha)),ecesq);%The true anomaly\nend\n%All orbits\nomega=u-v;%The argument of periapsis\n\n%Adjust revolutions, if necessary, so that omega remains in the range\n%-pi to pi. The second condition in the if-statement takes care of possible\n%parabolic case; this is just for the elliptical case.\nif(alpha>0&&abs(alpha)>epsVal)\n adj=2*pi*fix(abs(omega/(2*pi))+(1/2))*sign(omega);\n omega=omega-adj;\n tau=tau+adj/en;\nend\n\nend\n\n\nfunction x=GoodingSinDiffFun(e,EE)\n%%GOODINGSINDIFFFUN Evaluate the function EE-(1-e)*sin(EE) using Gooding's\n% EMKEP procedure for when e and EE are close\n% to (1,0). This is supposed to be more accurate than\n% just directly evaluating the functions, unless EE is\n% large as it is then supposed to worsen rounding errors.\n%\n%\n%The algorithm is the EMKPL algorithm taken from Appendix C of\n%A. W. Odell and R. H. Gooding, \"Procedure for solving Kepler's\n%equation,\" Celestial Mechanics, vol. 38, no. 4, pp. 307-334, Apr. 1986.\n%modified to solve EE-(1-e)*sin(EE) instead of EE-e*sin(EE).\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nx=e*sin(EE);\nEE2=-EE^2;\nterm=EE;\nd=0;\nwhile(1)\n d=d+2;\n term=term*EE2/(d*(d+1));\n x0=x;\n x=x-term;\n if(x==x0)\n break;\n end\nend\n\nend\n\n\nfunction x=GoodingHyperSinDiffFun(g1,s)\n%%GOODINGHYPERSINDIFFFUN Evaluate the function s-(1-g1)*asinh(s) when\n% (g1,s) is close to (0,0) using Gooding's method.\n% This is supposed to have a higher precision than\n% just explicitly evaluating the function.\n%\n%The algorithm is the SHMKEP function taken from Appendix B of \n%R. H. Gooding and A. W. Odell, \"The hyperbolic Kepler's equation,\n%and the elliptic equations revisited,\" Royal Aerospace Executive,\n%Procurement Executive, Ministry of Defence, Farnborough, Hants, United\n%Kingdom, Tech. Rep. 369, Jul. 1989.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\ng=1-g1;\nt=s/(1+sqrt(1+s^2));\nx=s*(g1+g*t^2);\nterm=2*g*t;\ntwoI1=1;\n%Iterate until convergence or until a maximum number of iterations is\n%reached.\nmaxIter=64;\nfor curIter=1:maxIter\n twoI1=twoI1+2;\n term=term*t^2;\n x0=x;\n x=x-term/twoI1;\n if(x==x0)\n break;\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\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/state2OrbEls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7973783748923229}} {"text": "function fx = p34_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P34_FUN evaluates the integrand for problem 34.\n%\n% Interval:\n%\n% 0 <= x <= 1\n%\n% Integrand:\n%\n% ( 10 * x - 1 ) * ( 10 * x - 1.1 ) * ( 10 * x - 1.2 ) * ( 10 * x - 1.3 )\n%\n% Exact Integral:\n%\n% 1627879 / 1500\n%\n% Approximate Integral (20 digits):\n%\n% 1085.2526666666666666...\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Hermann Engels,\n% Numerical Quadrature and Cubature,\n% Academic Press, 1980.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n fx = ( 10.0 * x - 1.0 ) .* ( 10.0 * x - 1.1 ) .* ( 10.0 * x - 1.2 ) ...\n .* ( 10.0 * x - 1.3 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p34_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.7973629664947972}} {"text": "function p = gaussian_prob(x, m, C, use_log)\n% GAUSSIAN_PROB Evaluate a multivariate Gaussian density.\n% p = gaussian_prob(X, m, C)\n% p(i) = N(X(:,i), m, C) where C = covariance matrix and each COLUMN of x is a datavector\n\n% p = gaussian_prob(X, m, C, 1) returns log N(X(:,i), m, C) (to prevents underflow).\n%\n% If X has size dxN, then p has size Nx1, where N = number of examples\n\nif nargin < 4, use_log = 0; end\n\nif length(m)==1 % scalar\n x = x(:)';\nend\n[d N] = size(x);\n%assert(length(m)==d); % slow\nm = m(:);\nM = m*ones(1,N); % replicate the mean across columns\ndenom = (2*pi)^(d/2)*sqrt(abs(det(C)));\nmahal = sum(((x-M)'*inv(C)).*(x-M)',2); % Chris Bregler's trick\nif any(mahal<0)\n warning('mahal < 0 => C is not psd')\nend\nif use_log\n p = -0.5*mahal - log(denom);\nelse\n p = exp(-0.5*mahal) / (denom+eps);\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/KPMstats/gaussian_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7973064370361043}} {"text": "function [v,d,dref] = generate_doddbench(N)\n% Generate DODDBENCH signal.\n%\n% Benchmark signal introduced in Dodd, T.J., Kadirkamanathan, V. and\n% Harrison, R.F., \"Function estimation in Hilbert space using sequential\n% projections,\" Proc. of the IFAC Conf. on Intelligent Control Systems and\n% Signal Processing, 113-118, 2003.\n% \n% Comment: copyright Cedric Richard, http://cedric-richard.fr/\n%\n% Input: N: number of data points\n% \n% Outputs: v: input sequence (2-dimensional sequence [v(:,1);v(:,2)])\n% d: noisy desired output (1-dimensional sequence)\n% dref: noise-free desired output\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\ndref = zeros(1,N+2);\ndref(1:2)=[0.1 0.1];\n\nfor t=3:N+2\n dref(t) = (0.8-0.5*exp(-dref(t-1)^2))*dref(t-1) - ...\n (0.3+0.9*exp(-dref(t-1)^2))*dref(t-2)+0.1*sin(pi*dref(t-1));\nend\nd = dref + 0.1*randn(1,N+2);\nv = [d(1:N); d(2:N+1)]';\n\nd(1:2)=[];\ndref(1:2)=[];\n", "meta": {"author": "steven2358", "repo": "kafbox", "sha": "694cf94df02a9728a90d7bacda1a8520b425f86f", "save_path": "github-repos/MATLAB/steven2358-kafbox", "path": "github-repos/MATLAB/steven2358-kafbox/kafbox-694cf94df02a9728a90d7bacda1a8520b425f86f/demo/literature/richard2009online/generate_doddbench.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7973064356435208}} {"text": "function [ x, seed ] = simplex_unit_sample ( dim_num, n, seed )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_UNIT_SAMPLE samples the unit simplex.\n%\n% Discussion:\n%\n% The interior of the unit DIM_NUM-dimensional simplex is the set of\n% points X(1:DIM_NUM) such that each X(I) is nonnegative, and\n% sum(X(1:DIM_NUM)) <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Reuven Rubinstein,\n% Monte Carlo Optimization, Simulation, and Sensitivity\n% of Queueing Networks,\n% Wiley, 1986.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, integer N, the number of points.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Output, real X(DIM_NUM,N), the points.\n%\n\n%\n% The construction begins by sampling DIM_NUM+1 points from the\n% exponential distribution with parameter 1.\n%\n for j = 1 : n\n\n [ e, seed ] = r8vec_uniform_01 ( dim_num+1, seed );\n\n e(1:dim_num+1) = -log ( e(1:dim_num+1) );\n\n x(1:dim_num,j) = e(1:dim_num)' / sum ( e(1:dim_num+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/simplex_gm_rule/simplex_unit_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.79730643064319}} {"text": "function area = triangle_area_2d ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_AREA_2D computes the area of a triangle in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the triangle vertices.\n%\n% Output, real AREA, the absolute area of the triangle.\n%\n area = 0.5 * abs ( ...\n t(1,1) * ( t(2,2) - t(2,3) ) ...\n + t(1,2) * ( t(2,3) - t(2,1) ) ...\n + t(1,3) * ( t(2,1) - t(2,2) ) );\n\n return\nend\n", "meta": {"author": "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/triangle_area_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7972443271340975}} {"text": "\nif (~exist('syms.m','file')) \n fprintf('The symbolic toolbox is not installed, skipping test\\n');\n return;\nend\n\n%% Gradients\nclear\nclc\n\nsyms x1 x2\nx = [0.1;0.1];\n\n%OPTI Sym\nfun = @(x) sin(x(1) + x(2)) + (x(1) - x(2))^2 - 1.5*x(1) + 2.5*x(2) + 1\n[jac,jacp] = symJac(fun)\n[hess,hessp] = symHess(fun)\n\n%Symbolic\nsfun = sin(x1+x2) + (x1-x2)^2 - 1.5*x1 + 2.5*x2 + 1\njac1 = jacobian(sfun)\nhess1 = hessian(sfun)\n\n%Eval\n[jac(x);double(subs(jac1,{'x1','x2'},{x(1) x(2)}))]\nfull(jacp())\n[hess(x);double(subs(hess1,{'x1','x2'},{x(1) x(2)}))]\nfull(hessp())\n\n%OPTI Sym\nfun = @(x) [x(1) + x(2) - 1; \n x(1)^2 + x(2)^2 - 1];\njac = symJac(fun)\n\n%Symbolic\nfun = [x1 + x2 - 1; \n x1^2 + x2^2 - 1];\njac1 = jacobian(fun)\n\n%Eval\n[jac(x);double(subs(jac1,{'x1','x2'},{x(1) x(2)}))]\n\n%OPTI Sym\nfun = @(x) 0.01*(x(1)-1)^2 + (x(2)-x(1)^2)^2;\n[jac,jacp] = symJac(fun)\n[hess,hessp] = symHess(fun)\n\n%Symbolic\nsfun = 0.01*(x1-1)^2 + (x2-x1^2)^2;\njac1 = jacobian(sfun)\nhess1 = hessian(sfun)\n\n%Eval\n[jac(x);double(subs(jac1,{'x1','x2'},{x(1) x(2)}))]\nfull(jacp())\n[hess(x);double(subs(hess1,{'x1','x2'},{x(1) x(2)}))]\nfull(hessp())\n\n\n%% Symbolic Hessian of Lagrangian\nclc\nfun = @(x) x(1)*x(4)*(x(1) + x(2) + x(3)) + x(3);\n% Nonlinear Constraints \n nlcon = @(x) [ x(1)*x(2)*x(3)*x(4); \n x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2 ];\n\njac = symJac(fun) \nhessObj = symHess(fun)\n\n[hessLag,pattern] = symHessLag(fun,nlcon,4,true)\n\n\n% Hessian\n H = @(x,sigma,lambda) sparse(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 lambda(2)*diag([2 2 2 2]));\n \n \nx = 0.1:0.1:0.4;\nsigma = 0.3;\nlambda = 1:2;\n\nhessLag(x,sigma,lambda)\nfull(H(x,sigma,lambda))\nfull(pattern())\n\n\n%% Application to an NLP, first no derivs\nclc\n% Objective\n fun = @(x) x(1)*x(4)*(x(1) + x(2) + x(3)) + x(3);\n\n% Nonlinear Constraints \n nlcon = @(x) [ x(1)*x(2)*x(3)*x(4); \n x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2 ];\n cl = [25;40];\n cu = [Inf;40]; \n\n% Bounds (lb <= x <= ub)\n lb = ones(4,1);\n ub = 5*ones(4,1); \n\n% Initial Guess\n x0 = [1 5 5 1]';\n \nopts = optiset('display','iter','solver','ipopt','derivCheck','on','solverOpts',ipoptset('derivative_test','first-order'));\nOpt = opti('fun',fun,'nl',nlcon,cl,cu,'bounds',lb,ub,'x0',x0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\n\n\n%% Application to an NLP, now with symJac, symHessLag\nclc\n% Objective\n fun = @(x) x(1)*x(4)*(x(1) + x(2) + x(3)) + x(3);\n\ngrad = symJac(fun); \n \n% Nonlinear Constraints \n nlcon = @(x) [ x(1)*x(2)*x(3)*x(4); \n x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2 ];\n \n[nljac,nljacstr] = symJac(nlcon);\n \n cl = [25;40];\n cu = [Inf;40]; \n \n %Hessian\n [hess,hstr] = symHessLag(fun,nlcon);\n\n% Bounds (lb <= x <= ub)\n lb = ones(4,1);\n ub = 5*ones(4,1); \n\n% Initial Guess\n x0 = [1 5 5 1]';\n \nopts = optiset('display','iter','solver','ipopt','derivCheck','on','solverOpts',ipoptset('derivative_test','second-order'));\nOpt = opti('fun',fun,'grad',grad,'nl',nlcon,cl,cu,'nljac',nljac,'nljacstr',nljacstr,'H',hess,'HStr',hstr,'bounds',lb,ub,'x0',x0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\n \n\n%% Application to an NLP, analytical derivs supplied\nclc\n% Objective\n fun = @(x) x(1)*x(4)*(x(1) + x(2) + x(3)) + x(3);\n\n% Gradient\n grad = @(x) [x(1)*x(4) + x(4)*sum(x(1:3)), x(1)*x(4),...\n x(1)*x(4) + 1, x(1)*sum(x(1:3))];\n \n% Nonlinear Constraints \n nlcon = @(x) [ x(1)*x(2)*x(3)*x(4); \n x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2 ];\n \n% Jacobian\n jac = @(x) sparse([prod(x')./x';\n 2.*x']);\n\n% Jacobian Structure\n jacstr = @() sparse(ones(2,4));\n \n cl = [25;40];\n cu = [Inf;40]; \n \n %Hessian\n% Hessian\n H = @(x,sigma,lambda) sparse(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 lambda(2)*diag([2 2 2 2]));\n\n% Hessian Structure\n Hstr = @() sparse(tril(ones(4)));\n\n% Bounds (lb <= x <= ub)\n lb = ones(4,1);\n ub = 5*ones(4,1); \n\n% Initial Guess\n x0 = [1 5 5 1]';\n \nopts = optiset('display','iter','solver','ipopt','derivCheck','on','solverOpts',ipoptset('derivative_test','second-order'));\nOpt = opti('fun',fun,'grad',grad,'nl',nlcon,cl,cu,'nljac',nljac,'nljacstr',nljacstr,'H',H,'HStr',hstr,'bounds',lb,ub,'x0',x0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\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/Development/test_sym_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.797220612272447}} {"text": "function n = vectorNorm3d(v)\n%VECTORNORM3D Norm of a 3D vector or of set of 3D vectors\n%\n% N = vectorNorm3d(V);\n% Returns the norm of vector V.\n%\n% When V is a N-by-3 array, compute norm for each vector of the array.\n% Vector are given as rows. Result is then a N-by-1 array.\n%\n% NOTE: compute only euclidean norm.\n%\n% See Also\n% vectors3d, normalizeVector3d, vectorAngle3d, hypot3\n%\n\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 21/02/2005.\n\n% HISTORY\n% 19/06/2009 rename as vectorNorm3d\n\nn = sqrt(sum(v.*v, 2));\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/vectorNorm3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7972206088795434}} {"text": "function result = polygon_x_2d ( n, v )\n\n%*****************************************************************************80\n%\n%% POLYGON_X_2D integrates the function X over a polygon in 2D.\n%\n% Discussion:\n%\n% The polygon is bounded by the points (X(1:N), Y(1:N)).\n%\n% INTEGRAL = (1/6) * sum ( 1 <= I <= N )\n% ( X(I)^2 + X(I) * X(I-1) + X(I-1)^2 ) * ( Y(I) - Y(I-1) )\n%\n% where X(0) and Y(0) should be replaced by X(N) and Y(N).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% S F Bockman,\n% Generalizing the Formula for Areas of Polygons to Moments,\n% American Mathematical Society Monthly,\n% 1989, pages 131-132.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n% N should be at least 3 for a nonzero result.\n%\n% Input, real V(2,N), the coordinates of the vertices\n% of the polygon. These vertices should be given in counter-clockwise order.\n%\n% Output, real RESULT, the value of the integral.\n%\n result = 0.0;\n\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_X_2D - Warning!\\n' );\n fprintf ( 1, ' The number of vertices must be at least 3.\\n' );\n fprintf ( 1, ' The input value of N = %d\\n', n );\n return\n end\n\n for i = 1 : n\n\n if ( i == 1 )\n im1 = n;\n else\n im1 = i - 1;\n end\n\n result = result + ( v(1,i).^2 + v(1,i) * v(1,im1) + v(1,im1).^2 ) ...\n * ( v(2,i) - v(2,im1) );\n\n end\n\n result = result / 6.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_x_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7972206069191615}} {"text": "function pde = Darcydata4\n%% Darcydata4 diagonal and anisotropic tensor\n%\n% p = x^2 + y^2\n% K = [1 + 4*(x^2 + y^2) 0 ]\n% = [0 1 + 11*(x^2 + y^2)]\n\npde = struct('exactp',@exactp,'K',@K,'exactu',@exactu,'Dp',@gradp,...\n 'f', @f,'g_D',@g_D,'g_N',@g_N);\n\n function s = K(pt)\n x = pt(:,1); y = pt(:,2);\n% s(:,3) = 3*x.*y; \n s(:,1) = 1 + 4*(x.^2 + y.^2);\n s(:,2) = 1 + 11*(x.^2 + y.^2);\n end\n function s = exactp(pt)\n x = pt(:,1); y = pt(:,2);\n% s = x.^3.*y + y.^4 + sin(pi*x).*cos(pi*y);\n s = x.^2 + y.^2;\n end\n function s = gradp(pt)\n x = pt(:,1); y = pt(:,2);\n% s(:,2) = x.^3 + 4*y.^3 - pi*sin(pi*x).*sin(pi*y);\n% s(:,1) = 3*x.^2.*y + pi*cos(pi*x).*cos(pi*y); \n s(:,2) = 2*y;\n s(:,1) = 2*x; \n end\n function s = exactu(pt)\n Dp = gradp(pt); % u = K*grad(p)\n K = K(pt);\n s(:,2) = K(:,2).*Dp(:,2);\n s(:,1) = K(:,1).*Dp(:,1);\n end\n function s = f(pt)\n x = pt(:,1); y = pt(:,2);\n% s = 2+24*x.^2+14*y.^2+6*x.^2+2+22*x.^2+66*y.^2;\n s = 2+24*x.^2+16*y.^2++2+22*x.^2+66*y.^2;\n s = -s;\n end\n function s = g_D(pt)\n s = exactp(pt); \n end\n function f = g_N(p,vargin)\n if nargin > 1\n f = dot(exactu(p),vargin,2);\n else\n f = zeros(size(p,1),1);\n x = p(:,1); \n y = p(:,2);\n uprime = exactu(p);\n leftbd = (abs(x)= sum(isnan(yhat)) \n yhat(isnan(y))=[];\n y(isnan(y))=[];\n else\n y(isnan(yhat))=[]; \n yhat(isnan(yhat))=[];\n end\nend\n\n% 1 - SSe/SSt\nR2 = 1 - ( sum( (y-yhat).^2 ) / sum( (y-mean(y)).^2 ) );\n\n% SSr/SSt\n% R2 = sum((yhat-mean(y)).^2) / sum( (y-mean(y)).^2 ) ;\n\nif R2<0 || R2>1\n error(['R^2 of ',num2str(R2),' : yhat does not appear to be the estimate of y from a regression.'])\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/13872-rsquare/rsquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7968693552357399}} {"text": "function dist = sphere_distance_xyz ( xyz1, xyz2 )\n\n%*****************************************************************************80\n%\n%% SPHERE_DISTANCE_XYZ computes great circle distances on a sphere.\n%\n% Discussion:\n%\n% XYZ coordinates are used.\n%\n% We assume the points XYZ1 and XYZ2 lie on the same sphere.\n%\n% This computation is a special form of the Vincenty formula.\n% It should be less sensitive to errors associated with very small\n% or very large angular separations.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% \"Great-circle distance\",\n% Wikipedia.\n%\n% Parameters:\n%\n% Input, real XYZ1(3), the coordinates of the first point.\n%\n% Input, real XYZ2(3), the coordinates of the second point.\n%\n% Output, real DIST, the great circle distance between the points.\n%\n r = norm ( xyz1 );\n\n lat1 = r8_asin ( xyz1(3) );\n lon1 = r8_atan ( xyz1(2), xyz1(1) );\n\n lat2 = r8_asin ( xyz2(3) );\n lon2 = r8_atan ( xyz2(2), xyz2(1) );\n\n top = ( cos ( lat2 ) * sin ( lon1 - lon2 ) ).^2 ...\n + ( cos ( lat1 ) * sin ( lat2 ) ...\n - sin ( lat1 ) * cos ( lat2 ) * cos ( lon1 - lon2 ) ).^2;\n\n top = sqrt ( top );\n\n bot = sin ( lat1 ) * sin ( lat2 ) ...\n + cos ( lat1 ) * cos ( lat2 ) * cos ( lon1 - lon2 );\n\n dist = r * atan2 ( top, bot );\n\n return\nend\n", "meta": {"author": "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_distance_xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7968693470162734}} {"text": "%%% This program provides a numerical verification that equations (15.2)\n%%% and (15.6) coincide in a 2x2 case. The program generates a random 2x2\n%%% GOE matrix H and uses it to compute the numerical value of Z(x)\n%%% according to the two formulas. You will be asked to choose the real and\n%%% imaginary parts of the number x (imaginary part has to be positive).\n\nclear all\nclose all\n\n%%% Reads the real part from the Command Window\nprompt = '\\n Choose real part of argument x: ';\nre = input(prompt);\n\n%%% Reads the imaginary part from the Command Window\nprompt = '\\n Choose imaginary part of argument x: ';\nim = input(prompt);\n\nif im <= 0\n sprintf('ERROR: Imaginary part has to be positive')\n return;\nend\n\nx = re - i*im;\n\n%%% Generating 2x2 GOE matrix\nH = randn(2)/sqrt(2);\nH = (H + H')/2;\n\n%%% Eigenvalues of matrix H\nE = eig(H);\n\n%%% Definition of integrand function for Z\nf = @(y1,y2) exp(-i*((x-H(1,1)).*y1.^2 + 2.*H(1,2).*y1.*y2 + (x-H(2,2)).*y2.^2)/2);\n\n%%% Z function\nZ = integral2(f,-Inf,Inf,-Inf,Inf);\n\n%%% Explicit form of Z function\nZ_exp = 2*pi*exp(-(log(E(1)-x) + log(E(2)-x))/2 + i*pi/2);\n\nsprintf('Value of Z function computed as integral: %6.4f%+6.4fi',real(Z),imag(Z))\nsprintf('Value of Z function computed explicitly via eigenvalues of H: %6.4f%+6.4fi',real(Z_exp),imag(Z_exp))\n\n", "meta": {"author": "RMT-TheoryAndPractice", "repo": "RMT", "sha": "8710c8bafb25b0abde206c9d869a8acdd582dbed", "save_path": "github-repos/MATLAB/RMT-TheoryAndPractice-RMT", "path": "github-repos/MATLAB/RMT-TheoryAndPractice-RMT/RMT-8710c8bafb25b0abde206c9d869a8acdd582dbed/Zmultiple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090975, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7968380508425176}} {"text": "function AInv=invert2X2Matrix(A)\n%%INVERT2X2MATRIX Inver the 2X2 matrix A. This function demonstrates the\n% algorithm given in [1], which is more efficient than Gaussian\n% elimination. This could be used as a template for implementation in\n% other languages. In Matlab, this function is not faster than the\n% built-in inv function.\n%\n%INPUTS: A A 2X2 real or complex invertible matrix.\n%\n%OUTPUTS: AInv The 2X2 matrix inverse of A. \n%\n%EXAMPLE:\n%This just shows that this function produces the same result as Matlab\n%within finite precision limitations.\n% A=randn(2,2);\n% C=invert2X2Matrix(A);\n% C1=inv(A);%Matlab's way.\n% RelErr=max(max(abs(abs((C-C1)./C1))))\n%\n%REFERENCES:\n%[1] V. Strassen, \"Gaussian elimination is not optimal,\" Numerische\n% Mathematik, vol. 13, pp. 354-356, 1965.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nI=1/A(1,1);\nII=A(2,1)*I;\nIII=I*A(1,2);\nIV=A(2,1)*III;\nV=IV-A(2,2);\nVI=1/V;\n\nAInv=zeros(2,2);\nAInv(1,2)=III*VI;\nAInv(2,1)=VI*II;\nVII=III*AInv(2,1);\nAInv(1,1)=I-VII;\nAInv(2,2)=-VI;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/Fixed_Size_Operations/invert2X2Matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8807970842359876, "lm_q1q2_score": 0.7968135535693902}} {"text": "% Demo script for software from the paper\n% 'Generating spike-trains with specified correlations',\n% Macke et al., submitted for publication, 2008\n%\n% www.kyb.mpg.de/bethgegroup/code/efficientsampling\n%\n% Instructions:\n% - Change to the code directory and run demo.m\n% - The script will take you through the functions .\n% - After each step, the script will pause. \n% - To continue, hit any button.\n% - Read along in the demo.m file to follow what's happening.\n%\n% If you have questions, feel free to email us.\n\nf = 1;\nfprintf('\\nDemo program for GENERATING SPIKE TRAINS WITH SPECIFIED CORRELATIONS, Macke et al.\\n')\n\n\n%% Step 1: Generating correlated binary variables (2D example)\nmu = [.4,.3]'; % set the mean\nv = mu.*(1-mu); % calculate the variances\nC = diag(v); % build covariance matrix\nC(1,2) = .1;\nC(2,1) = .1;\n\n[S,g,L] = sampleDichGauss01(mu,C,1e5); % generate samples from the DG model\n\nmuHat = mean(S,2); % estimate mean\nCHat = cov(S'); % estimate covariance\n\nfprintf('\\nStep 1: Generating correlated binary variables (section 2.1)\\n\\n')\nfprintf('Target mean X1: %.2f Estimated mean X1: %.3f\\n',mu(1),muHat(1))\nfprintf('Target mean X2: %.2f Estimated mean X2: %.3f\\n',mu(2),muHat(2))\nfprintf('Target cov X1X2: %.2f Estimated cov X1X2: %.3f\\n',C(1,2),CHat(1,2))\n\ndisp('To proceed to compare histograms, hit any key...')\npause\n\n%% Step 2: How much do correlations change the distribution when means are\n% assumed to be equal?\n\nfprintf('\\nStep 2: Effect of correlations\\n\\n')\nfprintf('Computing...\\n')\n\n% First, we generate a mean vector in ten dimensions. We assume that all\n% means are approximately .5, but we add some Gaussian noise to the network\n% is not to uniform. We set the covariances so that the resulting\n% correlations are sizable, but not to large (~0.1). \n\nmu = ones(10,1) * .2 + randn(10,1)*0.05;\nv = mu.*(1-mu);\nC = ones(10,10) * .02;\nC(eye(size(C))==1) = v;\n\n% We find the histogram of the independent distribution with this mean\n% vector P(x) = PROD_i P(X_i=1) and the DG distribution with the same mean\n% and the covariances as defined above.\n\nh1 = binHistIndep(mu); % returns the histogram of an independet distribution\nS = sampleDichGauss01(mu,C,1e5);\nh2 = binHist(S); % creates a histogram of the binary patterns in S\nh2 = h2 / sum(h2);\n\n% When we compare them, we see that some patterns occur much more often \n% in the correlated then in the independent distribution. This a clear\n% indication of the strength of the correlations. The \"stripes\" coincide\n% with patterns with a different number of active neurons (starting at 0 in\n% the upper left corner).\n\nfigure(f)\nloglog(h1,h2,'k.')\nxlabel('P(X) in independent model')\nylabel('P(X) in DG model')\ntitle('Step 2: What effect do correlations have?')\naxis square\n\nf = f+1;\n\n\ndisp('To proceed to generate Poisson RVs, hit any key...')\npause\n\n%% Step 3: Correlated Poisson from a binary process (3.1)\n% First, we generate samples from a correlated Poisson distribution with\n% specified mean and covariance matrix. The covariance between the two\n% distributions is positive and quite strong. The construction follows the\n% description in section 3.1, i.e. we first find a binary process with the\n% correct parameters and sum over it. This means we create\n% a joint Poisson distribution.\n\nfprintf('\\nStep 3: Correlated Poisson from a binary process (3.1)\\n\\n')\nfprintf('Computing...\\n')\n\nmu = [7,9]'; % set the mean\nC = [7 3;3 9]; % set an admissable covariance matrix\n\nS = sampleCovPoisson(mu,C,10000); % generate sample via discretized Gaussian\n\n% We obtain a set of samples S. Next, we verify that the samples have \n% desired mean and covariance structure. We see that this is indeed the case.\n\nmuHat = mean(S,2);\nCHat = cov(S');\n\nfprintf('Target mean X1: %.2f Estimated mean X1: %.3f\\n',mu(1),muHat(1))\nfprintf('Target mean X2: %.2f Estimated mean X2: %.3f\\n',mu(2),muHat(2))\nfprintf('Target cov X1X2: %.2f Estimated cov X1X2: %.3f\\n',C(1,2),CHat(1,2))\n\ndisp('To plot the marginals and joint histogram, hit any key...')\npause\nfprintf('Computing...\\n')\n\nfigure (f)\n\n% Now, we look at the marginal distribution we obtain from our sampling\n% procedure. For comparison, we also plot the true 1D Poisson distributions\n% as specified by the mean of the marginal (dotted). We see that they are\n% very close to one another. \n\nh1 = histc(S(1,:),0:30); h1 = h1/sum(h1);\nh2 = histc(S(2,:),0:30); h2 = h2/sum(h2);\n\nsubplot(1,2,1)\nplot(0:length(h1)-1,h1,'-r','markersize',5), hold on\nplot(0:length(h1),poisspdf(0:length(h1),mu(1)),'.r','markersize',5)\nplot(0:length(h2)-1,h2,'-g','markersize',5)\nplot(0:length(h1),poisspdf(0:length(h1),mu(2)),'.g','markersize',5)\nt = legend('X_1','X_1 Poisson','X_2','X_2 Poisson');\nset(t,'box','off')\naxis square\nxlabel('X'), ylabel('P(X)')\ntitle(sprintf('Step 3: Correlated Poisson, Positive Correlation\\nMarginal Distributions with Poisson\\n distribution with correct mean'))\n\n% Finally, we convince ourselves that the two variables are indeed\n% positively correlated by looking at the 2D joint histogram. We can see\n% that although the marginals are perfect Poissonian, most samples are\n% concentrated along the main diagonal, indicating the positive\n% correlation.\n\nsubplot(1,2,2)\nhh = EstimateDiscreteJoint(S);\nimagesc(hh)\naxis square\ntitle('')\nxlabel('X_1'), ylabel('X_2')\n\ndisp('To proceed to positively correlated Poisson variables with another method, hit any key...')\npause\n\n\nf = f+1;\n\n\n%% Step 4: Generating correlated Poisson variables via the method \n% in section 3.3 for positive correlations\n%\n% Again, we generate samples from a correlated Poisson distribution with\n% specified mean and covariance matrix. The covariance between the two\n% distributions is positive and quite strong. The construction follows now\n% section 3.3, so we truncate a Gaussian to obtain a distribution with\n% Poisson marginals and a given covariance.\n\nfprintf('\\nStep 4: Generating positively correlated Poisson variables (section 3.3)\\n\\n')\nfprintf('Computing...\\n')\n\nmu = [7,9]'; % set the mean\nC = [7 3;3 9]; % set an admissable covariance matrix\n\n[S,gamma,Lambda,joints2D] = DGPoisson(mu,C,1e5); % generate sample via discretized Gaussian\n\n% We obtain a set of samples S, the parameters of the hidden Gaussian\n% variable (gamma and Lambda) and a structure containing the marginal\n% distributions as well as the 2D joint distribution\n\n% Next, we verify that the samples have desired mean and covariance\n% structure. We see that this is indeed the case.\n\nmuHat = mean(S,2);\nCHat = cov(S');\n\n\nfprintf('Target mean X1: %.2f Estimated mean X1: %.3f\\n',mu(1),muHat(1))\nfprintf('Target mean X2: %.2f Estimated mean X2: %.3f\\n',mu(2),muHat(2))\nfprintf('Target cov X1X2: %.2f Estimated cov X1X2: %.3f\\n',C(1,2),CHat(1,2))\n\ndisp('To plot the marginals and joint histogram, hit any key...')\npause\n\nfigure(f)\n\n% Now, we look at the marginal distribution we obtain from our sampling\n% procedure. For comparison, we also plot the true 1D Poisson distributions\n% as specified by the mean of the marginal (dotted). We see that they are\n% very close to one another. \n\nsubplot(2,2,1)\nh1 = joints2D{1,1}; % marginal of X_1\nh2 = joints2D{2,2}; % marginal of X_2\nplot(0:length(h1)-1,h1,'-r','markersize',5), hold on\nplot(0:length(h1),poisspdf(0:length(h1),mu(1)),'.r','markersize',5)\nplot(0:length(h2)-1,h2,'-g','markersize',5)\nplot(0:length(h1),poisspdf(0:length(h1),mu(2)),'.g','markersize',5)\nt = legend('X_1','X_1 Poisson','X_2','X_2 Poisson');\nset(t,'box','off')\naxis square\nxlabel('X'), ylabel('P(X)')\ntitle(sprintf('Step 4: Correlated Poisson, Positive Correlation\\nMarginal Distributions with Poisson\\n distribution with correct mean'))\n\n% Finally, we convince ourselves that the two variables are indeed\n% positively correlated by looking at the 2D joint histogram. We can see\n% that although the marginals are perfect Poissonian, most samples are\n% concentrated along the main diagonal, indicating the positive\n% correlation.\n\nsubplot(2,2,3)\nhh = joints2D{2}; % joint histogram\nimagesc(hh)\naxis square\ntitle('')\nxlabel('X_1'), ylabel('X_2')\n\ndisp('To proceed to negatively correlated Poisson variables, hit any key...')\npause\n\n%% Step 5: Generating correlated Poisson variables via the method \n% in section 3.3 for negative correlations\n%\n% Again, we generate samples from a correlated Poisson distribution with\n% specified mean and covariance matrix. This time the covariance is\n% negative though.\n\nfprintf('\\nStep 5: Generating negatively correlated Poisson variables (section 3.3)\\n\\n')\nfprintf('Computing...\\n')\n\nmu = [7,9]'; % set the mean\nC = [7 -3;-3 9]; % set an admissable covariance matrix\n\n[S,gamma,Lambda,joints2D] = DGPoisson(mu,C,1e5); % generate sample via discretized Gaussian\n\n% Next, we verify that the samples have desired mean and covariance\n% structure. We see that this is indeed the case. \n\nmuHat = mean(S,2);\nCHat = cov(S');\n\nfprintf('Target mean X1: %.2f Estimated mean X1: %.3f\\n',mu(1),muHat(1))\nfprintf('Target mean X2: %.2f Estimated mean X2: %.3f\\n',mu(2),muHat(2))\nfprintf('Target cov X1X2: %.2f Estimated cov X1X2: %.3f\\n',C(1,2),CHat(1,2))\n\ndisp('To plot the marginals and joint histogram, hit any key...')\npause\n\nfigure(f)\n\n% Again we compare the marginal distributions to the Poisson distribution\n% with the same mean and we find them matching very well.\n\nsubplot(2,2,2)\nh1 = joints2D{1,1}; % marginal of X_1\nh2 = joints2D{2,2}; % marginal of X_2\nplot(0:length(h1)-1,h1,'-r','markersize',5), hold on\nplot(0:length(h1),poisspdf(0:length(h1),mu(1)),'.r','markersize',5)\nplot(0:length(h2)-1,h2,'-g','markersize',5)\nplot(0:length(h1),poisspdf(0:length(h1),mu(2)),'.g','markersize',5)\nt = legend('X_1','X_1 Poisson','X_2','X_2 Poisson');\nset(t,'box','off')\naxis square\nxlabel('X'), ylabel('P(X)')\ntitle(sprintf('Step 5: Correlated Poisson, Negative Correlation\\nMarginal Distributions with Poisson\\n distribution with correct mean'))\n\n% Nevertheless, the samples have a different structure as we can see from\n% the 2D joint histogram. This time, the two variables are negatively\n% correlated and when X_1 tends to take large values, X_2 tends to take low\n% ones. \n\nsubplot(2,2,4)\nhh = joints2D{2}; % joint histogram\nimagesc(hh)\naxis square\ntitle('')\nxlabel('X_1'), ylabel('X_2')\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20591-sampling-from-multivariate-correlated-binary-and-poisson-random-variables/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7967862276696893}} {"text": "function mel = frq2mel(frq)\n%FRQ2ERB Convert Hertz to Mel frequency scale MEL=(FRQ)\n%\tmel = frq2mel(frq) converts a vector of frequencies (in Hz)\n%\tto the corresponding values on the Mel scale which corresponds\n%\tto the perceived pitch of a tone\n\n%\tThe relationship between mel and frq is given by:\n%\n%\tm = ln(1 + f/700) * 1000 / ln(1+1000/700)\n%\n% \tThis means that m(1000) = 1000\n%\n\nmel = sign(frq).*log(1+abs(frq)/700)*1127.01048;\nif ~nargout\n plot(frq,mel,'-x');\n xlabel(['Frequency (' xticksi 'Hz)']);\n ylabel(['Frequency (' yticksi 'Mel)']);\nend\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/第11章 说话人识别/11.2 基于高斯混合模型(GMM)的说话人识别实验/frq2mel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7967862226372291}} {"text": "%{\nTest the trace-constrained least-squares problem with positive\nsemi-definite matrix variables\n\n minimize (1/2)*norm( A * X - b )^2 \n with the constraint that X is positive semi-definite ( X >= 0 )\nand optionally,\n the constraint trace(X) <= lambda\n\n%}\n\n% Try to load the problem from disk\nfileName = fullfile('reference_solutions','traceLS_problem2_noisy');\nif exist([fileName,'.mat'],'file')\n load(fileName);\n fprintf('Loaded problem from %s\\n', fileName );\nelse\n % Generate a new problem\n randn('state',sum('Trace')+5);\n rand('state',sum('Trace2')+5);\n \n N = 30; R = 2;\n \n df = R*N;\n oversample = 5;\n Left = randn(M,R);\n Right = Left;\n k = round(oversample*df); \n k = min( k, round(.8*N*N) );\n omega = randperm(N*N);\n omega = sort(omega(1:k)).';\n\n X_original = Left*Right'; % the \"original\" signal -- may not be optimal value\n b_original = X_original(omega); \n EPS = .001; % noise level\n noise = EPS * randn(k,1); % this destroys symmetry...\n b = b_original + noise;\n lambda = trace( X_original );\n objective = @(X) sum_square( X(omega) - b )/2;\n obj_original = objective(X_original);\n\n % get references via CVX\n cvx_begin\n cvx_precision best\n cvx_quiet true\n variable Xcvx(N,N)\n minimize objective(Xcvx)\n subject to\n Xcvx == semidefinite(N)\n cvx_end\n X_reference_noTraceConstraint = Xcvx; \n fprintf('Difference between convex solution (no trace constraint) and original signal: %.2e\\n', ...\n norm( Xcvx - X_original, 'fro' ) );\n \n cvx_begin\n cvx_precision best\n cvx_quiet true\n variable Xcvx(N,N)\n minimize objective(Xcvx)\n subject to\n Xcvx == semidefinite(N)\n trace(Xcvx) <= lambda\n cvx_end\n X_reference = Xcvx; % the trace norm minimizer \n obj_reference = objective(X_reference);\n fprintf('Difference between convex solution (with trace constraint) and original signal: %.2e\\n', ...\n norm( Xcvx - X_original, 'fro' ) );\n save(fileName,'X_original','X_reference','X_reference_noTraceConstraint',...\n 'omega','b','obj_original',...\n 'Left','EPS','b_original','R','obj_reference','lambda');\n fprintf('Saved data to file %s\\n', fileName);\n \nend\n\n[M,N] = size(X_reference);\nnorm_X_reference = norm(X_reference,'fro');\ner_reference = @(x) norm(x-X_reference,'fro')/norm_X_reference;\nnorm_X_reference2= norm(X_reference_noTraceConstraint,'fro');\ner_reference2 = @(x) norm(x-X_reference_noTraceConstraint,'fro')/norm_X_reference2;\nobjective = @(X) norm( X(omega) - b )^2/2;\n\n[omegaI,omegaJ] = ind2sub([M,N],omega);\nmat = @(x) reshape(x,M,N);\nvec = @(x) x(:);\n \nk = length(omega);\np = k/(M*N);\ndf = R*(M+N-R);\nfprintf('%d x %d rank %d matrix, observe %d = %.1f x df = %.1f%% entries\\n',...\n M,N,R,k,k/df,p*100);\nfprintf(' Trace norm solution and original matrix differ by %.2e\\n',...\n norm(X_reference-X_original,'fro')/norm_X_reference );\n%% Solve unconstrained version. No smoothing is necessary!\nopts = struct('maxIts',500);\nopts.errFcn{1} = @(f,x) er_reference2(x); % no trace constraint\nopts.errFcn{2} = @(f,x) sum( abs(eig(x)) > 1e-5 ); % numerical rank\n% tell it to use eigs instead of eig\n% opts.largescale = true; % ( but not recommended)\n\n% opts.symmetrize = true; % another option\n\nA = sparse( omegaI,omegaJ,b,N,N);\n[x,out] = solver_psdComp( A, opts );\n% Note: we do not expect to get zero error because there might be more\n% than one optimal solution for this problem (since there are not\n% so many constraints)\n% Check that we have a feasible solution\nfprintf('Objective is %.2e, min eigenvalue is %.2e\\n', objective(x),...\n min(eig(x)) );\n%% Solve trace constrained version. No smoothing necessary!\nopts = struct('maxIts',1500,'tol',1e-9);\nopts.errFcn{1} = @(f,x) er_reference(x); % no trace constraint\nopts.errFcn{2} = @(f,x) trace(x)-lambda;\nopts.errFcn{3} = @(f,x) sum( abs(eig(x)) > 1e-5 ); % numerical rank\n% we can also symmetrize \"omega\", but it makes little difference,\n% and gives slightly differen value than CVX, since CVX symmetrizes\n% differently:\n% opts.symmetrize = true;\nA = sparse( omegaI,omegaJ,b,N,N);\n[x,out] = solver_psdCompConstrainedTrace( A,lambda, opts );\n\nh=figure();\nsemilogy(out.err(:,1));\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-5\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n\n%%\nclose(h)\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/smallscale/test_psdCompletion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8652240964782012, "lm_q1q2_score": 0.7966894228920495}} {"text": "function [theta, phi, r] = besa_transformCartesian2Spherical(X, Y, Z)\n% BESA_TRANSFORMCARTESIAN2SPHERICAL takes the cartesian coordinates X, Y \n% and Z of a 3D point and transforms them to the spherical coordinates \n% theta, phi and r. \n%\n% Parameters:\n% [X]\n% The X-coordinate of the current 3D point. It should point to the\n% right.\n% \n% [Y]\n% The Y-coordinate of the current 3D point. It should point\n% foreward.\n% \n% [Z]\n% The Z-coordinate of the current 3D point. It should point up.\n% \n% \n% Return:\n% [theta] \n% The azimuth angle with the vertical z-axis (0 degree) in the \n% x-z-plane, +90 degree lie in the positive x-axis.\n% \n% [phi] \n% The latitude angle in the horizontal x-y-plane \n% (counter-clockwise).\n%\n% [r] \n% The radius.\n\n% Copyright (C) 2015, BESA GmbH\n%\n% File name: besa_transformCartesian2Spherical.m\n%\n% Author: Todor Jordanov\n% Created: 2015-07-29\n\nSquareOfRadiusXY = X*X + Y*Y;\nRadiusXY = sqrt(SquareOfRadiusXY);\n\nif(RadiusXY == 0.0 && Z == 0.0)\n\n theta = 0.0;\n\nelse\n\n theta = atan2d(RadiusXY, Z);\n\nend\n\nif(X==0.0 && Y==0.0)\n\n phi = 0.0;\n\nelse\n\n phi = atan2d(Y, X);\n\nend\n\n% square of total radius\nSquareOfRadiusXY = SquareOfRadiusXY + Z*Z;\n\nr = sqrt(SquareOfRadiusXY);\n\n% set phi & theta to BESA ranges\nif(phi > 90.)\n\n phi = phi - 180.0;\n theta = -theta;\n\nelseif(phi < -90.) \n\n phi = phi+180.0;\n theta = -theta;\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/besa/besa_transformCartesian2Spherical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377308419051, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.796681971099136}} {"text": "function volume = ellipsoid_volume ( m, a, v, r )\n\n%*****************************************************************************80\n%\n%% ELLIPSOID_VOLUME returns the volume of an ellipsoid.\n%\n% Discussion:\n%\n% The points X in the ellipsoid are described by an M by M\n% positive definite symmetric matrix A, an M-dimensional point V,\n% and a \"radius\" R, such that\n% (X-V)' * A * (X-V) <= R * R\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, real A(M,M), the matrix that describes\n% the ellipsoid. A must be symmetric and positive definite.\n%\n% Input, real V(M), the \"center\" of the ellipse.\n% The value of V is not actually needed by this function.\n%\n% Input, real R, the \"radius\" of the ellipse.\n%\n% Output, real VOLUME, the volume of the ellipsoid.\n%\n [ u, info ] = r8po_fa ( m, a );\n \n sqrt_det = 1.0;\n for i = 1 : m\n sqrt_det = sqrt_det * u(i,i);\n end\n\n volume = r ^ m * hypersphere_unit_volume ( m ) / sqrt_det;\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/ellipsoid_monte_carlo/ellipsoid_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7966819621677819}} {"text": "function geometry_test0493 ( )\n\n%*****************************************************************************80\n%\n%% TEST0493 tests PARABOLA_EX, PARABOLA_EX2.\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, 'TEST0493\\n' );\n fprintf ( 1, ' PARABOLA_EX finds the extreme value of a parabola\\n' );\n fprintf ( 1, ' determined by three points.\\n' );\n fprintf ( 1, ' PARABOLA_EX2 finds the extreme value of a parabola\\n' );\n fprintf ( 1, ' determined by three points.\\n' );\n\n a = 2.0;\n b = -4.0;\n c = 10.0;\n\n x1 = 1.0;\n y1 = a * x1 * x1 + b * x1 + c;\n x2 = 2.0;\n y2 = a * x2 * x2 + b * x2 + c;\n x3 = 3.0;\n y3 = a * x3 * x3 + b * x3 + c;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Parabolic coefficients (A,B,C) = %f %f %f\\n', a, b, c );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X, Y data\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X1, Y1 = %f %f\\n', x1, y1 );\n fprintf ( 1, ' X2, Y2 = %f %f\\n', x2, y2 );\n fprintf ( 1, ' X3, Y3 = %f %f\\n', x3, y3 );\n\n a = 0.0;\n b = 0.0;\n c = 0.0;\n\n [ xmin, ymin, ierror ] = parabola_ex ( x1, y1, x2, y2, x3, y3 );\n\n if ( ierror == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PARABOLA_EX returns (XMIN,YMIN) = %f %f\\n', xmin, ymin );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PARABOLA_EX returns error code %d\\n', ierror );\n end\n\n [ xmin, ymin, a, b, c, ierror ] = parabola_ex2 ( x1, y1, x2, y2, x3, y3 );\n\n if ( ierror == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PARABOLA_EX2 returns (XMIN,YMIN) = %f %f\\n', xmin, ymin );\n fprintf ( 1, ' and (A,B,C) = %f %f %f\\n', a, b, c );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PARABOLA_EX2 returns error code %d\\n', ierror );\n end\n\n return\nend\n", "meta": {"author": "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_test0493.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.7966632086827478}} {"text": "classdef RiceD\n%%RICED Functions to handle the Rice distribution.\n%Implemented methods are: mean, var, PDF, CDF, rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n \nfunction val=mean(s,sigma)\n%%MEAN Obtain the mean of the Rice distribution for given noncentrality\n% and scale parameters.\n%\n%INPUTS: s The noncentrality parameter of the distribution.\n% sigma The scale parameter of the distribution.\n%\n%OUTPUTS: val The mean of the Rice distribution.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n param=-s^2/(2*sigma^2);\n val=sigma*sqrt(pi/2)*exp(param/2)*((1-param)*besseli(0,-param/2)-param*besseli(1,-param/2));\nend\n\nfunction val=var(s,sigma)\n%%VAR Obtain the variance of the Rice distribution for given noncentrality\n% and scale parameters.\n%\n%INPUTS: s The noncentrality parameter of the distribution.\n% sigma The scale parameter of the distribution.\n%\n%OUTPUTS: val The variance of the Rice distribution.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n param=-s^2/(2*sigma^2);\n L=exp(param/2)*((1-param)*besseli(0,-param/2)-param*besseli(1,-param/2));\n val=2*sigma^2+s^2-pi*(sigma^2/2)*L^2;\nend \n \nfunction val=PDF(x,s,sigma)\n%%PDF Evaluate the Rice probability distribution function at one or more\n% desired points.\n%\n%INPUTS: x The point(s) at which the Rice PDF is to be evaluated. Note that\n% x>=0.\n% s The noncentrality parameter of the distribution.\n% sigma The scale parameter of the distribution.\n%\n%OUTPUTS: val The value(s) of the Rice PDF with parameters s and sigma\n% evaluated at x.\n%\n%The PDF of the Rice distribution is given in Chapter 2.1.4 of [1].\n%\n%REFERENCES:\n%[1] J. G. Proakis, Digital Communications. Ed. 4, Boston, MA:\n% McGraw Hill, 2001.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n %We are evaluating \n %val=(x/sigma^2).*exp(-(x.^2+s^2)/(2*sigma^2)).*besseli(0,x*s/sigma^2);\n %However, if x*s/sigma^2 is large, then this function could return\n %NaNs. large doesn't have to be all that large. For example, s=30,\n %sigma=1, x=100. means that ratio is 3000. Thus, we use besseli with\n %the third argument to get a scaled value, then take the logarithm, do\n %everything else in the logarithmic domain and take the exponent to\n %undo the logarithm.\n \n besselArg=x*s/sigma^2;\n val=exp(log(besseli(0,besselArg,1))+besselArg-(x.^2+s^2)/(2*sigma^2)+log(x/sigma^2));\nend\n\nfunction val=CDF(x,s,sigma)\n%%CDF Evaluate the cumulative distribution function of the Rice\n% distribution at desired points.\n%\n%INPUTS: x The point(s) at which the Rice CDF is to be evaluated. Note that\n% x>=0.\n% s The noncentrality parameter of the distribution.\n% sigma The scale parameter of the distribution.\n%\n%OUTPUTS: prob The value(s) of the CDF of the Rice distribution with\n% parameters k and theta evaluated at x.\n%\n%The CDF of the Rice distribution can be expressed in terms of Marcum's Q\n%function as shown in Chapter 2.1.4 of [1].\n%\n%REFERENCES:\n%[1] J. G. Proakis, Digital Communications. Ed. 4, Boston, MA:\n% McGraw Hill, 2001.\n%\n%February 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n numPoints=length(x(:));\n val=zeros(size(x));\n \n for curPoint=1:numPoints\n val(curPoint)=1-MarcumQ(1,s/sigma,x(curPoint)/sigma);\n end\nend\n\n\nfunction vals=rand(N,s,sigma)\n%%RAND Generate Rice-distributed random variables with the given\n% parameters.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% s The noncentrality parameter of the distribution.\n% sigma The scale parameter of the distribution.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated Rice random variables.\n%\n%This generates Rice distributed random variables by transforming normally\n%distributed random variables using the identity given in Chapter 2.1.4 of\n%[1].\n%\n%REFERENCES:\n%[1] J. G. Proakis, Digital Communications. Ed. 4, Boston, MA:\n% McGraw Hill, 2001.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(isscalar(N))\n dims=[N, N];\n else\n dims=N;\n end\n\n m=s/sqrt(2);\n\n X=sigma*randn(dims)+m;\n Y=sigma*randn(dims)+m;\n\n vals=sqrt(X.^2+Y.^2);\nend\n \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/RiceD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7966021668219303}} {"text": "function p = gaussProb(X, mu, Sigma)\n% Multivariate Gaussian distribution, pdf\n% X(i,:) is i'th case\n% *** In the univariate case, Sigma is the variance, not the standard\n% deviation! ***\n\n% This file is from pmtk3.googlecode.com\n\n\nd = size(Sigma, 2);\nX = reshape(X, [], d); % make sure X is n-by-d and not d-by-n\nX = bsxfun(@minus, X, rowvec(mu));\nlogp = -0.5*sum((X/(Sigma)).*X, 2); \nlogZ = (d/2)*log(2*pi) + 0.5*logdet(Sigma);\nlogp = logp - logZ;\np = exp(logp); \n\nend\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/lib/utils/gaussProb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.796585216523325}} {"text": "function h = r8mat_house_form ( n, v )\n\n%*****************************************************************************80\n%\n%% R8MAT_HOUSE_FORM constructs a Householder matrix from its compact form.\n%\n% Discussion:\n%\n% H(v) = I - 2 * v * v' / ( v' * v )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real V(N), the vector defining the Householder matrix.\n%\n% Output, real H(N,N), the Householder matrix.\n%\n\n%\n% Compute the L2 norm of V.\n%\n beta = sum ( v(1:n).^2 );\n%\n% Form the matrix H.\n%\n h = r8mat_identity ( n );\n\n for i = 1 : n\n for j = 1 : n\n h(i,j) = h(i,j) - 2.0 * v(i) * v(j) / beta;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/r8mat_house_form.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7965852142511203}} {"text": "function [ X ] = LineFaceIntersection( faceX, faceN, lineX, lineD )\n%LINEFACEINTERSECTION Intersection of a plane and a line\n% faceX: a point on the plane\n% faceN: the normal direction of the plane\n% lineX: a point on the line\n% lineD: direction of the line\n%\n\n% A = dot(faceN,lineD,2)/lineD(1);\n% B = -dot(faceX,faceN,2) + (dot(lineX(2:3),faceN(2:3),2)) - lineX(1)/lineD(1)*(dot(lineD(2:3),faceN(2:3),2));\nA = sum(faceN.*lineD)/lineD(1);\nB = -sum(faceX.*faceN) + (sum(lineX(2:3).*faceN(2:3),2)) - lineX(1)/lineD(1)*(sum(lineD(2:3).*faceN(2:3),2));\n\nx = -B/A;\n\ny = (x-lineX(1))/lineD(1)*lineD(2) + lineX(2);\nz = (x-lineX(1))/lineD(1)*lineD(3) + lineX(3);\nX = [x y z];\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/LineFaceIntersection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.796570154960089}} {"text": "function centroids = computeCentroids(X, idx, K)\n%COMPUTECENTROIDS returs the new centroids by computing the means of the \n%data points assigned to each centroid.\n% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by \n% computing the means of the data points assigned to each centroid. It is\n% given a dataset X where each row is a single data point, a vector\n% idx of centroid assignments (i.e. each entry in range [1..K]) for each\n% example, and K, the number of centroids. You should return a matrix\n% centroids, where each row of centroids is the mean of the data points\n% assigned to it.\n%\n\n% Useful variables\n[m n] = size(X);\n\n% You need to return the following variables correctly.\ncentroids = zeros(K, n);\n\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every centroid and compute mean of all points that\n% belong to it. Concretely, the row vector centroids(i, :)\n% should contain the mean of the data points assigned to\n% centroid i.\n%\n% Note: You can use a for-loop over the centroids to compute this.\n%\n\nnumberOfElementsHavingCentroid_k = zeros(K,1);\nsumOfElementsHavingCentroid_k = zeros(K,n);\nfor i = 1:size(idx,1)\n\tz = idx(i);\n\tnumberOfElementsHavingCentroid_k(z) += 1;\n\tsumOfElementsHavingCentroid_k(z,:) += X(i,:);\nend\n\ncentroids = sumOfElementsHavingCentroid_k./numberOfElementsHavingCentroid_k;\n\n\n\n\n\n\n\n% =============================================================\n\n\nend\n\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex7/ex7/computeCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8962513731336202, "lm_q1q2_score": 0.7965512890521941}} {"text": "function dist = shape_point_dist_2d ( center, p1, nside, p )\n\n%*****************************************************************************80\n%\n%% SHAPE_POINT_DIST_2D: distance ( regular shape, point ) in 2D.\n%\n% Discussion:\n%\n% The \"regular shape\" is assumed to be an equilateral and equiangular\n% polygon, such as the standard square, pentagon, hexagon, and so on.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CENTER(2,1), the center of the shape.\n%\n% Input, real P1(2,1), the first vertex of the shape.\n%\n% Input, integer NSIDE, the number of sides in the shape.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, real DIST, the distance from the point to the shape.\n%\n\n%\n% Determine the angle subtended by a single side.\n%\n sector_angle = 360.0 / nside;\n%\n% How long is the half-diagonal?\n%\n radius = sqrt ( sum ( ( p1(1:2,1) - center(1:2,1) ).^2 ) );\n%\n% If the radius is zero, then the shape is a point and the computation is easy.\n%\n if ( radius == 0.0 )\n dist = sqrt ( sum ( ( p(1:2,1) - center(1:2,1) ).^2 ) );\n return;\n end\n%\n% If the test point is at the center, then the computation is easy.\n% The angle subtended by any side is ( 2 * PI / NSIDE ) and the\n% nearest distance is the midpoint of any such side.\n%\n if ( sqrt ( sum ( ( p1(1:2,1) - center(1:2,1) ).^2 ) ) == 0.0 )\n dist = radius * cos ( pi / nside );\n return\n end\n%\n% Determine the angle between the ray to the first corner,\n% and the ray to the test point.\n%\n angle = angle_deg_2d ( p1, center, p );\n%\n% Determine the sector of the point.\n%\n sector_index = floor ( angle / sector_angle ) + 1;\n%\n% Generate the two corner points that terminate the SECTOR-th side.\n%\n angle2 = ( sector_index - 1 ) * sector_angle;\n angle2 = degrees_to_radians ( angle2 );\n\n pa = vector_rotate_base_2d ( p1, center, angle2 );\n\n angle2 = ( sector_index ) * sector_angle;\n angle2 = degrees_to_radians ( angle2 );\n\n pb = vector_rotate_base_2d ( p1, center, angle2 );\n%\n% Determine the distance from the test point to the line segment that\n% is the SECTOR-th side.\n%\n dist = segment_point_dist_2d ( pa, pb, p );\n\n return\nend\n", "meta": {"author": "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/shape_point_dist_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7965102804446444}} {"text": "function [ n_data, n, c ] = tau_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TAU_VALUES returns some values of the Tau function.\n%\n% Discussion:\n%\n% TAU(N) is the number of divisors of N, including 1 and N.\n%\n% In Mathematica, the function can be evaluated by:\n%\n% DivisorSigma[1,n]\n%\n% First values:\n%\n% N TAU(N)\n%\n% 1 1\n% 2 2\n% 3 2\n% 4 3\n% 5 2\n% 6 4\n% 7 2\n% 8 4\n% 9 3\n% 10 4\n% 11 2\n% 12 6\n% 13 2\n% 14 4\n% 15 4\n% 16 5\n% 17 2\n% 18 6\n% 19 2\n% 20 6\n%\n% Formula:\n%\n% If the prime factorization of N is\n%\n% N = P1^E1 * P2^E2 * ... * PM^EM,\n%\n% then\n%\n% TAU(N) = ( E1 + 1 ) * ( E2 + 1 ) * ... * ( EM + 1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the argument of the Tau function.\n%\n% Output, integer C, the value of the Tau function.\n%\n n_max = 20;\n\n c_vec = [ ...\n 1, 2, 2, 3, 2, 4, 2, 4, 3, 4, ...\n 2, 12, 12, 4, 18, 24, 2, 8, 14, 28 ];\n\n n_vec = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n 23, 72, 126, 226, 300, 480, 521, 610, 832, 960 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data);\n c = c_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/tau_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7965102676734738}} {"text": "function x = hypersphere_to_cartesian ( m, n, c, r, theta )\n\n%*****************************************************************************80\n%\n%% HYPERSPHERE_TO_CARTESIAN: hypersphere to Cartesian coordinate transform.\n%\n% Discussion:\n%\n% We allow the trivial case M = 1; in that case alone, the value R\n% must be assumed to have a sign.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n% 1 <= M.\n%\n% Input, integer N, the number of points to transform.\n%\n% Input, real C(M,1), the center of the hypersphere.\n%\n% Input, real R(N,1), the radius of the points on the hypersphere.\n% Except for the trivial case M = 1, R is assumed nonnegative.\n%\n% Input, real THETA(M-1,N), the coordinate angles of the points,\n% measured in radians.\n%\n% Output, real X(M,N), the Cartesian coordinates of the points.\n%\n x = zeros ( m, n );\n%\n% Make R a row vector.\n%\n r = ( r(:) )';\n%\n% Handle special case of M = 1.\n%\n if ( m == 1 )\n x(1:1,1:n) = repmat ( c(1:1,1:1), 1, n ) ...\n + repmat ( r(1:1,1:n), 1, 1 );\n return\n end\n\n x(1:m,1:n) = repmat ( r(1:1,1:n), m, 1 );\n\n for i1 = 1 : m - 1\n x(i1,1:n) = x(i1,1:n) .* cos ( theta(i1,1:n) );\n for i2 = i1 + 1 : m\n x(i2,1:n) = x(i2,1:n) .* sin ( theta(i1,1:n) );\n end\n end\n%\n% Add the center.\n%\n x(1:m,1:n) = x(1:m,1:n) + repmat ( c(1:m,1:1), 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/hypersphere_surface/hypersphere_to_cartesian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8705972600147105, "lm_q1q2_score": 0.796510266621799}} {"text": "function dist = line_exp_point_dist_3d ( p1, p2, p )\n\n%*****************************************************************************80\n%\n%% LINE_EXP_POINT_DIST_3D: distance ( explicit line, point ) in 3D.\n%\n% Discussion:\n%\n% The explicit form of a line in 3D is:\n%\n% ( P1, P2 ) = ( (X1,Y1,Z1), (X2,Y2,Z2) ).\n%\n% Thanks to Francois Struempfer for pointing out a parenthesis mistake in the\n% computation of the Euclidean norm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(3,1), P2(3,1), two points on the line.\n%\n% Input, real P(3,1), the point whose distance from the line is\n% to be measured.\n%\n% Output, real DIST, the distance from the point to the line.\n%\n dim_num = 3;\n\n bot = sum ( ( p2(1:dim_num,1) - p1(1:dim_num,1) ).^2 );\n\n if ( bot == 0.0 )\n\n pn(1:dim_num,1) = p1(1:dim_num,1);\n%\n% (P-P1) dot (P2-P1) = Norm(P-P1) * Norm(P2-P1) * Cos(Theta).\n%\n% (P-P1) dot (P2-P1) / Norm(P-P1)**2 = normalized coordinate T\n% of the projection of (P-P1) onto (P2-P1).\n%\n else\n\n t = sum ( ( p(1:dim_num,1) - p1(1:dim_num,1) )' ...\n * ( p2(1:dim_num,1) - p1(1:dim_num,1) ) ) / bot;\n\n pn(1:dim_num,1) = p1(1:dim_num,1) + t * ( p2(1:dim_num,1) - p1(1:dim_num,1) );\n\n end\n%\n% Now compute the distance between the projection point and P.\n%\n dist = sqrt ( sum ( ( p(1:dim_num,1) - pn(1:dim_num,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/line_exp_point_dist_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7963552053471609}} {"text": "% Exercise 4.57: Capacity of a communication channel \n% Boyd & Vandenberghe \"Convex Optimization\" \n% Joëlle Skaf - 04/24/08 \n%\n% We consider a discrete memoryless communication channel, with input \n% X(t) \\in {1,...,n}, and output Y(t) \\in {1,...,m}, for t = 1,2,... \n% The relation between the input and output is given statistically: \n% p_ij = Prob(Y(t)=i|X(t)=j), i=1,...,m, j=1,...,n\n% The matrix P is called the channel transition matrix.\n% The channel capacity C is given by \n% C = sup{ I(X;Y) | x >= 0, sum(x) = 1}, \n% I(X;Y) is the mutual information between X and Y, and it can be shown \n% that: I(X;Y) = c'*x - sum_{i=1}^m y_i*log_2(y_i)\n% where c_j = sum_{i=1}^m p_ij*log_2(p_ij), j=1,...,m\n\n% Input data \nrand('state', 0); \nn = 15;\nm = 10; \nP = rand(m,n); \nP = P./repmat(sum(P),m,1); \nc = sum(P.*log2(P))';\n\n% Channel capacity \ncvx_begin\n variable x(n) \n y = P*x; \n maximize (c'*x + sum(entr(y))/log(2))\n x >= 0;\n sum(x) == 1; \ncvx_end\nC = cvx_optval; \n\n% Results\ndisplay(['The channel capacity is: ' num2str(C) ' bits.'])\n\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch04_cvx_opt_probs/channel_capacity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426397881662, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7963524010150839}} {"text": "function [rmag, dec] = geodet4 (lat, alt)\n\n% geodetic to geocentric coordinates\n\n% input\n\n% lat = geodetic latitude (radians)\n% (+north, -south; -pi/2 <= lat <= +pi/2)\n% alt = geodetic altitude (kilometers)\n\n% output\n\n% rmag = geocentric position magnitude (kilometers)\n% dec = geocentric declination (radians)\n% (+north, -south; -pi/2 <= dec <= +pi/2)\n\n% global constants\n\n% req = equatorial radius (kilometers)\n% flat = flattening factor (non-dimensional)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal req flat\n\n% \"normalize\" altitude\n\nhhat = alt / req;\n\nhp1 = hhat + 1;\n\n% calculate trig terms\n\ns2lat = sin(2 * lat);\n\nc2lat = cos(2 * lat);\n\ns4lat = sin(4 * lat);\n\nc4lat = cos(4 * lat);\n\n% geocentric distance (kilometers)\n\nrho = hp1 + (0.5 * (c2lat - 1)) * flat ...\n + ((1/(4 * hp1) + (1/16)) * (1 - c4lat)) * flat * flat;\n\nrmag = req * rho;\n\n% geocentric declination (radians)\n\ndec = lat + (-s2lat/hp1) * flat ...\n + (-s2lat/(2 * (hp1 * hp1)) + (1/(4 * hp1 * hp1) + 1/(4 * hp1))...\n * s4lat) * flat * flat;\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/39494-geodetic-and-geocentric-coordinates/geodet4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.796347420346797}} {"text": "function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)\n%GRADIENTDESCENTMULTI Performs gradient descent to learn theta\n% theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by\n% taking num_iters gradient steps with learning rate alpha\n\n% Initialize some useful values\nm = length(y); % number of training examples\nJ_history = zeros(num_iters, 1);\n\nfor iter = 1:num_iters\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCostMulti) and gradient here.\n %\n\n\n\n\n\n\n\n predictions = X * theta;\n updates = X' * (predictions - y);\n theta = theta - alpha * (1/m) * updates;\n\n\n\n % ============================================================\n\n % Save the cost J in every iteration \n J_history(iter) = computeCostMulti(X, y, theta);\n\nend\n\nend\n", "meta": {"author": "vugsus", "repo": "coursera-machine-learning", "sha": "4c2d45cb729355593509abcd41779d19de5a1970", "save_path": "github-repos/MATLAB/vugsus-coursera-machine-learning", "path": "github-repos/MATLAB/vugsus-coursera-machine-learning/coursera-machine-learning-4c2d45cb729355593509abcd41779d19de5a1970/mlclass-ex1/gradientDescentMulti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7963337650496279}} {"text": "function A = makejcf(n, e, m, X)\n%MAKEJCF A matrix with specified Jordan canonical form.\n% MAKEJCF(N, E, M) is a matrix having the Jordan canonical form\n% whose i'th Jordan block is of dimension M(i) with eigenvalue E(i),\n% and where N = SUM(M).\n% Defaults: E = 1:N, M = ONES(SIZE(E)) with M(1) so that SUM(M) = N.\n% The matrix is constructed by applying a random similarity\n% transformation to the Jordan form.\n% Alternatively, the matrix used in the similarity transformation\n% can be specified as a fifth parameter.\n% In particular, MAKEJCF(N, E, M, EYE(N)) returns the Jordan form\n% itself.\n% NB: The JCF is very sensitive to rounding errors.\n\nif nargin < 2, e = 1:n; end\nif nargin < 3, m = ones(size(e)); m(1) = m(1) + n - sum(m); end\n\nif length(e) ~= length(m)\n error('Parameters E and M must be of same dimension.')\nend\n\nif sum(m) ~= n, error('Block dimensions must add up to N.'), end\n\nA = zeros(n);\nj = 1;\nfor i=1:max(size(m))\n if m(i) > 1\n Jb = gallery('jordbloc',m(i),e(i));\n else\n Jb = e(i); % JORDBLOC fails in n = 1 case.\n end\n A(j:j+m(i)-1,j:j+m(i)-1) = Jb;\n j = j + m(i);\nend\n\nif nargin < 4\n X = randn(n);\nend\nA = X\\A*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/base/utilities/matrixcomp/makejcf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7963097438914892}} {"text": "function [ pp, normal, seed ] = plane_normal_uniform_nd ( dim_num, seed )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_UNIFORM_ND generates a random normal plane in ND.\n%\n% Discussion:\n%\n% The normal form of a plane is:\n%\n% PP is a point on the plane,\n% N is a normal vector to the plane.\n%\n% The point PP will be chosen at random inside the unit sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n% Output, real PP(DIM_NUM), a point on the plane.\n%\n% Output, real NORMAL(DIM_NUM), the unit normal vector.\n%\n\n%\n% Pick PP as a random point inside the unit sphere in ND.\n%\n [ pp, seed ] = ball_unit_sample_nd ( dim_num, seed );\n%\n% Get values from a standard normal distribution.\n%\n [ normal, seed ] = r8vec_normal_01 ( dim_num, seed );\n%\n% Compute the length of the vector.\n%\n norm = sqrt ( sum ( normal(1:dim_num).^2 ) );\n%\n% Normalize the vector.\n%\n normal(1:dim_num) = normal(1:dim_num) / norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_normal_uniform_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7963097390632836}} {"text": "function C=circulantMatrix(v,reverseDir)\n%%CIRCULANTMATRIX Create a circulant matrix where the first row is given by\n% v. A circulatn matrix is a matrix where each row going down\n% from the top rotates the elements of the previous row by 1.\n%\n%INPUTS: v A 1XN or NX1 vector containing the elemtns that go into the\n% first row.\n% reverseDir If true, this boolean parameter indicates that each subsequent\n% row should be left-shifted from the previous one. If this\n% parameter is omitted or an empty matrix is passed, then the\n% default is false.\n%\n%OUTPUTS: C The NXN circulant matrix whose first row is v.\n%\n%EXAMPLE:\n% CF=circulantMatrix(1:5,false)\n% CR=circulantMatrix(1:5,true)\n%The results are:\n%CF=[1,2,3,4,5;\n% 5,1,2,3,4;\n% 4,5,1,2,3;\n% 3,4,5,1,2;\n% 2,3,4,5,1];\n%CR=[1,2,3,4,5;\n% 2,3,4,5,1;\n% 3,4,5,1,2;\n% 4,5,1,2,3;\n% 5,1,2,3,4];\n%\n%October 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(nargin<2||isempty(reverseDir))\n reverseDir=false;\n end\n\n N=length(v);\n v=v(:);\n x=[v(N:-1:1,1);flipud(v(2:end))];\n if(reverseDir)\n idx=bsxfun(@plus,mod(0:-1:-((N-1)),N)',(N:-1:1));\n else\n idx=bsxfun(@plus,(0:(N-1))',(N:-1:1));\n end\n \n C=x(idx);\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/circulantMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8991213813246445, "lm_q1q2_score": 0.7962902049404429}} {"text": "function [x,iflaw]=fmpar(N,p1,p2,p3)\n%FMPAR\tParabolic frequency modulated signal.\n%\t[X,IFLAW]=FMPAR(N,P1,P2,P3) generates a signal with\n%\tparabolic frequency modulation law.\n%\tX(T) = exp(j*2*pi(A0.T + A1/2.T^2 +A2/3.T^3)) \n%\n%\tN : the number of points in time\n%\tP1 : if NARGIN=2, P1 is a vector containing the three \n%\t coefficients [A0 A1 A2] of the polynomial instantaneous phase.\n%\t If NARGIN=4, P1 (as P2 and P3) is a time-frequency point of \n%\t the form [Ti Fi].\n%\t The coefficients (A0,A1,A2) are then deduced such that \n%\t the frequency modulation law fits these three points.\n%\tP2,P3 : same as P1 if NARGIN=4. (optional)\n%\tX : time row vector containing the modulated signal samples \n%\tIFLAW : instantaneous frequency law\n%\n%\tExamples : \n%\t [X,IFLAW]=fmpar(128,[1 0.4],[64 0.05],[128 0.4]);\n%\t subplot(211);plot(real(X));subplot(212);plot(IFLAW);\n%\t [X,IFLAW]=fmpar(128,[0.4 -0.0112 8.6806e-05]);\n%\t subplot(211);plot(real(X));subplot(212);plot(IFLAW);\n%\n%\tSee also FMCONST, FMHYP, FMLIN, FMSIN, FMODANY, FMPOWER.\n\n%\tP. Goncalves - October 1995, O. Lemoine - November 1995\n%\tCopyright (c) 1995 Rice University\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin <= 1),\n error ( 'The number of parameters must be at least 2.' );\nelseif (N <= 0),\n error ('The signal length N must be strictly positive' );\nelseif nargin == 2 ;\n if length(p1) ~= 3\n error('Bad number of coefficients for P1');\n end\n a0 = p1(1) ; a1 = p1(2) ; a2 = p1(3) ;\nelseif nargin == 4 ;\n if (length(p1) ~= 2) |(length(p2) ~= 2) |(length(p3) ~= 2),\n error('Bad number of coefficients for P1, P2, P3');\n end\n if p1(1)>N | p1(1)<1,\n error ('P1(1) must be between 1 and N');\n elseif p2(1)>N | p2(1)<1,\n error ('P2(1) must be between 1 and N');\n elseif p3(1)>N | p3(1)<1,\n error ('P3(1) must be between 1 and N');\n elseif p1(2)<0,\n error ('P1(2) must be > 0');\n elseif p2(2)<0,\n error ('P2(2) must be > 0');\n elseif p3(2)<0,\n error ('P3(2) must be > 0');\n end\n Y = [p1(2) p2(2) p3(2)] ;\n X = [1 1 1;p1(1) p2(1) p3(1);p1(1)^2 p2(1)^2 p3(1)^2] ;\n coef = Y*inv(X) ; \n a0 = coef(1) ;\n a1 = coef(2) ;\n a2 = coef(3) ;\nend \n\nt=1:N;\n\nphi = 2*pi*(a0*t + a1/2*t.^2 + a2/3*t.^3) ;\niflaw = (a0 + a1*t + a2*t.^2).' ;\n\naliasing = find(iflaw<0 | iflaw>0.5) ;\nif isempty(aliasing) == 0\n disp(['!!! WARNING: signal is undersampled or has negative frequencies']) ;\nend\n\nx = exp(i*phi).';\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/fmpar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.796233768762171}} {"text": "function [Xco Tau MT] = HC_CrankNicolson_h (Tin,TC,DE,HC,SE,DI,TS,TT,TBC,BC)\n%\n% DESCRIPTION:\n%\n% Crank-Nicolson numerical method for one dimensional unsteady state \n% heat transfer by conduction for homogenous material\n%\n% Basic PDE equation :\n%\n% dT d^2 T \n% ------ = TD ------ for 0 < x < DI and tau > 0 \n% dtau dx^2\n%\n% Principle of method :\n% ^\n% time |\n% | m-1 m m+1\n% | | | |\n% | ---o------x------o----- p+1\n% | dtau | | |\n% | ---o------o------o----- p \n% | dtau | | |\n% | ---+------+------+----- p-1\n% | | dx | dx |\n% |\n% +--------------------------------> \n% x \n% Space description:\n% DI\n% |<------------------------------>|\n% + + + + + . . . + + \n% 1 2 3 4 5 n-1 n\n% |<->|\n% SE\n%\n% Difference equation :\n%\n% T(m,p+1) - T(m,p) TD\n% ------------------- = -------( T(m-1,p+1) - 2.T(m,p+1) + T(m+1,p+1) )\n% dTau 2.dx.dx\n%\n% TD\n% + -------( T(m-1,p) - 2.T(m,p) + T(m+1,p) )\n% 2.dx.dx\n%\n% System of equations:\n%\n% (1+M).T(2,p+1) - M/2.T(3,p+1) = \n% = M/2.T(1,p) + (1-M).T(2,p) + M/2.T(3,p) + M/2.T(1,p+1)\n% . . . \n% for m <2,n-1> \n% - M/2.T(m-1,p+1) + (1+M).T(m,p+1)- M/2.T(m+1,p+1) = \n% = M/2.T(m-1,p) + (1-M).T(m,p) + M/2.T(m+1,p)\n% . . . \n% - M/2.T(n-2,p+1) + (1+M).T(n-1,p+1) = \n% = M/2.T(n-2,p) + (1-M).T(n-1,p) + M/2.T(n,p) + M/2.T(n,p+1)\n%\n% Matrix notation:\n%\n% A.T = b\n%\n% The elements of A are given by\n%\n% A(n-2,n-2) = 0 except for:\n% \n% A(1,1) = 1 + M;\n% A(1,2) = - M/2;\n% \n% A(m,m-1) = - M/2; \n% A(m,m) = 1 + M;\n% A(m,m+1) = - M/2; for m <2,n-3>\n% \n% A(n-2,n-3) = - M/2;\n% A(n-2,n-2) = 1 + M;\n%\n% and the elements of b are given by\n%\n% b(1) = M/2*Tin(1) + (1-M)*Tin(2) + M/2*Tin(3) + M/2*T(1); \n% \n% b(m) = M/2*Tin(m) + (1-M)*Tin(m+1) + M/2*Tin(m+2); for m <2,n-3>\n% \n% b(n-2) = M/2*Tin(n-2) + (1-M)*Tin(n-1) + M/2*Tin(n) + M/2*T(n); \n% \n% INPUTS:\n%\n% Tin - initialization temperatures [ K ] \n% TC - thermal conductivity [ W.m^-1.K^-1 ]\n% DE - density [ kg.m^-3 ]\n% HC - specific heat capacity [ kg.m^-3 ]\n% SE - size of element [ m ]\n% DI - distance [ m ]\n% TS - time step [ s ]\n% TT - total time of simulation [ s ]\n% TBC - type of boundary condition \n% (1 = first-type, 2 = second-type) [ - ]\n% BC - boundary condition \n% - first-type : BC(1) = T(1), BC(2) = T(n) [ K ]\n% - second-type: BC(1) = iQ(1), BC(2) = iQ(n) [ W.m^-2 ]\n% \n% OUTPUTS:\n%\n% Xco - vector of X coordinate [ m ]\n% Tau - vector of time [ s ]\n% MT - matrix of temperatures [ K ]\n% \n% AUXILIARY VARIABLE:\n%\n% r - time step number [ - ]\n% n - space point number [ - ] \n% TD - thermal diffusivity [ m^2.m^-1 ]\n% M - modul (Fourier number) [ - ]\n% A - matrix (n-2,n-2) [ - ]\n% b - vector (n-2) [ - ]\n%\n% Copyright (C) 2013, Technical University of Kosice\n% Author : Zecova Monika, Terpak Jan\n% Revision: 27.08.2013\n%\n r = round(TT/TS) + 1; \n n = round(DI/SE) + 1; \n \n Xco = 0.0:SE:DI; \n Tau = 0.0:TS:TT; \n MT = zeros(r,n);\n MT(1,:) = Tin;\n \n for j=2:r\n [T] = CrankNicolson (Tin,TC,DE,HC,SE,TS,TBC,BC);\n Tin = T; \n MT(j,:) = Tin; \n end\nend\nfunction [T] = CrankNicolson (Tin,TC,DE,HC,SE,TS,TBC,BC)\n\n TD = TC/(DE*HC);\n M = TD*TS/(SE*SE);\n\n T = Tin;\n \n if TBC == 1\n T(1) = BC(1);\n T(end) = BC(2);\n end\n \n if TBC == 2\n T(1) = T(2) - BC(1)*SE/TC;\n T(end) = T(end-1) - BC(2)*SE/TC;\n end \n \n k = length(Tin)-2;\n A = zeros(k,k);\n b = zeros(k,1);\n\n for i=1:k\n b(i) = M/2*Tin(i) + (1-M)*Tin(i+1) + M/2*Tin(i+2) ;\n end\n\n A(1,1) = (1+M);\n A(1,2) = - M/2;\n b(1) = b(1) + M/2*T(1);\n \n for i=2:k-1\n A(i,i-1) = - M/2;\n A(i,i) = 1 + M;\n A(i,i+1) = - M/2; \n end\n \n A(k,k-1) = - M/2;\n A(k,k) = 1 + M;\n b(k) = b(k) + M/2*T(end);\n\n x = A\\b;\n\n for i=2:length(Tin)-1\n T(i) = x(i-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/43146-heat-conduction-toolbox/HeatConductionToolbox/HC_CrankNicolson_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7961975645659497}} {"text": "function [W phi]=train_rbf(X,Y,Xc,k_i,basisfunction)\n%trains a radial basis function\n%X is a N_p by N_dim matrix of training data\n%Y is a N_p by N_dim matrix of training data\n%Xc is a N_r by N_dim matrix of rbf centres\n%basisfunction may be 'gaussian' or 'polyharmonicspline'\n%k_i is a prescaler for 'gaussian' rbf and function order for\n%'polyharmonicspline'. See k_i(i)=0 for constant bias\n\n% Copyright Travis Wiens 2008\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% If you would like to request that this software be licensed under a less\n% restrictive license (i.e. for commercial closed-source use) please\n% contact Travis at travis.mlfx@nutaksas.com\n\nif nargin<4\n k_i=1;\nend\n\nif nargin<5\n basisfunction='gaussian';\nend\n\nN_r=size(Xc,1);%number of centres\n\nW=zeros(N_r,1);%weight matrix\n[z phi]=sim_rbf(Xc,X,W,k_i,basisfunction);%simulate rbf\nA=pinv(phi'*phi)*phi';%do inverse\nW=A*Y;%find weights", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22174-rbf-acoustic-tomography/rbf_tomo_1_01/train_rbf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7961975606508439}} {"text": "function mc = moc ( a, b, n, f )\n\n%*****************************************************************************80\n%\n%% MOC estimates the modulus of continuity of a function over an interval.\n%\n% Discussion;\n%\n% The modulus of continuity function MC(T) for a function F(X) over an \n% interval [A,B] is defined as\n%\n% MC(T) = max | F(X+DX) - F(X) | for 0 <= DX <= T, and X and X+DX in [A,B].\n%\n% The modulus of continuity function is a monotone increasing function,\n% with MC(0) = 0.\n%\n% This function estimates the modulus of continuity based on a discrete\n% set of data at N equally spaced points in the interval [A,B]. \n% \n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the left and right endpoints of the interval.\n%\n% Input, integer N, the number of equally spaced sample points.\n%\n% Input, function F(x), a handle to the function.\n%\n% Output, real MC(N), the modulus of continuity function estimated at \n% 0, H or less, 2*H or less, ..., (N-1)*H or less.\n%\n\n% Compute the maximum difference with a separation DX of exactly 0*H, 1*H, 2*H, \n% ..., (N-1)*H.\n%\n mc1 = moc1 ( a, b, n, f );\n%\n% Compute the maximum difference with a separation DX of 0*H or less, \n% 1*H or less, 2*H or less, ..., (N-1)*H or less.\n%\n mc = zeros ( n, 1 );\n for i = 1 : n - 1\n mc(i+1) = max ( mc(i), mc1(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/moc_display/moc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7961834993301606}} {"text": "function Nimg = Gscale(img,levels,gsize,sigma);\n%\n% Function to generate a gaussian-pyramid for the given input image\n%\n% Input: \n% img: input image-matrix grayscale\n% levels: number of levels of the pyramid \n% gsize: size of the gaussian kernel [w h] ([5 5] normally provides a smooth output)\n% sigma: sigma for gaussian kernel \n% Output:\n% Nimg: is a struct consisting of images from each level\n% : Nimg.img;\n% Usage:\n% im = imread('cameraman.tif');\n% Nimg = Gscale(im,3,[5 5],1.6);\n% i = 2; %select a level\n% figure; imshow(Nimg(i).img);\n%\n% Author: Pranam Janney Date: 24th July 2006 15:39\n% Email: pranamjanney@yahoo.com\n%\n% Revised Version 1.0.1 Date: 04th August 2006, 10:50\n%\n\n\n%guassian filter with a sigma=1.6\ng = fspecial('gaussian',gsize,sigma);\n\n%pyramid\nfor i = 1:levels\n if i == 1\n im = imfilter(img,g,'conv');\n Nimg(i).img = im;\n else \n %perform guassian filtering\n im = imfilter(Nimg(i-1).img,g,'conv');\n %perform downsampling (horizontal)\n im1 = im(:,1:2:size(Nimg(i-1).img,2));\n %vertical\n im2 = im1(1:2:size(Nimg(i-1).img,1),:);\n %store it in a struct format\n Nimg(i).img = im2;\n end\nend\n \n%End\n \n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/imageproc/Gscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7961834901730489}} {"text": "% Y = spharm_fast(theta,phi,l,m,p0)\n%\n% Orthonormal spherical harmonic function (Arfken, p. 681) for quantum\n% numbers l and m. Angles theta and phi should be given in radians.\n% p0 contains the values of the Legendre polynomial\n%\nfunction Y = spharm_fast(theta,phi,l,m,p0)\n\n% Copyright (c) 2016, Elekta Oy\n% ---------------------------------------\n% \n% Redistribution and use of the Software in source and binary forms, with or without \n% modification, are permitted for non-commercial use.\n% \n% The Software is provided \"as is\" without warranties of any kind, either express or\n% implied including, without limitation, warranties that the Software is free of defects,\n% merchantable, fit for a particular purpose. Developer/user agrees to bear the entire risk \n% in connection with its use and distribution of any and all parts of the Software under this license.\n% \n\n%p0 = legendre(l,cos(theta));\np = p0(2:end); % Values m > 1\n%\n% Arfken, p. 681. The Condon-Shortley phase is included in the\n% Legendre polynomials\n%\n%scale = sqrt((2*l+1)*prod(1:(l-m))/(4*pi*prod(1:(l+m)))); \nif m < 0\n Y = ((-1)^m)*sqrt((2*l+1)*prod(1:(l+m))/(4*pi*prod(1:(l-m))))*p(-m); \n %Y = scale*((-1)^m)*(prod(1:(l-abs(m)))/prod(1:(l+abs(m))))*p(-m);\nelseif m > 0\n Y = sqrt((2*l+1)*prod(1:(l-m))/(4*pi*prod(1:(l+m))))*p(m);\n %Y = scale*p(m);\nelse\n Y = sqrt((2*l+1)/(4*pi))*p0(1);\n %Y = scale*p0(1);\nend\nY = Y*complex(cos(m*phi),sin(m*phi));\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/TSSS/private/spharm_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7960863855056931}} {"text": "function [mellin,beta]=fmt(X,fmin,fmax,N);\n%FMT Fast Fourier Mellin Transform.\n% [MELLIN,BETA]=FMT(X,FMIN,FMAX,N) computes the Fast Mellin\n% Transform of signal X.\n%\n% X : signal in time (Nx=length(X)).\n% FMIN,FMAX : respectively lower and upper frequency bounds of \n% the analyzed signal. These parameters fix the equivalent \n% frequency bandwidth (expressed in Hz). When unspecified, you\n% have to enter them at the command line from the plot of the\n% spectrum. FMIN and FMAX must be >0 and <=0.5. \n% N : number of analyzed voices. N must be even\n%\t\t\t\t (default : automatically determined).\n% MELLIN : the N-points Mellin transform of signal S.\n% BETA : the N-points Mellin variable.\n%\n% Examples : \n% sig=altes(128,0.05,0.45); \n%\t [MELLIN,BETA]=fmt(sig,0.05,0.5,128);\n% plot(BETA,real(MELLIN));\n%\n% See also IFMT, FFT, IFFT.\n\n% P. Goncalves 9-95 - O. Lemoine, June 1996. \n% Copyright (c) 1995 Rice University - CNRS (France) 1996.\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error('At least one parameter required');\nend;\n\n[xrow,xcol] = size(X);\n\nif (nargin==2),\n disp('FMIN will not be taken into account. Determine it with FMAX');\n disp(' from the following plot of the spectrum.'); \nelseif nargin==3,\n N=[];\nelseif (nargin==4 & rem(N,2)~=0),\n error('N must be even');\nend;\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nend\n\nMt = length(X); \nZ = hilbert(real(X));\nM = (Mt+rem(Mt,2))/2;\n\nif nargin<=2, % fmin,fmax,N unspecified\n STF = fft(fftshift(X)); Nstf=length(STF);\n sp = (abs(STF(1:Nstf/2))).^2; Maxsp=max(sp);\n f = linspace(0,0.5,Nstf/2+1) ; f = f(1:Nstf/2);\n plot(f,sp) ; grid;\n xlabel('Normalized frequency');\n title('Analyzed signal energy spectrum');\n indmin=min(find(sp>Maxsp/1000));\n indmax=max(find(sp>Maxsp/1000));\n fmindflt=max([0.001 0.05*fix(f(indmin)/0.05)]);\n fmaxdflt=0.05*ceil(f(indmax)/0.05);\n txtmin=['Lower frequency bound [',num2str(fmindflt),'] : '];\n txtmax=['Upper frequency bound [',num2str(fmaxdflt),'] : '];\n fmin = input(txtmin); fmax = input(txtmax);\n if fmin==[], fmin=fmindflt; end\n if fmax==[], fmax=fmaxdflt; end\nend\n\nif fmin >= fmax\n error('FMAX must be greater or equal to FMIN');\nelseif fmin<=0.0 | fmin>0.5,\n error('FMIN must be > 0 and <= 0.5');\nelseif fmax<=0.0 | fmax>0.5,\n error('FMAX must be > 0 and <= 0.5');\nend\n\nB = fmax-fmin; \t\t% Bandwidth of the signal X\nR = B/((fmin+fmax)/2);\t\t% Relative bandwidth of X\n\nNq= ceil((B*Mt*(1+2/R)*log((1+R/2)/(1-R/2)))/2);\nNmin = Nq-rem(Nq,2);\nNdflt = 2^nextpow2(Nmin);\nif nargin<=2,\n Ntxt=['Number of frequency samples (>=',num2str(Nmin),') [',num2str(Ndflt),'] : '];\n N = input(Ntxt);\nend\n\nif N~=[],\n if (N= ',num2str(Nmin)];\n disp(dispstr);\n end\nelse\n N=Ndflt; \nend\n\n\n% Geometric sampling of the analyzed spectrum\nNo2 = N/2;\nk = (1:No2);\nq = (fmax/fmin)^(1/(No2-1));\nt = (1:Mt)-M-1;\ngeo_f = fmin*(exp((k-1).*log(q)));\ntfmatx = zeros(Mt,N);\ntfmatx = exp(-2*j*pi*t'*geo_f);\nZS = Z.'*tfmatx; \nZS(No2+1:N) = zeros(1,N-No2);\n\n\n% Mellin transform computation of the analyzed signal\np = 0:(N-1);\nL = log(fmin)/log(q);\nmellin = N*log(q)*fftshift(ifft(ZS)).*exp(j*2*pi*L*(p/N-1/2));\nbeta = (p/N-1/2)./log(q);\n\n\n% Normalization\nSP = fft(hilbert(real(X))); \nindmin = 1+round(fmin*(xrow-2));\nindmax = 1+round(fmax*(xrow-2));\nSPana = SP(indmin:indmax);\nnu = (indmin:indmax)'/N; \nSPp = SPana./nu;\nNormsig = sqrt(SPp'*SPana);\n\nmellin = mellin*Normsig/norm(mellin);\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/fmt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7960605766726502}} {"text": "clear\n\n% problem specification\nm = 400; n = 500; r = 10;\nt = 1; esr = ceil(t*r); \nfprintf('[m n r esr] = [%i, %i, %i, %i]\\n',m,n,r,esr);\n\n% data\n% Xo = rand(m,r); Yo = rand(r,n);\nXo = abs(randn(m,r)); Yo = abs(randn(r,n));\n\nd = ones(r,1).*(1:r)';\nM = Xo*spdiags(d,0,r,r)*Yo;\n\n% set solver options\nopts.tol = 1e-5;\nopts.maxit = 500;\nopts.print = 1;\n\n% call solver\n\nsr = 0.5;\nOmega = randsample(m*n, sr*m*n);\nA = M(Omega);\n\n%exact rank-estimate case\nt0 = tic;\n[X,Y,Out] = mc_nmf(A,Omega,esr,m,n,opts);\ntime = toc(t0);\nrelerr = norm(X*Y-M,'fro')/norm(M,'fro');\nfprintf('RelErr = %5.2e, %4.2e Sec.\\n',relerr,time);\n%%\n[numr,numc] = size(M);\nI = randi([0 1],numr,numc);\nOmega = find(I);\nA = M(Omega);\n\n%%\nsubplot(1,2,1),imagesc(M);\nsubplot(1,2,2),imagesc(X*Y);\n%%\n\n%over-estimate case\nesr = ceil(1.5*r);\nt0 = tic;\nfprintf('[m n r esr] = [%i, %i, %i, %i]\\n',m,n,r,esr);\n[X,Y,Out] = mc_nmf(A,Omega,esr,m,n,opts);\ntime = toc(t0);\nrelerr = norm(X*Y-M,'fro')/norm(M,'fro');\nfprintf('RelErr = %5.2e, %4.2e Sec.\\n',relerr,time);", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/mc/MC-NMF/quicktest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.796060566734825}} {"text": "function value = cube_monomial ( a, b, expon )\n\n%*****************************************************************************80\n%\n%% CUBE_MONOMIAL integrates a monomial over a cube in 3D.\n%\n% Discussion:\n%\n% This routine integrates a monomial of the form\n%\n% product ( 1 <= dim <= 3 ) x(dim)^expon(dim)\n%\n% The combination 0^0 should be treated as 1.\n%\n% The integration region is:\n% A(1) <= X <= B(1)\n% A(2) <= Y <= B(2)\n% A(3) <= Z <= B(3)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(3), B(3), the lower and upper limits.\n%\n% Input, integer EXPON(3), the exponents.\n%\n% Output, real VALUE, the integral of the monomial.\n%\n for i = 1 : 3\n\n if ( expon(i) == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CUBE_MONOMIAL - Fatal error!\\n' );\n fprintf ( 1, ' Exponent of -1 encountered.\\n' );\n error ( 'CUBE_MONOMIAL - Fatal error!' );\n end\n\n end\n\n value = 1.0;\n\n for i = 1 : 3\n\n value = value * ( b(i) ^ ( expon(i) + 1 ) - a(i) ^ ( expon(i) + 1 ) ) ...\n / ( expon(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/cube_felippa_rule/cube_monomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7958799355124515}} {"text": "#!/usr/bin/env octave\n%% Machine Learning Online Class - Exercise 1: Linear Regression\n\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the\n% linear exercise. You will need to complete the following functions \n% in this exericse:\n%\n% warmUpExercise.m\n% plotData.m\n% gradientDescent.m\n% computeCost.m\n% gradientDescentMulti.m\n% computeCostMulti.m\n% featureNormalize.m\n% normalEqn.m\n%\n% For this exercise, you will not need to change any code in this file,\n% or any other files other than those mentioned above.\n%\n% x refers to the population size in 10,000s\n% y refers to the profit in $10,000s\n%\n\n%% Initialization\nclear all; close all; clc\n\n%% ==================== Part 1: Basic Function ====================\n% Complete warmUpExercise.m \nfprintf('Running warmUpExercise ... \\n');\nfprintf('5x5 Identity Matrix: \\n');\nwarmUpExercise()\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% ======================= Part 2: Plotting =======================\nfprintf('Plotting Data ...\\n')\ndata = csvread('ex1data1.txt');\nX = data(:, 1); y = data(:, 2);\nm = length(y); % number of training examples\n\n% Plot Data\n% Note: You have to complete the code in plotData.m\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =================== Part 3: Gradient descent ===================\nfprintf('Running Gradient Descent ...\\n')\n\nX = [ones(m, 1), data(:,1)]; % Add a column of ones to x\ntheta = zeros(2, 1); % initialize fitting parameters\n\n% Some gradient descent settings\niterations = 1500;\nalpha = 0.01;\n\n% compute and display initial cost\ncomputeCost(X, y, theta)\n\n% run gradient descent\ntheta = gradientDescent(X, y, theta, alpha, iterations);\n\n% print theta to screen\nfprintf('Theta found by gradient descent: ');\nfprintf('%f %f \\n', theta(1), theta(2));\n\n% Plot the linear fit\nhold on; % keep previous plot visible\nplot(X(:,2), X*theta, '-')\nlegend('Training data', 'Linear regression')\nhold off % don't overlay any more plots on this figure\n\n% Predict values for population sizes of 35,000 and 70,000\npredict1 = [1, 3.5] *theta;\nfprintf('For population = 35,000, we predict a profit of %f\\n',...\n predict1*10000);\npredict2 = [1, 7] * theta;\nfprintf('For population = 70,000, we predict a profit of %f\\n',...\n predict2*10000);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ============= Part 4: Visualizing J(theta_0, theta_1) =============\nfprintf('Visualizing J(theta_0, theta_1) ...\\n')\n\n% Grid over which we will calculate J\ntheta0_vals = linspace(-10, 10, 100);\ntheta1_vals = linspace(-1, 4, 100);\n\n% initialize J_vals to a matrix of 0's\nJ_vals = zeros(length(theta0_vals), length(theta1_vals));\n\n% Fill out J_vals\nfor i = 1:length(theta0_vals)\n for j = 1:length(theta1_vals)\n\t t = [theta0_vals(i); theta1_vals(j)]; \n\t J_vals(i,j) = computeCost(X, y, t);\n end\nend\n\n\n% Because of the way meshgrids work in the surf command, we need to \n% transpose J_vals before calling surf, or else the axes will be flipped\nJ_vals = J_vals';\n% Surface plot\nfigure;\nsurf(theta0_vals, theta1_vals, J_vals)\nxlabel('\\theta_0'); ylabel('\\theta_1');\n\n% Contour plot\nfigure;\n% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100\ncontour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))\nxlabel('\\theta_0'); ylabel('\\theta_1');\nhold on;\nplot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n", "meta": {"author": "SaveTheRbtz", "repo": "ml-class", "sha": "74ce689e21e9f3ca184e60313351b31112e5dd56", "save_path": "github-repos/MATLAB/SaveTheRbtz-ml-class", "path": "github-repos/MATLAB/SaveTheRbtz-ml-class/ml-class-74ce689e21e9f3ca184e60313351b31112e5dd56/ex1/ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384593, "lm_q2_score": 0.8824278540866548, "lm_q1q2_score": 0.7958799341253966}} {"text": "function [total_error, max_error] = eq_area_error(dim,N)\n%EQ_AREA_ERROR Total area error and max area error per region of an EQ partition\n%\n%Syntax\n% [total_error, max_error] = eq_area_error(dim,N)\n%\n%Description\n% [TOTAL_ERROR, MAX_ERROR] = EQ_AREA_ERROR(dim,N) does the following:\n% 1) uses the recursive zonal equal area sphere partitioning algorithm to \n% partition the unit sphere S^dim into N regions,\n% 2) sets TOTAL_ERROR to be the absolute difference between the total area of\n% all regions of the partition, and the area of S^dim, and\n% 3) sets MAX_ERROR to be the maximum absolute difference between the area of \n% any region of the partition, and the ideal area of a region as given by\n% AREA_OF_IDEAL_REGION(dim,N), which is 1/N times the area of S^dim.\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The results TOTAL_ERROR and MAX_ERROR will be arrays of the same size as N.\n%\n%Examples\n% > [total_error, max_error] = eq_area_error(2,10)\n% total_error =\n% 1.7764e-15\n% \n% max_error =\n% 4.4409e-16\n% \n% > [total_error, max_error] = eq_area_error(3,1:6)\n% total_error =\n% 1.0e-12 *\n% 0.0036 0.0036 0.1847 0.0142 0.0142 0.2132\n% \n% max_error =\n% 1.0e-12 *\n% 0.0036 0.0018 0.1954 0.0284 0.0440 0.0777\n%\n%See also\n% EQ_REGIONS, AREA_OF_SPHERE, AREA_OF_IDEAL_REGION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Check number of arguments\n%\nerror(nargchk(2,2,nargin));\nerror(nargoutchk(2,2,nargout));\n\n%\n% Flatten N into a row vector.\n%\nshape = size(N);\nn_partitions = prod(shape);\nN = reshape(N,1,n_partitions);\n\ntotal_error = zeros(size(N));\nmax_error = zeros(size(N));\nsphere_area = area_of_sphere(dim);\n\nfor partition_n = 1:n_partitions\n n = N(partition_n);\n regions = eq_regions(dim,n);\n ideal_area = area_of_ideal_region(dim,n);\n total_area = 0;\n for region_n = 1:size(regions,3)\n area = area_of_region(regions(:,:,region_n));\n total_area = total_area + area;\n region_error = abs(area - ideal_area);\n if region_error > max_error(partition_n)\n max_error(partition_n) = region_error;\n end\n end\n total_error(partition_n) = abs(sphere_area - total_area);\nend\n%\n% Reshape output to same array size as original N.\n%\ntotal_error = reshape(total_error,shape);\nmax_error = reshape(max_error,shape);\n%\n% end function\n\nfunction area = area_of_region(region)\n%AREA_OF_REGION Area of given region\n%\n% area = area_of_region(region);\n\ndim = size(region,1);\ns_top = region(dim,1);\ns_bot = region(dim,2);\nif dim > 1\n area = area_of_collar(dim, s_top, s_bot)*area_of_region(region(1:dim-1,:))/area_of_sphere(dim-1);\nelse\n if s_bot == 0\n s_bot = 2*pi;\n end\n if s_top == s_bot\n s_bot = s_top + 2*pi;\n end\n area = s_bot - s_top;\nend\n%\n% end function\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/eq_sphere_partitions/eq_test/eq_area_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8824278556326343, "lm_q1q2_score": 0.7958799262143463}} {"text": "function result = fit_maxwell_pdf( x,y,W,hAx )\n% fit_maxwell_pdf - Non Linear Least Squares fit of the maxwellian distribution.\n% given the samples of the histogram of the samples, finds the \n% distribution parameter that fits the histogram samples.\n%\n% fits data to the probability of the form: \n% p(r) = sqrt(2/pi)*(a^(-3/2))*(r^2)*exp(-(r^2)/(2*a))\n% with parameter: a\n%\n% format: result = fit_maxwell_pdf( x,y,W,hAx )\n%\n% input: y - vector, samples of the histogram to be fitted\n% x - vector, position of the samples of the histogram (i.e. y = f(x,a))\n% W - matrix or scalar, a square weighting matrix of the size NxN where\n% N = length(y), or 0 to indicate no weighting is needed.\n% hAx - handle of an axis, on which the fitted distribution is plotted\n% if h is given empty, a figure is created.\n%\n% output: result - structure with the fields\n% a - fitted parameter\n% VAR - variance of the estimation\n% type- weighted LS or not weighted LS\n% iter- number of iteration for the solution\n%\n\n%\n% Algorithm\n% ===========\n%\n% We use the WLS algorithm to estimate the PDF from the samples.%\n% The maxwell distribution is given by:\n%\n% p(x,a) = sqrt(2/pi)*(a^(-3/2))*(x.^2).*exp(-(x.^2)/(2*a))\n% = Const * (a^(-3/2)) .* exp(-(x.^2)/(2*a))\n%\n% note that X is known and therefore, considered a constant vector\n%\n% The non liner WLS estimator is given by:\n%\n% a(n+1) = a(n) + inv(H'*W*H)*(H') * (y-h) = a(n) + G * err\n% \n% where: h = p(x,a)\n% H = diff( p(x,a) ) with respect to \"a\"\n% W = weighting matrix of size NxN (N = length(y))\n% a = a single parameter to be estimated\n%\n% The error estimation is given by:\n%\n% VAR( a ) = G * VAR( err ) * (G')\n%\n% or when W=I and the noise is a gaussian noise \n%\n% VAR( a ) = inv( H' * H )\n%\n\n\nif (nargin<3)\n error( 'fit_maxwell_pdf - insufficient input arguments' );\nend\n\na = x(find(y==max(y)))^2; % initial guess\ny = y(:); % both should be column vectors !\nx = x(:);\nx2 = x.^2; % save computation time\nC = sqrt(2/pi)*x2; % a constant vector\nthresh = 0.995; % convergence threshold for the loop\nlast_cnt= inf;\niter = 0;\n\n% check weight matrix input\nif (size(W,1)==length(y)) & (size(W,2)==length(y))\n weights_flag = 1;\n type = 'WLS';\nelse\n weights_flag = 0;\n type = 'LS';\nend\n\n\n% Estimation\n% =============\nif (weights_flag)\n % loop for convergence (with weighting matrix)\n % =============================================\n while (1)\n iter = iter + 1;\n h = C*(a^(-1.5)).*exp(-x2/(2*a));\n H = h.*( x2/(2*a^2) - 3/(2*a) );\n HTW = H'*W;\n e = inv( HTW * H ) * HTW * (y-h);\n a = a + e;\n control = e*e;\n if ( control > (last_cnt * thresh) )\n break;\n else\n last_cnt = control;\n end\n end\n\n % summarize results\n h = C*(a^(-1.5)).*exp(-x2/(2*a));\n H = h.*( x2/(2*a^2) - 3/(2*a) );\n HTW = H'*W;\n G = inv( HTW * H ) * HTW;\n err = ( y - h );\n result.a = a;\n result.VAR = G * var( err ) * (G');\n result.RMS = sqrt( (err')*err/ (x(2)-x(1))^2 / (length(err)-1) );\n result.iter = iter;\n result.type = type;\nelse\n\n % loop for convergence (without a weighting matrix) - assume white noise\n % ========================================================================\n while (1)\n iter = iter + 1;\n h = C*(a^(-1.5)).*exp(-x2/(2*a));\n H = h.*( x2/(2*a^2) - 3/(2*a) );\n HT = H';\n control = inv( HT * H );\n a = a + control * HT * (y-h);\n if ( control>(last_cnt * thresh) )\n break;\n else\n last_cnt = control;\n end\n end\n \n\t% summarize results\n h = C*(a^(-1.5)).*exp(-x2/(2*a));\n\tH = h.*( x2/(2*a^2) - 3/(2*a) );\n err = ( y - h );\n result.a = a;\n result.VAR = inv( (H') * H );\n result.RMS = sqrt( (err')*err/ (x(2)-x(1))^2 / (length(err)-1) );\n result.iter = iter;\n result.type = type;\nend\n\n\n% plot distribution if asked for\n% ===============================\nif (nargin>3)\n if ishandle( hAx )\n plot_maxwell( x,result,hAx,2 );\n else\n figure;\n plot_maxwell( x,result,gca,2 );\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/FitFunc/fit_maxwell_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7958152706444713}} {"text": "function [P] = JacobiP(x,alpha,beta,N);\n\n% function [P] = JacobiP(x,alpha,beta,N)\n% Purpose: Evaluate Jacobi Polynomial of type (alpha,beta) > -1\n% (alpha+beta <> -1) at points x for order N and returns P[1:length(xp))]\n% Note : They are normalized to be orthonormal.\n\n% Turn points into row if needed.\nxp = x; dims = size(xp);\nif (dims(2)==1) xp = xp'; end;\n\nPL = zeros(N+1,length(xp)); \n\n% Initial values P_0(x) and P_1(x)\ngamma0 = 2^(alpha+beta+1)/(alpha+beta+1)*gamma(alpha+1)*...\n gamma(beta+1)/gamma(alpha+beta+1);\nPL(1,:) = 1.0/sqrt(gamma0);\nif (N==0) P=PL'; return; end;\ngamma1 = (alpha+1)*(beta+1)/(alpha+beta+3)*gamma0;\nPL(2,:) = ((alpha+beta+2)*xp/2 + (alpha-beta)/2)/sqrt(gamma1);\nif (N==1) P=PL(N+1,:)'; return; end;\n\n% Repeat value in recurrence.\naold = 2/(2+alpha+beta)*sqrt((alpha+1)*(beta+1)/(alpha+beta+3));\n\n% Forward recurrence using the symmetry of the recurrence.\nfor i=1:N-1\n h1 = 2*i+alpha+beta;\n anew = 2/(h1+2)*sqrt( (i+1)*(i+1+alpha+beta)*(i+1+alpha)*...\n (i+1+beta)/(h1+1)/(h1+3));\n bnew = - (alpha^2-beta^2)/h1/(h1+2);\n PL(i+2,:) = 1/anew*( -aold*PL(i,:) + (xp-bnew).*PL(i+1,:));\n aold =anew;\nend;\n\nP = PL(N+1,:)';\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/Codes1D/JacobiP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7958152647711088}} {"text": "function [varargout] = funname(varargin)\n\n% SOLID_ANGLE of a planar triangle as seen from the origin\n%\n% The solid angle W subtended by a surface S is defined as the surface\n% area W of a unit sphere covered by the surface's projection onto the\n% sphere. Solid angle is measured in steradians, and the solid angle\n% corresponding to all of space being subtended is 4*pi sterradians.\n%\n% Use:\n% [w] = solid_angle(v1, v2, v3)\n% or\n% [w] = solid_angle(pnt, tri)\n% where v1, v2 and v3 are the vertices of a single triangle in 3D or\n% pnt and tri contain a description of a triangular mesh (this will\n% compute the solid angle for each triangle)\n\n% Copyright (C) 2003-2009, 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 .\n%\n% $Id: solid_angle.m 2885 2011-02-16 09:41:58Z roboos $\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The first section contains the plain Matlab implementation. The mex file\n% is many times faster and this function is called so frequently (for\n% large meshes), that the mex file should be used in all practical cases.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function [w] = solid_angle(r1, r2, r3);\n%\n% if nargin==2\n% % reassign the input arguments\n% pnt = r1;\n% tri = r2;\n% npnt = size(pnt,1);\n% ntri = size(tri,1);\n% w = zeros(ntri,1);\n% % compute solid angle for each triangle\n% for i=1:ntri\n% r1 = pnt(tri(i,1),:);\n% r2 = pnt(tri(i,2),:);\n% r3 = pnt(tri(i,3),:);\n% w(i) = solid_angle(r1, r2, r3);\n% end\n% return\n% elseif nargin==3\n% % compute the solid angle for this triangle\n% cp23_x = r2(2) * r3(3) - r2(3) * r3(2);\n% cp23_y = r2(3) * r3(1) - r2(1) * r3(3);\n% cp23_z = r2(1) * r3(2) - r2(2) * r3(1);\n% nom = cp23_x * r1(1) + cp23_y * r1(2) + cp23_z * r1(3);\n% n1 = sqrt (r1(1) * r1(1) + r1(2) * r1(2) + r1(3) * r1(3));\n% n2 = sqrt (r2(1) * r2(1) + r2(2) * r2(2) + r2(3) * r2(3));\n% n3 = sqrt (r3(1) * r3(1) + r3(2) * r3(2) + r3(3) * r3(3));\n% ip12 = r1(1) * r2(1) + r1(2) * r2(2) + r1(3) * r2(3);\n% ip23 = r2(1) * r3(1) + r2(2) * r3(2) + r2(3) * r3(3);\n% ip13 = r1(1) * r3(1) + r1(2) * r3(2) + r1(3) * r3(3);\n% den = n1 * n2 * n3 + ip12 * n3 + ip23 * n1 + ip13 * n2;\n% if (nom == 0)\n% if (den <= 0)\n% w = nan;\n% return\n% end\n% end\n% w = 2 * atan2 (nom, den);\n% return\n% else\n% error('invalid input');\n% end\n\n% compile the missing mex file on the fly\n% remember the original working directory\npwdir = pwd;\n\n% determine the name and full path of this function\nfunname = mfilename('fullpath');\nmexsrc = [funname '.c'];\n[mexdir, mexname] = fileparts(funname);\n\ntry\n % try to compile the mex file on the fly\n warning('trying to compile MEX file from %s', mexsrc);\n cd(mexdir);\n\n if ispc\n mex -I. -c geometry.c\n mex -I. -c solid_angle.c ; mex solid_angle.c solid_angle.obj geometry.obj\n else\n mex -I. -c geometry.c\n mex -I. -c solid_angle.c ; mex -o solid_angle solid_angle.o geometry.o\n end\n\n cd(pwdir);\n success = true;\n\ncatch\n % compilation failed\n disp(lasterr);\n error('could not locate MEX file for %s', mexname);\n cd(pwdir);\n success = false;\nend\n\nif success\n % execute the mex file that was juist created\n funname = mfilename;\n funhandle = str2func(funname);\n [varargout{1:nargout}] = funhandle(varargin{:});\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/solid_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7958152622848134}} {"text": "function poly_cof = r8poly_basis ( ntab, xtab )\n\n%*****************************************************************************80\n%\n%% R8POLY_BASIS computes all Lagrange basis polynomial in standard form.\n%\n% Discussion:\n%\n% The I-th Lagrange basis polynomial for a set of NTAB X values XTAB,\n% L(I,NTAB,XTAB)(X) is a polynomial of order NTAB-1 which is zero at\n% XTAB(J) for J not equal to I, and 1 when J is equal to I.\n%\n% The Lagrange basis polynomials have the property that the interpolating\n% polynomial through a set of NTAB data points (XTAB,YTAB) may be\n% represented as\n%\n% P(X) = Sum ( 1 <= I <= N ) YTAB(I) * L(I,NTAB,XTAB)(X)\n%\n% Higher order interpolation at selected points may be accomplished\n% using repeated X values, and scaled derivative values.\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 number of data points XTAB.\n%\n% Input, real XTAB(NTAB), the X values upon which the\n% Lagrange basis polynomial is to be based.\n%\n% Output, real POLY_COF(NTAB,NTAB), the polynomial\n% coefficients for the I-th Lagrange basis polynomial are stored\n% in column I. POLY_COF(1,I) is the constant term, and POLY_COF(1,NTAB)\n% is the coefficient of X**(NTAB-1).\n%\n\n%\n% Initialize POLY_COF to the identity matrix.\n%\n poly_cof(1:ntab,1:ntab) = 0.0;\n for i = 1 : ntab\n poly_cof(i,i) = 1.0;\n end\n%\n% Compute the divided difference table for the IVAL-th Lagrange basis\n% polynomial.\n%\n for i = 1 : ntab\n poly_cof(1:ntab,i) = ( data_to_dif ( ntab, xtab, poly_cof(1:ntab,i) ) )';\n end\n%\n% Convert the divided difference table coefficients to standard polynomial\n% coefficients.\n%\n for i = 1 : ntab\n poly_cof(1:ntab,i) = ( dif_to_r8poly ( ntab, xtab, poly_cof(1:ntab,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/divdif/r8poly_basis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7958152607736757}} {"text": "% \"Powel test function which has n decision variables, has no local optima.\n%has one global optimum. all decision variables are bounded in [-4\n% 5]. One global minimum at x=[3 -1 0, 1...,3 -1 0 1] with f(x)=0\n\nfunction sum=test10(x)\nsum=0;\n\nb=numel(x)/4;\n\nfor i=1:b\n sum=sum+(x(4*i-3)+10*x(4*i-2)).^2+5*(x(4*i-1)-x(4*i)).^2+(x(4*i-2)-x(4*i-1)).^4+10*(x(4*i-3)-x(4*i)).^4;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43326-modified-harmony-search-optimisation-with-linearly-decreasing-par-and-exponentially-decreasing-bw/test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7958152584585683}} {"text": "function H_MMSE = MMSE_CE(Y,Xp,pilot_loc,Nfft,Nps,h,SNR)\n%function H_MMSE = MMSE_CE(Y,Xp,pilot_loc,Nfft,Nps,h,ts,SNR)\n% MMSE channel estimation function\n% Inputs:\n% Y = Frequency-domain received signal\n% Xp = Pilot signal\n% pilot_loc = Pilot location\n% Nfft = FFT size\n% Nps = Pilot spacing\n% h = Channel impulse response\n% ts = Sampling time\n% SNR = Signal-to-Noise Ratio[dB]\n% output:\n% H_MMSE = MMSE channel estimate\n\n%H = fft(h,N);\nsnr = 10^(SNR*0.1);\nNp=Nfft/Nps; k=1:Np; \nH_tilde = Y(1,pilot_loc(k))./Xp(k); % LS estimate\nk=0:length(h)-1; %k_ts = k*ts; \nhh = h*h'; \ntmp = h.*conj(h).*k; %tmp = h.*conj(h).*k_ts;\nr = sum(tmp)/hh; \nr2 = tmp*k.'/hh; %r2 = tmp*k_ts.'/hh;\ntau_rms = sqrt(r2-r^2); % rms delay\ndf = 1/Nfft; %1/(ts*Nfft);\nj2pi_tau_df = j*2*pi*tau_rms*df;\nK1 = repmat([0:Nfft-1].',1,Np); \nK2 = repmat([0:Np-1],Nfft,1);\nrf = 1./(1+j2pi_tau_df*(K1-K2*Nps));\nK3 = repmat([0:Np-1].',1,Np); \nK4 = repmat([0:Np-1],Np,1);\nrf2 = 1./(1+j2pi_tau_df*Nps*(K3-K4));\nRhp = rf;\nRpp = rf2 + eye(length(H_tilde),length(H_tilde))/snr;\nH_MMSE = transpose(Rhp*inv(Rpp)*H_tilde.'); % MMSE channel estimate", "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/第6章 信道估计/MMSE_CE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346834, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7956347873633547}} {"text": "% X: data matrix, each row is one observation, each column is one feature\n% d: reduced dimension\n% type: type of kernel, can be 'simple', 'poly', or 'gaussian'\n% para (input): parameter for computing the 'poly' kernel, for 'simple'\n% and 'gaussian' it will be ignored\n% Y: dimensionanlity-reduced data\n% eigVector: eigen-vector, will later be used for pre-image\n% reconstruction\n% para (output): automatically selected Gaussian kernel parameter\n\n% Copyright by Quan Wang, 2011/05/10\n% Please cite: Quan Wang. Kernel Principal Component Analysis and its\n% Applications in Face Recognition and Active Shape Models.\n% arXiv:1207.3538 [cs.CV], 2012.\n\nfunction [Y, eigVector, para]=kPCA(X,d,type,para)\n\n%% check input\nif ( strcmp(type,'simple') || strcmp(type,'poly') || ...\n strcmp(type,'gaussian') ) == 0\n Y=[];\n eigVector=[];\n para=[];\n fprintf(['\\nError: Kernel type ' type ' is not supported. \\n']);\n return;\nend\n\n%% parameters\nN=size(X,1);\nif strcmp(type,'gaussian')\n DIST=zeros(N,N);\n for k=1:size(X,2)\n [a,b]=meshgrid(X(:,k));\n DIST=DIST+(a-b).^2;\n end\n DIST=DIST.^0.5;\n DIST=DIST+diag(ones(N,1)*inf);\n para=10*median(min(DIST));\nend\n\n%% kernel PCA\nK0=kernel(X,type,para);\noneN=ones(N,N)/N;\nK=K0-oneN*K0-K0*oneN+oneN*K0*oneN;\n\n%% eigenvalue analysis\n[V,D]=eig(K/N);\neigValue=diag(D);\n% eigValue=eigValue(1:min(size(X)));\n[eigValue,IX]=sort(eigValue,'descend');\neigVector=V(:,IX);\n\n%% normailization\nnorm_eigVector=sqrt(sum(eigVector.^2));\neigVector=eigVector./repmat(norm_eigVector,size(eigVector,1),1);\n\n%% dimensionality reduction\nY=K0*eigVector(:,1:d);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39715-kernel-pca-and-pre-image-reconstruction/kPCA_v2.0/code/kPCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7954989210706672}} {"text": "function n = cfn_e_size_total ( m, ell_max )\n\n%*****************************************************************************80\n%\n%% CFN_E_SIZE_TOTAL: Closed Fully Nested, Exponential Growth.\n%\n% Discussion:\n%\n% This calculation assumes that an exponential growth rule is being used,\n% that is, that the 1D rules have orders 1, 3, 7, 15, 31, and so on.\n%\n% It counts the number of points in all the product rules that compose\n% the sparse grid, and it does not reduce the count in any way to account\n% for repeated points.\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% 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 M, the spatial dimension.\n%\n% Input, integer ELL_MAX, the sparse grid level.\n%\n% Output, integer N, the total number of points in the grids.\n%\n n = 0;\n\n lvec = zeros ( m, 1 );\n\n ell_min = max ( ell_max + 1 - m, 0 );\n\n for ell = ell_min : ell_max\n\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ lvec, more, h, t ] = comp_next ( ell, m, lvec, more, h, t );\n\n nvec = cfn_e_nvec_from_lvec ( lvec );\n ell_num = prod ( nvec(1:m) );\n n = n + ell_num;\n\n if ( ~ more ) \n break\n end\n\n end\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_count/cfn_e_size_total.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7954626515783451}} {"text": "function varargout = boundedCentroidalVoronoi2d(germs, box, varargin)\n%BOUNDEDCENTROIDALVORONOI2D Create a 2D Centroidal Voronoi Tesselation in a box.\n%\n% [N, E, F] = boundedCentroidalVoronoi2d(GERMS, BOX)\n% GERMS are N-by-2 point array, BOX is given as [xmin xmax ymin ymax].\n% Algorithm is an iteration of voronoi diagram computations, using at\n% each steps the centroids of previous diagram as germs for the new\n% diagram.\n%\n% [N, E, F] = boundedCentroidalVoronoi2d(GERMS, BOX, NITER)\n% Specifies the number of iterations. Default is 10.\n%\n% [N, E, F, G] = boundedCentroidalVoronoi2d(...)\n% also returns the positions of germs/centroids for each face. If the\n% number of iteration was sufficient, location of germs should correspond\n% to centroids of faces 'fc' computed using: \n% fc(i,:) = polygonCentroid(n(f{i}, :));\n%\n% Example\n% [n, e, f] = boundedCentroidalVoronoi2d(rand(20, 2)*100, [0 100 0 100]);\n% drawGraph(n, e, f);\n%\n% See also \n% graphs, boundedVoronoi2d, centroidalVoronoi2d, clipGraph\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2007-01-12\n% Copyright 2007-2022 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas\n\n% number of iteration\nnIter = 10;\nif ~isempty(varargin)\n nIter = varargin{1};\nend\n\n% limits and size of the box\nx0 = box(1); x1 = box(2);\ny0 = box(3); y1 = box(4);\ndx = x1 - x0; dy = y1 - y0;\n\n% far points to bound the voronoi diagram\nfarPoints = [...\n x1 + 10 * dx, y1 + 10 * dy;...\n x0 - 10 * dx, y1 + 10 * dy;...\n x0 - 10 * dx, y0 - 10 * dy;...\n x1 + 10 * dx, y0 - 10 * dy];\n\n% iterate bounded voronoi tesselation\nfor i = 1:nIter\n % generate Voronoi diagram, and clip with the box\n [n, e, f] = voronoi2d([germs ; farPoints]);\n [n, e, f] = clipGraph(n, e, f, box);\n \n % centroid of each face will be used as germs for next iteration\n for j = 1:length(f)\n face = n(f{j}, :);\n germs(j, 1:2) = polygonCentroid(face);\n end\nend\n\n% result is given in n, e, and f, eventually germs\nvarargout{1} = n;\nvarargout{2} = e;\nvarargout{3} = f;\nif nargout > 3\n varargout{4} = germs;\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/graphs/boundedCentroidalVoronoi2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7954442911194407}} {"text": "function z = distSqr_fast(x,y,x2,y2) %x2 = sum(x.^2,1)'; %y2 = sum(y.^2,1);\n% function z = distSqr_fast(x,y,x2,y2)\n%\n% Return matrix of all-pairs squared distances between the vectors\n% in the columns of x and y.\n%\n% INPUTS\n% \tx \tdxn matrix of vectors\n% \ty \tdxm matrix of vectors\n%\n% OUTPUTS\n% \tz \tnxm matrix of squared distances\n%\n% This routine is faster when mn. In other words y should be\n% smaller than x.\n%\n% David Martin \n% March 2003\n\n% Based on dist2.m code,\n% Copyright (c) Christopher M Bishop, Ian T Nabney (1996, 1997)\n\nif ~exist('y','var')\n y = x;\nend\n\nif ~exist('x2','var')\n x2 = sum(x.^2,1)';\nend\n\nif ~exist('y2','var')\n y2 = sum(y.^2,1);\nend\n\nif size(x,1) ~= size(y,1), \n error('size(x,1)~=size(y,1)'); \nend\n\n[d,n] = size(x);\n[d,m] = size(y);\n\n%z = x'*y\n%z = repmat(x2,1,m) ...\n% + repmat(y2,n,1) ...\n% - 2*x'*y;\n%return\n\nz = x'*y;\n\nfor i = 1:m,\n z(:,i) = x2 + y2(i) - 2*z(:,i);\nend\n\n%z = zeros(n,m);\n%for i = 1:m,\n% z(:,i) = x2 + y2(i) - 2*x'*y(:,i);\n%end\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/util/distSqr_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7954442819165433}} {"text": "function rotatedData = rotatePoints(alignmentVector, originalData)\n\n% rotatedData = rotatePoints(alignmentVector, originalData) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \n% Rotate the 'originalData' in the form of Nx2 or Nx3 about the origin by aligning the x-axis with the alignment vector\n% \n% Rdata = rotatePoints([1,2,-1], [Xpts(:), Ypts(:), Zpts(:)]) - rotate the (X,Y,Z)pts in 3D with respect to the vector [1,2,-1]\n% \n% Rotating using spherical components can be done by first converting using [dX,dY,dZ] = cart2sph(theta, phi, rho); alignmentVector = [dX,dY,dZ];\n% \n% Example:\n% %% Rotate the point [3,4,-7] with respect to the following:\n% %%%% Original associated vector is always [1,0,0]\n% %%%% Calculate the appropriate rotation requested with respect to the x-axis. For example, if only a rotation about the z-axis is\n% %%%% sought, alignmentVector = [2,1,0] %% Note that the z-component is zero\n% rotData = rotatePoints(alignmentVector, [3,4,-7]);\n% \n% Author: Shawn Arseneau\n% Created: Feb.2, 2006\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n alignmentDim = numel(alignmentVector);\n DOF = size(originalData,2); %---- DOF = Degrees of Freedom (i.e. 2 for two dimensional and 3 for three dimensional data)\n \n if alignmentDim~=DOF \n error('Alignment vector does not agree with originalData dimensions'); \n end\n if DOF<2 || DOF>3 \n error('rotatePoints only does rotation in two or three dimensions'); \n end\n \n \n if DOF==2 % 2D rotation... \n [rad_theta, rho] = cart2pol(alignmentVector(1), alignmentVector(2)); \n deg_theta = -1 * rad_theta * (180/pi);\n ctheta = cosd(deg_theta); stheta = sind(deg_theta);\n \n Rmatrix = [ctheta, -1.*stheta;...\n stheta, ctheta];\n rotatedData = originalData*Rmatrix; \n \n else % 3D rotation... \n [rad_theta, rad_phi, rho] = cart2sph(alignmentVector(1), alignmentVector(2), alignmentVector(3));\n rad_theta = rad_theta * -1; \n deg_theta = rad_theta * (180/pi);\n deg_phi = rad_phi * (180/pi); \n ctheta = cosd(deg_theta); stheta = sind(deg_theta);\n Rz = [ctheta, -1.*stheta, 0;...\n stheta, ctheta, 0;...\n 0, 0, 1]; %% First rotate as per theta around the Z axis\n rotatedData = originalData*Rz;\n\n [rotX, rotY, rotZ] = sph2cart(-1* (rad_theta+(pi/2)), 0, 1); %% Second rotation corresponding to phi\n rotationAxis = [rotX, rotY, rotZ];\n u = rotationAxis(:)/norm(rotationAxis); %% Code extract from rotate.m from MATLAB\n cosPhi = cosd(deg_phi);\n sinPhi = sind(deg_phi);\n invCosPhi = 1 - cosPhi;\n x = u(1);\n y = u(2);\n z = u(3);\n Rmatrix = [cosPhi+x^2*invCosPhi x*y*invCosPhi-z*sinPhi x*z*invCosPhi+y*sinPhi; ...\n x*y*invCosPhi+z*sinPhi cosPhi+y^2*invCosPhi y*z*invCosPhi-x*sinPhi; ...\n x*z*invCosPhi-y*sinPhi y*z*invCosPhi+x*sinPhi cosPhi+z^2*invCosPhi]';\n\n rotatedData = rotatedData*Rmatrix; \n end\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/22158-plot-a-plane-or-line-in-3d/rotatePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.795387725396091}} {"text": "function [phi] = evalPhi( r );\n%\n% [phi] = evalPhi( r );\n%\n% Calculates phi( r ), phi the discrete delta function (without scaling)\n% \n% Returns:\n% phi = value of unscaled discrete delta function at each point, r\n%\n% Input:\n% r = the points to evaluate the discrete delta function at\n%\n% Note: \n% This code doesn't handle wrapping across periodic boundaries.\n%\n%\n% License: This code is free to use for any purposes, provided\n% any publications resulting from the use of this code\n% reference the original code/author.\n%\n% Author: Samuel Isaacson (isaacson@math.utah.edu)\n% Date: 11/2007\n%\n% Please notify the author of any bugs, and contribute any\n% modifications or bug fixes back to the original author.\n%\n% Disclaimer:\n% This code is provided as is. The author takes no responsibility \n% for its results or effects.\n\n\nphi = zeros(length(r), 1);\naR = abs( r );\nidx1 = find( aR < 1 );\nidx2 = find( aR >= 1 );\n\nrT = aR(idx1);\nphi(idx1) = 3 - 2*rT + sqrt( 1 + 4*rT - 4*rT.*rT );\n\nrT = aR(idx2);\nphi(idx2) = 5 - 2*rT - sqrt( -7 + 12*rT - 4*rT.*rT );\n\nphi = phi / 8;\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/IBM/evalPhi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7953877138099795}} {"text": "function centroid = polyhedron_centroid_3d ( coord, maxorder, face_num, node, ...\n node_num, order )\n\n%*****************************************************************************80\n%\n%% POLYHEDRON_CENTROID_3D computes the centroid of a polyhedron in 3D.\n%\n% Discussion:\n%\n% The centroid can be computed as the volume-weighted average of\n% the centroids of the tetrahedra defined by choosing a point in\n% the interior of the polyhedron, and using as a base every triangle\n% created by triangulating the faces of the polyhedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real COORD(3,NODE_NUM), the vertices.\n% The vertices may be listed in any order.\n%\n% Input, integer MAXORDER, the maximum number of vertices that make\n% up a face of the polyhedron.\n%\n% Input, integer FACE_NUM, the number of faces of the polyhedron.\n%\n% Input, integer NODE(FACE_NUM,MAXORDER). Face I is defined by\n% the vertices NODE(I,1) through NODE(I,ORDER(I)). These vertices\n% are listed in neighboring order.\n%\n% Input, integer NODE_NUM, the number of points stored in COORD.\n%\n% Input, integer ORDER(FACE_NUM), the number of vertices making up\n% each face.\n%\n% Output, real CENTROID(3), the centroid of the polyhedron.\n%\n dim_num = 3;\n%\n% Compute a point in the interior.\n% We take the area-weighted centroid of each face.\n%\n point(1:dim_num) = 0.0;\n area = 0.0;\n\n for face = 1 : face_num\n\n vert_num = order(face);\n\n v(1:dim_num,1:vert_num) = coord(1:dim_num,node(face,1:vert_num));\n\n [ polygon_area, normal ] = polygon_area_3d ( vert_num, v );\n\n polygon_centroid(1:dim_num) = polygon_centroid_3d ( vert_num, v );\n\n point(1:dim_num) = point(1:dim_num) + polygon_area * polygon_centroid(1:dim_num);\n\n area = area + polygon_area;\n\n end\n\n point(1:dim_num) = point(1:dim_num) / area;\n%\n% Now triangulate each face.\n% For each triangle, consider the tetrahedron created by including POINT.\n%\n centroid(1:dim_num) = 0.0;\n volume = 0.0;\n\n for face = 1 : face_num\n\n n3 = node(face,order(face));\n\n for vert = 1 : order(face) - 2\n\n n1 = node(face,vert);\n n2 = node(face,vert+1);\n\n tetra(1:dim_num,1:4) = [ ...\n coord(1:dim_num,n1)'; coord(1:dim_num,n2)'; coord(1:dim_num,n3)'; point(1:dim_num) ]';\n\n tetra_volume = tetrahedron_volume_3d ( tetra );\n\n tetra_centroid(1:dim_num) = tetrahedron_centroid_3d ( tetra );\n\n centroid(1:dim_num) = centroid(1:dim_num) + tetra_volume * tetra_centroid(1:dim_num);\n\n volume = volume + tetra_volume;\n\n end\n end\n\n centroid(1:dim_num) = centroid(1:dim_num) / volume;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polyhedron_centroid_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7953768162713887}} {"text": "function xyPoints=getEllipseHullPoints(z,A,gammaVal,numPoints,invertA)\n%%GETELLIPSHULLPOINTS Consider an ellipsoid in 3D (x,y,z) coordinates. For\n% every fixed z coordinate, if the x-y plane at the z coordinate\n% intersects the ellipsoid, it cuts an ellipse. For example, the\n% function projEllipse2ZPlane gets the parameters of the ellipse of\n% intersection. This function gets points marking the outer limits of\n% all of those ellipses in the x-y plane (the hull of the ellipses).\n%\n%INPUTS: z A 3XN vector corresponding to the centers of the N ellipses for\n% which points should be obtained.\n% A A 3X3XN set of N positive definite matrices that specify the\n% size and shape of the ellipsoids, where a point zp is on the ith\n% ellipsoid if\n% (zp-z(:,i))'*A(:,:,i)*(zp-z(:,i))=gammaVal (if invertA is true,\n% then replace A(:,:,i) with inv(A(:,:,i))).\n% gammaVal An optional parameter specifying the size of the ellipse/\n% ellipsoid. If omitted or an empty matrix is passed, then\n% gammaVal=18.8049 is used. This is approximately the value for a\n% 99.97% confidence region if A are inverse covariance matrices of\n% a Gaussian distribution. gammaVal must be positive gammaVal must\n% be positive.\n% numPoints An optional parameter specifying how many points should be\n% generated. The default if omitted or an empty matrix is passed\n% is 500.\n% invertA If this is true, then A is inverted before use. The default if\n% omitted or an empty matrix is passed is false.\n%\n%OUTPUTS: xyPoints A 2XnumPointsXN set of the points for each of the\n% ellipsoid projection hulls.\n%\n%The 3D ellipsoid (with the coordinate system shited to put the origin at\n%the center) is defined as x'*R*x=gammaVal. We can rewrite this as \n%[r*u,z]*R*[r*u;z]=gammaVal\n%where r is a positive scalar and u is a 2X1 unit vector. The matrix R can\n%be broken up accordingly as\n%R=[Rxy, rz;\n% rz', rzz];\n%We want the maximum extent of the ellipsoid in the x-y plane for each\n%direction (as specified by u). This will provide the hull of the ellipsoid\n%points. Thus, we perform the optimization:\n% maximize (over r,z) r^2\n% such that r^2*u'*Rxy*u+2*r*z*rz'*u+z^2*rzz=gammaVal\n%where the constraint is just from rewriting the expression for the\n%definition of an ellipsoid. Writing the Lagrangian, (with lambda as the\n%Lagrangian parameter) taking derivatives and setting them equal to 0, we\n%get two additional equations. Solving those two equations with the\n%original constraint, we get expressions for r, z, and lambda. Choosing the\n%solution such that r is positive and nonzero, one gets the expressions\n%implemented in this function.\n%\n%December 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(invertA))\n invertA=false;\nend\n\nif(nargin<4||isempty(numPoints))\n numPoints=500; \nend\n\nif(nargin<3||isempty(gammaVal))\n gammaVal=18.8049;\nend \n\nif(invertA)\n A=applyFunToEachMatrix(@inv,A);\nend\n\nnumEllipse=size(z,2);\n\ntheta=linspace(-pi,pi,numPoints);\nu=[cos(theta);\n sin(theta)];\nxyPoints=zeros(2,numPoints,numEllipse);\nfor curEllipse=1:numEllipse\n Rxyrzz=A(1:2,1:2,curEllipse)*A(3,3,curEllipse);\n rz=A(1:2,3,curEllipse);\n rzzGamma=A(3,3,curEllipse)*gammaVal;\n zXYCur=z(1:2,curEllipse);\n\n for k=1:numPoints\n uCur=u(:,k);\n \n r=sqrt(rzzGamma/(uCur'*Rxyrzz*uCur-(rz'*uCur)^2));\n xyPoints(:,k,curEllipse)=zXYCur-r*uCur;\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/getEllipseHullPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.7953290020241527}} {"text": "function [C, sigma] = dataset3Params(X, y, Xval, yval)\n%EX6PARAMS 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] = EX6PARAMS(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\nresults = eye(64,3);\nerrorRow = 0;\n\nfor C_test = [0.01 0.03 0.1 0.3 1, 3, 10 30]\n for sigma_test = [0.01 0.03 0.1 0.3 1, 3, 10 30]\n errorRow = errorRow + 1;\n model = svmTrain(X, y, C_test, @(x1, x2) gaussianKernel(x1, x2, sigma_test));\n predictions = svmPredict(model, Xval);\n prediction_error = mean(double(predictions ~= yval));\n\n results(errorRow,:) = [C_test, sigma_test, prediction_error]; \n end\nend\n\nsorted_results = sortrows(results, 3); % sort matrix by column #3, the error, ascending\n\nC = sorted_results(1,1);\nsigma = sorted_results(1,2);\n\n\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "Borye", "repo": "machine-learning-coursera-1", "sha": "033fdc2e6da393eeb1179a09aafe92362021effb", "save_path": "github-repos/MATLAB/Borye-machine-learning-coursera-1", "path": "github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 7 Assignments/Support Vector Machines/mlclass-ex6/dataset3Params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8918110569397306, "lm_q1q2_score": 0.7953269407650919}} {"text": "function [ wval, dwdx ] = r8poly_lagrange_factor ( npol, xpol, xval )\n\n%*****************************************************************************80\n%\n%% R8POLY_LAGRANGE_FACTOR evaluates the polynomial Lagrange factor at a point.\n%\n% Formula:\n%\n% W(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )\n%\n% Discussion:\n%\n% Suppose F(X) is at least N times continuously differentiable in the\n% interval [A,B]. Pick NPOL distinct points XPOL(I) in [A,B] and compute\n% the interpolating polynomial P(X) of order NPOL ( and degree NPOL-1)\n% which passes through all the points ( XPOL(I), F(XPOL(I)) ).\n% Then in the interval [A,B], the maximum error\n%\n% abs ( F(X) - P(X) )\n%\n% is bounded by:\n%\n% C * FNMAX * W(X)\n%\n% where\n%\n% C is a constant,\n% FNMAX is the maximum value of the NPOL-th derivative of F in [A,B],\n% W(X) is the Lagrange factor.\n%\n% Thus, the value of W(X) is useful as part of an estimated bound\n% for the interpolation error.\n%\n% Note that the Chebyshev abscissas have the property that they minimize\n% the value of W(X) over the interval [A,B]. Hence, if the abscissas may\n% be chosen arbitrarily, the Chebyshev abscissas have this advantage over\n% other choices.\n%\n% For a set of points XPOL(I), 1 <= I <= NPOL, the IPOL-th Lagrange basis\n% polynomial L(IPOL)(X), has the property:\n%\n% L(IPOL)( XPOL(J) ) = delta ( IPOL, J )\n%\n% and may be expressed as:\n%\n% L(IPOL)(X) = W(X) / ( ( X - XPOL(IPOL) ) * W'(XPOL(IPOL)) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NPOL, the number of abscissas.\n% NPOL must be at least 1.\n%\n% Input, real XPOL(NPOL), the abscissas, which should \n% be distinct.\n%\n% Input, real XVAL, the point at which the Lagrange \n% factor is to be evaluated.\n%\n% Output, real WVAL, the value of the Lagrange factor at XVAL.\n%\n% Output, real DWDX, the derivative of W with respect to XVAL.\n%\n wval = prod ( xval - xpol(1:npol) );\n\n dwdx = 0.0;\n\n for i = 1 : npol\n\n term = 1.0;\n\n for j = 1 : npol\n if ( i ~= j )\n term = term * ( xval - xpol(j) );\n end\n end\n\n dwdx = dwdx + term;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8poly_lagrange_factor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.7953082125654461}} {"text": "function ry = vecroty(angle) \n% \n% Function Name: \n% \n% vecroty - Transformation matrix for a rotation around the y axis. \n% \n% Calling Sequence: \n% \n% ry = vecroty(angle); \n% \n% Parameters: \n% \n% angle\t\t: rotation angle defined in radians \n% \n% ry\t\t: (4x4) Transformation matrix. \n% \n% \n% Description: \n% \n% Return the (4x4) Transformation matrix for a rotation about the y axis \n% by the defined angle. \n% \n% The matrix is: \n% \n% [ cos(angle) 0 sin(angle) 0] \n% [ 0 1 0 0] \n% [ -sin(angle) 0 cos(angle) 0] \n% [ 0 0 0 1] \n% \n% Examples: \n% \n% Rotate the NURBS line (0.0 0.0 0.0) - (3.0 3.0 3.0) by 45 degrees \n% around the y-axis \n% \n% line = nrbline([0.0 0.0 0.0],[3.0 3.0 3.0]); \n% trans = vecroty(%pi/4); \n% rline = nrbtform(line, trans); \n% \n% See: \n% \n% nrbtform \n \n% Dr D.M. Spink \n% Copyright (c) 2000. \n \nsn = sin(angle); \ncn = cos(angle); \nry = [cn 0 sn 0; 0 1 0 0; -sn 0 cn 0; 0 0 0 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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/vecroty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7952660657688548}} {"text": "function a=randNestedParenth(n)\n%%RANDNESTEDPARENTH Obtain a random character string of randomly nested\n% parentheses. Such parantheses can represent random\n% binary trees.\n%\n%INPUTS: n The number of open-closed parenthesis pairs.\n%\n%OUTPUTS: a A (2*n)X1 character string of n parenthesis pairs, with the\n% open parenthesis always coming before the close one.\n%\n%This function implements Algorithm W of Chapter 7.2.1.6 of [1].\n%\n%EXAMPLE:\n% a=randNestedParenth(5).'\n%We transpose it to make it easier to read.\n%\n%REFERENCES\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\np=n;\nq=n;\nm=1;\n%Allocate space for the random set of nested parentheses.\na=repmat(' ',2*n,1);\n\nwhile(q~=0)\n while(1)\n upperBound=(q+p)*(q-p+1);\n X=randi(upperBound-1);\n \n if(X<(q+1)*(q-p))\n q=q-1;\n a(m)=')';\n m=m+1;\n break; \n end\n p=p-1;\n a(m)='(';\n m=m+1;\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Combinatorics/randNestedParenth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8947894710123925, "lm_q1q2_score": 0.795252000140902}} {"text": "function rad=dms2rad(dms)\n% DMS2RAD Converts degrees-minutes-seconds to radians.\n% Vectorized.\n% Version: 12 Mar 00\n% Useage: rad=dms2rad(dms)\n% Input: dms - [d m s] array of angles in deg-min-sec, where\n% d = vector of degrees\n% m = vector of minutes\n% s = vector of seconds\n% Output: rad - vector of angles in radians\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nd=dms(:,1);\nm=dms(:,2);\ns=dms(:,3);\ndec=abs(d)+abs(m)./60+abs(s)./3600;\nrad=dec.*pi./180;\nind=(d<0 | m<0 | s<0);\nrad(ind)=-rad(ind);\n", "meta": {"author": "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/dms2rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7952335161449922}} {"text": "%................................................................\n\nfunction stiffness=formStiffness2D(GDof,numberElements,...\n elementNodes,numberNodes,nodeCoordinates,C,thickness)\n\n% compute stiffness matrix\n% for plane stress Q8 elements\n\nstiffness=zeros(GDof);\n\n% 3 by 3 quadrature\n[gaussWeights,gaussLocations]=gauss2d('3x3');\n\nfor e=1:numberElements \n numNodePerElement = length(elementNodes(e,:));\n numEDOF = 2*numNodePerElement;\n elementDof=zeros(1,numEDOF);\n for i = 1:numNodePerElement\n elementDof(2*i-1)=2*elementNodes(e,i)-1;\n elementDof(2*i)=2*elementNodes(e,i); \n end\n \n % cycle for Gauss point\n for q=1:size(gaussWeights,1) \n GaussPoint=gaussLocations(q,:); \n xi=GaussPoint(1);\n eta=GaussPoint(2);\n \n% shape functions and derivatives\n [shapeFunction,naturalDerivatives]=shapeFunctionQ8(xi,eta);\n\n% Jacobian matrix, inverse of Jacobian, \n% derivatives w.r.t. x,y \n [Jacob,invJacobian,XYderivatives]=...\n Jacobian(nodeCoordinates(elementNodes(e,:),:),naturalDerivatives);\n \n% B matrix\n B=zeros(3,numEDOF);\n B(1,1:2:numEDOF) = XYderivatives(:,1)'; \n B(2,2:2:numEDOF) = XYderivatives(:,2)';\n B(3,1:2:numEDOF) = XYderivatives(:,2)';\n B(3,2:2:numEDOF) = XYderivatives(:,1)';\n \n% stiffness matrix\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+...\n B'*C*thickness*B*gaussWeights(q)*det(Jacob); \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/FEM/Lab10_Q8/formStiffness2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7950998556432874}} {"text": "function [qp]=zn2fr(input)\n% [qp]=zn2fr(input)\n% Ziegler-Nichols PID controller for processes of 2nd order.\n% This function computes parameters of the controller (q0, q1, q2, p1, p2).\n% Controller is based on forward rectangular method of discretization.\n% Transfer function of the controller is as follows:\n%\n% q0 + q1*z^-1 + q2*z^-2 q0 + q1*z^-1 + q2*z^-2\n% G(z^-1) = ------------------------ = ------------------------\n% 1 - z^-1 1 + p1*z^-1 + p2*z^-2\n%\n% where p1=-1 and p2=0.\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2\n% Gs(z^-1) = -----------------------\n% 1 + a1*z^-1 + a2*z^-2\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... sample time T0\n% Output: qp ... controller parameters \n% qp(1) ... q0\n% qp(2) ... q1\n% qp(3) ... q2\n% qp(4) ... -1 (p1 of the controller)\n% qp(5) ... 0 (p2 of the controller)\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\nT0 = input(5);\n\n% compute ultimate gain and frequency\n[Kpu, Tu] = ultim([b1 b2],[a1 a2],T0);\n\nKp = 0.6*Kpu;\nTi = Tu/2;\nTd = Tu/8;\n\nq0 = Kp*(1+Td/T0);\nq1 = -Kp*(1-T0/Ti+2*Td/T0);\nq2 = Kp*(Td/T0);\np1 = -1;\np2 = 0;\n\nqp=[q0; q1; q2; p1; 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/8381-stcsl-standard-version/zn2fr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7950802153299902}} {"text": "function ex2bvp\n%EX2BVP Example 2 of the BVP tutorial.\n% A standard linear problem with a boundary layer at the origin.\n% The differential equation y'' + 3*p*y/(p + t^2)^2 = 0 has the \n% analytical solution y(t) = t/sqrt(p + t^2). The parameter p\n% is taken to be 1e-5, a common value in tests. The solution is\n% to have specified values at t = -0.1 and +0.1, values taken from\n% this analytical solution.\n% \n% The default RelTol of 1e-3 gives an acceptable solution, but \n% reducing RelTol to 1e-4 resolves better the boundary layer. A \n% constant guess is used for RelTol = 1e-3. The same guess could be\n% used for RelTol = 1e-4, but a very much better guess is provided \n% by the solution previously computed for RelTol = 1e-3.\n\n% Copyright 2002, The MathWorks, Inc.\n\n% Evaluate the analytical solution for comparison.\ntt = -0.1:0.01:+0.1;\np = 1e-5;\nyy = tt ./ sqrt(p + tt .^2);\n\noptions = bvpset('stats','on','Fjacobian',@ex2Jac);\n\n% BVPINT is used to specify an initial guess for the mesh of 10\n% equally spaced points. A constant guess based on a straight line\n% between the boundary values for y is 0 for y(t) and 10 for y'(t).\nsolinit = bvpinit(linspace(-0.1,0.1,10),[0 10]);\n\nsol = bvp4c(@ex2ode,@ex2bc,solinit, options);\nt = sol.x;\ny = sol.y;\n\nfigure\nplot(t,y(1,:),tt,yy,'*')\naxis([-0.1 0.1 -1.1 1.1])\ntitle(['Linear boundary layer problem with RelTol = 1e-3.'])\nxlabel('t')\nylabel('y and analytical (*) solutions')\n\nfprintf('\\n');\n\n% A smaller RelTol is used to resolve better the boundary layer.\n% The previous solution provides an excellent guess.\noptions = bvpset(options,'RelTol',1e-4);\nsol = bvp4c(@ex2ode,@ex2bc,sol,options);\nt = sol.x;\ny = sol.y;\n\nfigure\nplot(t,y(1,:),tt,yy,'*')\naxis([-0.1 0.1 -1.1 1.1])\ntitle(['Linear boundary layer problem with RelTol = 1e-4.'])\nxlabel('t')\nylabel('y and analytical (*) solutions')\n\n% --------------------------------------------------------------------------\n\nfunction dydt = ex2ode(t,y)\n%EX2ODE ODE function for Example 2 of the BVP tutorial. \n% The components of y correspond to the original variables\n% as y(1) = y, y(2) = y'.\np = 1e-5;\ndydt = [ y(2)\n -3*p*y(1)/(p+t^2)^2];\n\n% --------------------------------------------------------------------------\n\nfunction dfdy = ex2Jac(t,y)\n%EX2JAC The Jacobian of the ODE function for Example 2 of the BVP tutorial. \np = 1e-5;\ndfdy = [ 0 1\n -3*p/(p+t^2)^2 0 ]; \n\n% --------------------------------------------------------------------------\n\nfunction res = ex2bc(ya,yb)\n%EX2BC Boundary conditions for Example 2 of the BVP tutorial.\n% The boundary conditions are that the solution should agree\n% with the values of an analytical solution at both a and b.\np = 1e-5;\nyatb = 0.1/sqrt(p + 0.01);\nyata = - yatb;\nres = [ ya(1) - yata\n yb(1) - yatb ];\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples_65/ex2bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8976952968970956, "lm_q1q2_score": 0.7950272115404389}} {"text": "function coeffsRet=polyIntMultiDim(coeffs,intDim,intConst)\n%%POLYINTMULTIDIM Compute the indefinite integral of a multivariate\n% polynomial with respect to a particular dimension given a\n% hypermatrix of its coefficients (including cross terms). \n%\n%INPUTS: coeffs A hypermatrix of the coefficients for the multivariate\n% polynomial. These are arranged such that\n% coeffs(a1,a2,a3...an) corresponds to the coefficient of an\n% x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1) term. Thus, the\n% number of indices coeffs takes is equal to the\n% dimensionality of x (not counting singleton dimensions at\n% the end of coeffs). Note that this ordering is the reverse\n% that used in the 1D polyval function that is built into\n% Matlab. The number of elements for each index in coeffs is\n% the maximum order of that dimension +1.\n% intDim The dimension of x (index of coeffs) with respect to which\n% the integral is to be taken.\n% intConst The integration constant. If this parameter is omitted or\n% an empty matrix is passed, a default value of 0 is used.\n%\n%OUTPUTS: coeffsRet The indefinite integral of the coeffs hypermatrix.\n%\n%This function is just implemented using the basic rules of polynomial\n%integration.\n%\n%As an example, consider the multivariate polynomial:\n%14+3*x1^2-18*x2+12*x1*x3-3*x2*x3\n%The integrals with respect to the first, second and third variables are\n% coeffs=zeros(3,2,2);\n% coeffs(0+1,0+1,0+1)=14;\n% coeffs(2+1,0+1,0+1)=3;\n% coeffs(0+1,1+1,0+1)=-18;\n% coeffs(1+1,0+1,1+1)=12;\n% coeffs(0+1,1+1,1+1)=-3;\n% intCoeffs1=polyIntMultiDim(coeffs,1);\n% intCoeffs2=polyIntMultiDim(coeffs,2);\n% intCoeffs3=polyIntMultiDim(coeffs,3);\n%One will see that intCoeffs1 corresponds to\n%14*x1+x1^3-18*x1*x2+6*x1^2*x3-3*x1*x2*x3\n%intCoeffs2 corresponds to\n%14*x2*+3*x1^2*x2-9*x2^2+12*x1*x2*x3-(3/2)*x2^2*x3\n%and intCoeffs3 corresponds to.\n%14*x3+3*x1^2*x3-18*x2*x3+6*x1*x3^2-(3/2)*x2*x3^2\n%\n%Note that the fucntion can be used with variables that are not present in\n%the original polynomial. In the above example,\n% intCoeffs4=polyIntMultiDim(coeffs,4);\n%provides coefficients corresponding to\n%14*x4+3*x1^2*x4-18*x2*x4+12*x1*x3*x4-3*x2*x3*x4\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(intConst))\n intConst=0; \nend\n\ndimSizeList=size(coeffs);\nnumIdx=length(dimSizeList);\ntotalEls=prod(dimSizeList);\n\n%If the dimension of integration is a singleton dimension that has been\n%suppressed from the end of dimSizeList, then we must add in all of the\n%missing singleton dimensions.\ndimRetSizeList=[dimSizeList,ones(1,intDim-numIdx)];\n%Integration will increase the maximum degree of the term over which\n%integration is performed by one, meaning that the matrix has to be made\n%larger.\ndimRetSizeList(intDim)=dimRetSizeList(intDim)+1;\n\n%Allocate space for the return coefficients.\ncoeffsRet=zeros(dimRetSizeList);\n\n%We will now loop through all of the values in the original coefficient\n%set, adjusting them and inserting them into the proper location in the new\n%modified coefficient set, after multiplication by the appropriate\n%constant.\n\nif(intDim>numIdx)\n%This is used when integrating over a trailing singleton dimension.\n indicesFull=ones(numIdx,1);\n indicesFull(intDim)=2;\nend\nfor curEl=1:totalEls\n curCoeff=coeffs(curEl);\n indices=index2NDim(dimSizeList,curEl);\n \n if(intDim<=numIdx)\n constVal=1/indices(intDim);\n indices(intDim)=indices(intDim)+1;\n coeffsRet(nDim2Index(dimRetSizeList,indices))=constVal*curCoeff;\n else%If we are integration over a trailing singleton dimension.\n indicesFull(1:numIdx)=indices;\n coeffsRet(nDim2Index(dimRetSizeList,indicesFull))=curCoeff;\n end\nend\n\n%Add in the integration constant. It is the zeroth-order term.\ncoeffsRet(1)=intConst;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/Generic_Multivariate_Polynomials/polyIntMultiDim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8856314753275019, "lm_q1q2_score": 0.7950272035196098}} {"text": "function value = quad_fun ( n )\n\n%*****************************************************************************80\n%\n%% QUAD_FUN demonstrates MATLAB's PARFOR command for parallel programming.\n%\n% Discussion:\n%\n% This function estimates an integral using the composite trapezoidal rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points to use.\n%\n% Output, real VALUE, the estimate for the integral.\n%\n a = 0.0;\n b = 1.0;\n\n value = 0.0;\n h = ( b - a ) / ( n - 1 );\n\n parfor i = 1 : n\n\n x = ( ( n - i ) * a + ( i - 1 ) * b ) / ( n - 1 );\n\n fx = f ( x );\n\n if ( i == 1 )\n value = value + 0.5 * fx * h\n elseif ( i < n )\n value = value + fx * h;\n elseif ( i == n )\n value = value + 0.5 * fx * h;\n end\n\n end\n\n return\nend\nfunction value = f ( x )\n\n%*****************************************************************************80\n%\n%% F is the function to be integrated.\n%\n% Discussion:\n%\n% The integral of F(X) from 0 to 1 is exactly PI.\n%\n% Modified:\n%\n% 17 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the values where the integrand is to be evaluated.\n%\n% Output, real VALUE, the integrand values.\n%\n value = 4.0 ./ ( 1 + x.^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quad_parfor/quad_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367524, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.7949850372819994}} {"text": "function [center,radius] = minboundsphere(xyz)\n% minboundsphere: Compute the minimum radius enclosing sphere of a set of (x,y,z) triplets\n% usage: [center,radius] = minboundsphere(xyz)\n%\n% arguments: (input)\n% xyz - nx3 array of (x,y,z) triples, describing points in R^3\n% as rows of this array.\n%\n%\n% arguments: (output)\n% center - 1x3 vector, contains the (x,y,z) coordinates of\n% the center of the minimum radius enclosing sphere\n%\n% radius - scalar - denotes the radius of the minimum\n% enclosing sphere\n%\n%\n% Example usage:\n% Sample uniformly from the interior of a unit sphere. \n% As the sample size increases, the enclosing sphere\n% should asymptotically approach center = [0 0 0], and\n% radius = 1.\n%\n% xyz = rand(10000,3)*2-1;\n% r = sqrt(sum(xyz.^2,2));\n% xyz(r>1,:) = []; % 5156 points retained\n% tic,[center,radius] = minboundsphere(xyz);toc\n% \n% Elapsed time is 0.199467 seconds.\n%\n% center = [0.00017275 8.5006e-05 0.00012015]\n%\n% radius = 0.9999\n%\n% Example usage:\n% Sample from the surface of a unit sphere. Within eps\n% or so, the result should be center = [0 0 0], and radius = 1.\n%\n% xyz = randn(10000,3);\n% xyz = xyz./repmat(sqrt(sum(xyz.^2,2)),1,3);\n% tic,[center,radius] = minboundsphere(xyz);toc\n%\n% Elapsed time is 0.614762 seconds.\n%\n% center =\n% 4.6127e-17 -2.5584e-17 7.2711e-17\n%\n% radius =\n% 1\n%\n%\n% See also: minboundrect, minboundcircle\n%\n%\n% Author: John D'Errico\n% E-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 1/23/07\n\n% not many error checks to worry about\nsxyz = size(xyz);\nif (length(sxyz)~=2) || (sxyz(2)~=3)\n error 'xyz must be an nx3 array of points'\nend\nn = sxyz(1);\n\n% start out with the convex hull of the points to\n% reduce the problem dramatically. Note that any\n% points in the interior of the convex hull are\n% never needed.\nif n>4\n tri = convhulln(xyz,{'QJ' 'Pp'});\n\n % list of the unique points on the convex hull itself\n hlist = unique(tri(:));\n\n % exclude those points inside the hull as not relevant\n xyz = xyz(hlist,:);\n \nend\n\n% now we must find the enclosing sphere of those that\n% remain.\nn = size(xyz,1);\n\n% special case small numbers of points. If we trip any\n% of these cases, then we are done, so return.\nswitch n\n case 0\n % empty begets empty\n center = [];\n radius = [];\n return\n case 1\n % with one point, the center has radius zero\n center = xyz;\n radius = 0;\n return\n case 2\n % only two points. center is at the midpoint\n center = mean(xyz,1);\n radius = norm(xyz(1,:) - center);\n return\n case 3\n % exactly 3 points. For this odd case, just use enc4,\n % appending a new point at the centroid. This is simpler\n % than other solutions that would have reduced the\n % problem to 2-d. enc4 will do that anyway.\n [center,radius] = enc4([xyz;mean(xyz,1)]);\n return\n case 4\n % exactly 4 points\n [center,radius] = enc4(xyz);\n return\nend\n\n% pick a tolerance\ntol = 10*eps*max(max(abs(xyz),[],1) - min(abs(xyz),[],1));\n\n% more than 4 points. for no more than 15 points in the hull,\n% just do an exhaustive search.\nif n <= 15\n % for 15 points, there are only nchoosek(15,4) = 1365\n % sets to look through. this is only about a second.\n asets = nchoosek(1:n,4);\n \n center = inf(1,3);\n radius = inf;\n for i = 1:size(asets,1)\n aset = asets(i,:);\n iset = setdiff(1:n,aset);\n \n % get the enclosing sphere for the current set\n [centeri,radiusi] = enc4(xyz(aset,:));\n \n % are all the inactive set points inside the circle?\n ri = sqrt(sum((xyz(iset,:) - repmat(centeri,n-4,1)).^2,2));\n \n [rmax,k] = max(ri);\n if ((rmax - radiusi) <= tol) && (radiusi < radius) \n center = centeri;\n radius = radiusi;\n end\n end\n \nelse\n % Use an active set strategy, on many different\n % random starting sets.\n center = inf(1,3);\n radius = inf;\n \n for i = 1:250\n aset = randperm(n); % a random start, but quite adequate\n iset = aset(5:n);\n aset = aset(1:4);\n \n flag = true;\n iter = 0;\n centeri = inf(1,3);\n radiusi = inf;\n while flag && (iter < 12)\n iter = iter + 1;\n \n % get the enclosing sphere for the current set\n [centeri,radiusi] = enc4(xyz(aset,:));\n \n % are all the inactive set points inside the circle?\n ri = sqrt(sum((xyz(iset,:) - repmat(centeri,n-4,1)).^2,2));\n \n [rmax,k] = max(ri);\n if (rmax - radiusi) <= tol\n % the active set enclosing sphere also enclosed\n % all of the inactive points. We are done.\n flag = false;\n else\n % it must be true that we can replace one member of aset\n % with iset(k). That k'th element was farthest out, so\n % it seems best (a greedy algorithm) to swap it in. The\n % problem with the greedy algorithm, is it gets trapped\n % in a cycle at times. but since we are restarting the\n % algorithm multiple times, this will work.\n s1 = [aset([2 3 4]),iset(k)];\n [c1,r1] = enc4(xyz(s1,:));\n if (norm(c1 - xyz(aset(1),:)) <= r1)\n centeri = c1;\n radiusi = r1;\n \n % update the active/inactive sets\n swap = aset(1);\n aset = [iset(k),aset([2 3 4])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n s1 = [aset([1 3 4]),iset(k)];\n [c1,r1] = enc4(xyz(s1,:));\n if (norm(c1 - xyz(aset(2),:)) <= r1)\n centeri = c1;\n radiusi = r1;\n \n % update the active/inactive sets\n swap = aset(2);\n aset = [iset(k),aset([1 3 4])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n s1 = [aset([1 2 4]),iset(k)];\n [c1,r1] = enc4(xyz(s1,:));\n if (norm(c1 - xyz(aset(3),:)) <= r1)\n centeri = c1;\n radiusi = r1;\n \n % update the active/inactive sets\n swap = aset(3);\n aset = [iset(k),aset([1 2 4])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n s1 = [aset([1 2 3]),iset(k)];\n [c1,r1] = enc4(xyz(s1,:));\n if (norm(c1 - xyz(aset(4),:)) <= r1)\n centeri = c1;\n radiusi = r1;\n \n % update the active/inactive sets\n swap = aset(4);\n aset = [iset(k),aset([1 2 3])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n \n % if we get through to this point, then something went wrong.\n % Active set problem. Increase tol, then try again.\n tol = 2*tol;\n \n end\n end\n \n % have we improved over the best set so far?\n if radiusi < radius\n center = centeri;\n radius = radiusi;\n end\n end\nend\n\n% =======================================\n% begin subfunctions\n% =======================================\nfunction [center,radius] = enc4(xyz)\n% minimum radius enclosing sphere for exactly 4 points in R^3\n%\n% xyz is a 4x3 array\n%\n% Note that enc4 will attempt to pass a sphere through all\n% 4 of the supplied points. When the set of points proves to \n% be degenerate, perhaps because of collinearity of 3 or\n% more of the points, or because the 4 points are coplanar,\n% then the sphere would nominally have infinite radius. Since\n% there must be a finite radius sphere to enclose any set of\n% finite valued points, enc4 will provide that sphere instead.\n%\n% In addition, there are some non-degenerate sets of points\n% for which the circum-sphere is not minimal. enc4 will always\n% try to find the minimum radius enclosing sphere.\n\n% interpoint distance matrix D\n% dfun = @(A) (A(:,[1 1 1 1]) - A(:,[1 1 1 1])').^2;\ndfun = inline('(A(:,[1 1 1 1]) - A(:,[1 1 1 1])'').^2','A');\nD = sqrt(dfun(xyz(:,1)) + dfun(xyz(:,2)) + dfun(xyz(:,3)));\n\n% Find the most distant pair. Test if their circum-sphere\n% also encloses the other points. If it does, then we are\n% done.\n[dij,ij] = max(D(:));\n[i,j] = ind2sub([4 4],ij);\nothers = setdiff(1:4,[i,j]);\nradius = dij/2;\ncenter = (xyz(i,:) + xyz(j,:))/2;\nif (norm(center - xyz(others(1),:))<=radius) && ...\n (norm(center - xyz(others(2),:))<=radius)\n % we can stop here.\n return\nend\n\n% next, we need to test each triplet of points, finding their\n% enclosing sphere. If the 4th point is also inside, then we\n% are done.\nind = 1:3;\n[center,radius,isin] = enc3_4(xyz(ind,:),xyz(4,:),D(ind,ind));\nif isin\n % the 4th point was inside this enclosing sphere.\n return\nend\n\nind = [1 2 4];\n[center,radius,isin] = enc3_4(xyz(ind,:),xyz(3,:),D(ind,ind));\nif isin\n % the 3rd point was inside this enclosing sphere.\n return\nend\n\nind = [1 3 4];\n[center,radius,isin] = enc3_4(xyz(ind,:),xyz(2,:),D(ind,ind));\nif isin\n % the second point was inside this enclosing sphere.\n return\nend\n\nind = [2 3 4];\n[center,radius,isin] = enc3_4(xyz(ind,:),xyz(1,:),D(ind,ind));\nif isin\n % the first point was inside this enclosing sphere.\n return\nend\n\n% find the circum-sphere that passes through all 4 points\n% since we have passed all the other tests, we need not\n% worry here about singularities in the system of\n% equations.\nA = 2*(xyz(2:4,:)-repmat(xyz(1,:),3,1));\nrhs = sum(xyz(2:4,:).^2 - repmat(xyz(1,:).^2,3,1),2);\ncenter = (A\\rhs)';\nradius = norm(center - xyz(1,:));\n\n\n% =======================================\nfunction [center,radius,isin] = enc3_4(xyz,xyztest,Di)\n% minimum radius enclosing sphere for exactly 3 points in R^3\n%\n% xyz - a 3x3 array, with each row as a point in R^3\n%\n% xyztest - 1x3 vector, a point to be tested if it is\n% inside the generated enclosing sphere.\n% \n% Di - 3x3 array of interpoint distances\n\n% test the farthest pair of points. do they form a diameter\n% of the sphere?\nif Di(1,2)>=max(Di(1,3),Di(2,3))\n center = mean(xyz([1 2],:),1);\n radius = Di(1,2)/2;\n isin = (norm(xyz(3,:) - center)<=radius) && (norm(xyztest - center)<=radius);\nelseif Di(1,3)>=max(Di(1,2),Di(2,3))\n center = mean(xyz([1 3],:),1);\n radius = Di(1,3)/2;\n isin = (norm(xyz(2,:) - center)<=radius) && (norm(xyztest - center)<=radius);\nelseif Di(2,3)>=max(Di(1,2),Di(1,3))\n center = mean(xyz([2 3],:),1);\n radius = Di(2,3)/2;\n isin = (norm(xyz(1,:) - center)<=radius) && (norm(xyztest - center)<=radius);\nend\nif isin\n % we found the minimal enclosing sphere already\n return\nend\n\n% If we drop down to here, no singularities should\n% happen (I've already caught any degeneracies.)\n\n% We transform the three points into a plane, then\n% compute the enclosing sphere in that plane.\n\n% translate to the origin\nxyz0 = xyz(1,:);\nxyzt = xyz(2:3,:) - [xyz0;xyz0];\n\nrot = orth(xyzt');\n\n% uv is composed of 2 points, in 2-d, plus we\n% have the origin (after the translation)\nuv = xyzt*rot;\n\nA = 2*uv;\nrhs = sum(uv.^2,2);\ncenter = (A\\rhs)';\nradius = norm(center - uv(1,:));\n\n% rotate and translate back\ncenter = center*rot' + xyz0;\n\n% test if the 4th point is enclosed also\nisin = (norm(xyztest - center)<=radius);\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34767-a-suite-of-minimal-bounding-objects/MinBoundSuite/minboundsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.7948904379814702}} {"text": "function [p,s]=v_minspane(x)\n%V_MINSPANE calculate minimum spanning tree using euclidean distance [p,s]=X\n%\n% Inputs: x(n,d) d-dimensional data points, one per row\n%\n% Outputs: p(n-1,1) indices of the parent of each node within the tree\n% (data point n is the root)\n% s(n-1,1) list of the edges in ascending order of euclidean\n% distance. Thus the shortest edge goes from node\n% s(1) to node p(s(1))\n%\n% The minimum spanning tree (or shortest spanning tree ) defines a set of\n% n-1 links that interconnect n points (or nodes) with the minimum total\n% length. We represent these links in the form of a tree with node n as\n% the root. Each node (except node n) has a unique parent node that is\n% given in the output vector p; it is possible for several nodes to share\n% the same parent.\n% It can be useful to know which of the links are the longest, so the output\n% argument lists them in ascending order. s could be calculated directly by\n% calculaing the length, l, of each link as follows:\n% l=sqrt(sum((x(1:n-1,:) - x(p,:)).^2),2);\n% [v,s]=sort(l);\n\n% Copyright (C) Mike Brookes 2000-2009\n% Version: $Id: v_minspane.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[np,nd]=size(x);\n\n% first do delauny tessalation to find feasible edges\n\nt=delaunayn(x); % nd+1 vertices per polytope\nnt=size(t,1);\ncn=v_choosenk(nd+1,2);\nnf=size(cn,1);\nee=zeros(nt,nf,2); % space for all the edges\nee(:,:,1)=t(:,cn(:,1));\nee(:,:,2)=t(:,cn(:,2));\nee=reshape(ee,[],2);\nmk=ee(:,1)>ee(:,2);\nee(mk,:)=ee(mk,2:-1:1); % make all edges in ascending order\n% ees=sparse(ee(:,1),ee(:,2),1); % remove duplicates\n[er,ec]=find(sparse(ee(:,1),ee(:,2),1)); % remove duplicates\nee=[er,ec];\nne=size(ee,1);\n\n% now apply Kruskal shortest spanning tree algorithm\n\nsz=sum((x(ee(:,1),:)-x(ee(:,2),:)).^2,2); % length^2 of each edge\n[vz,mz]=sort(sz);\nee=ee(mz,:); % sort edges into ascenging length order\nts=ones(ne,1); % size of each component\ntp=zeros(np,1); % root node links\nei=zeros(np-1,1); % index of shortest spanning tree edges\nk=0;\nfor i=1:ne\n i1=ee(i,1);\n j=tp(i1);\n while j % find root node for ee(i,1)\n i1=j;\n j=tp(i1);\n end\n i2=ee(i,2);\n j=tp(i2);\n while j % find root node for ee(i,2)\n i2=j;\n j=tp(i2);\n end\n if i1~=i2 % if they are different, merge them\n k=k+1;\n ei(k)=i; % add to the shortest spanning tree\n if ts(i1)>ts(i2)\n tp(i2)=i1; % make i2 a sub tree of i1\n ts(i1)=ts(i1)+ts(i2);\n else\n tp(i1)=i2; % make i1 a sub tree of i2\n ts(i2)=ts(i1)+ts(i2);\n end\n end\nend\nee=ee(ei,:); % refine the edges to include only those in the minimum spanning tree\n\n% now arrange as a tree with point np as the head\n\neet=sparse(ee(:,1),ee(:,2),1:np-1,np,np);\np=zeros(np-1,1); % points to parent node\ns=zeros(np-1,1); % sorted index\nchn=np; % start with the root node of the tree\n[rf,cf]=find(eet(:,chn)); % find any nodes that connect to it\n[rg,cg]=find(eet(chn,:));\nwhile ~isempty(rf) || ~isempty(rg)\n p(rf)=chn(cf); % set the parents\n rcf=rf(:)+np*(chn(cf(:))-1);\n s(eet(rcf))=rf(:);\n eet(rcf)=0; % delete the edges linking them to their parents\n p(cg)=chn(rg);\n rcg=chn(rg(:))+np*(cg(:)-1);\n s(eet(rcg))=cg(:);\n eet(rcg)=0;\n chn=[rf(:); cg(:)]; % now search for their children\n [rf,cf]=find(eet(:,chn));\n [rg,cg]=find(eet(chn,:));\nend\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_minspane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8723473879530491, "lm_q1q2_score": 0.7948652441927265}} {"text": "%% A 10x10 tridiagonal matrix, with 2 on the diagonal, -1 on the off diagonal.\n\nA = blktridiag(2,-1,-1,10);\n\n% The sparsity pattern is correct\nspy(A)\n\n% and the elements are as designated\nfull(A)\n\n%% A lower block bidiagonal matrix with replicated blocks\n\n% with 2x2 blocks of ones on the main diagonal, and\n% 2x2 blocks of twos on the sub-diagonal\n\nA = blktridiag(ones(2),2*ones(2),zeros(2),5);\n\nspy(A)\nfull(A)\n\n%% A block tridiagonal matrix with replicated blocks\n\nAmd = reshape(1:9,3,3);\nAsub = reshape(11:19,3,3);\nAsup = reshape(21:29,3,3);\nA = blktridiag(Amd,Asub,Asup,4);\n\nspy(A)\nfull(A)\n\n%% A tridiagonal matrix with random elements\n\nAmd = rand(1,1,7);\nAsub = rand(1,1,6);\nAsup = rand(1,1,6);\nA = blktridiag(Amd,Asub,Asup);\n\nspy(A)\nfull(A)\n\n%% A block tridiagonal matrix with distinct elements\n\nAmd = reshape(1:27,[3 3 3]);\nAsub = reshape(101:118,[3 3 2]);\nAsup = reshape(201:218,[3 3 2]);\nA = blktridiag(Amd,Asub,Asup);\n\nspy(A)\nfull(A)\n\n%% A block tridiagonal matrix with 2x3 fixed non-square blocks\n\nAmd = rand(2,3);\nAsub = 2*ones(2,3);\nAsup = ones(2,3);\nA = blktridiag(Amd,Asub,Asup,3);\n\nspy(A)\nfull(A)\n\n%% A block tridiagonal matrix with varying 3x2 non-square blocks\nAmd = reshape(1:18,[3 2 3]);\nAsub = reshape(101:112,[3 2 2]);\nAsup = reshape(201:212,[3 2 2]);\nA = blktridiag(Amd,Asub,Asup);\n\nspy(A)\nfull(A)\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/10603-block-tri-diagonal-matrices/BLKTRIDIAG/demo/blktridiag_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7948652161209134}} {"text": "function lagrange_nd_test07 ( )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_ND_TEST07 tests LAGRANGE_ND_COMPLETE in 3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_ND_TEST07\\n' );\n fprintf ( 1, ' LAGRANGE_COMPLETE determines\\n' );\n fprintf ( 1, ' the Lagrange interpolating polynomials L(x)\\n' );\n fprintf ( 1, ' for ND points in D dimensions, assuming that\\n' );\n fprintf ( 1, ' the number of points exactly coincides with\\n' );\n fprintf ( 1, ' R = Pi(D,N), the number of monomials of degree N or less\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data points are the grid nodes of a tetrahedron.\\n' );\n\n d = 3;\n n = 2;\n r = mono_upto_enum ( d, n );\n nd = 10;\n xd = [ 0.0, 0.0, 0.0; ...\n 1.0, 0.0, 0.0; ...\n 2.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 1.0, 1.0, 0.0; ...\n 0.0, 2.0, 0.0; ...\n 0.0, 0.0, 1.0; ...\n 1.0, 0.0, 1.0; ...\n 0.0, 1.0, 1.0; ...\n 0.0, 0.0, 2.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension D = %d\\n', d );\n fprintf ( 1, ' Maximum degree N = %d\\n', n );\n fprintf ( 1, ' Number of monomials R = %d\\n', r );\n fprintf ( 1, ' Number of data points ND = %d\\n', nd );\n\n r8mat_transpose_print ( d, nd, xd, ' Data points XD:' );\n\n [ po, pc, pe ] = lagrange_complete ( d, n, r, nd, xd );\n%\n% Print the polynomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Lagrange polynomials for XD data points:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : nd\n o = po(i);\n label = sprintf ( ' P(%d)(x) =', i );\n polynomial_print ( d, o, pc(i,1:o), pe(i,1:o), label );\n end\n%\n% Evaluate the polynomials at XD.\n%\n value = zeros ( nd, nd );\n\n for j = 1 : nd\n o = po(j);\n label = sprintf ( ' P(%d)(x) =', j );\n value(1:nd,j) = polynomial_value ( d, o, pc(j,1:o), pe(j,1:o), nd, xd ); \n end\n\n err = r8mat_is_identity ( nd, value );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of Lagrange matrix error = %g\\n', err );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/lagrange_nd/lagrange_nd_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.7948652073769035}} {"text": "function c = min_errorbar_scale(stderrs,significance)\n% c = min_errorbar_scale(stderrs,significance) \n% returns the minimum scale factor c such that any pair of non-overlapping\n% error bars represents statistical significance exceeding the given level.\n% stderrs is a vector.\n% significance is a scalar.\n%\n% See \"Judging significance from error bars\" by Tom Minka (2002) \n% http://research.microsoft.com/~minka/papers/minka-errorbars.pdf\n%\n% Examples:\n% min_errorbar_scale(ones(10,1)) % returns 1.16\n% min_errorbar_scale(0:10) % returns 1.64\n\n% Written by Tom Minka\n\n% Algorithm:\n% We want c*(stderr(i)+stderr(j)) >= z*sqrt(stderr(i)^2+stderr(j)^2)\n% for all pairs (i,j). Therefore\n% c = max_(i,j) z*sqrt(stderr(i)^2+stderr(j)^2)/(stderr(i) + stderr(j));\n\nif nargin < 2\n significance = 0.95;\nend\n\nz = erfinv(2*significance - 1)*sqrt(2);\n\nn = length(stderrs);\nratio = zeros(n,1);\nfor i = 1:length(stderrs)\n exact = sqrt(stderrs(i).^2 + stderrs.^2);\n approx = stderrs(i) + stderrs;\n ratio(i) = max(exact./approx);\nend\nc = z*max(ratio);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+lightspeed/graphics/min_errorbar_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7948323001832656}} {"text": "function point = projPointOnLine3d(point, line)\n%PROJPOINTONLINE3D Project a 3D point orthogonally onto a 3D line.\n%\n% PT2 = projPointOnLine3d(PT, LINE).\n% Computes the (orthogonal) projection of 3D point PT onto the 3D line\n% LINE. \n% \n% Function works also for multiple points and lines. In this case, it\n% returns multiple points.\n% Point PT1 is a N-by-3 array, and LINE is a N-by-6 array.\n% Result PT2 is a N-by-3 array, containing coordinates of orthogonal\n% projections of PT1 onto lines LINE. \n%\n%\n% See also \n% projPointOnLine, distancePointLine3d\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2012-08-23\n% Copyright 2012-2022 INRA - TPV URPOI - BIA IMASTE\n\n% direction vector of the line\nvx = line(:, 4);\nvy = line(:, 5);\nvz = line(:, 6);\n\n% difference of point with line origin\ndx = point(:,1) - line(:,1);\ndy = point(:,2) - line(:,2);\ndz = point(:,3) - line(:,3);\n\n% Position of projection on line, using dot product\ndelta = vx .* vx + vy .* vy + vz .* vz;\ntp = (dx .* vx + dy .* vy + dz .* vz) ./ delta;\n\n% convert position on line to cartesian coordinates\npoint = [line(:,1) + tp .* vx, line(:,2) + tp .* vy, line(:,3) + tp .* vz];\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/projPointOnLine3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.794724528198949}} {"text": "function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...\n num_features, lambda)\n %COFICOSTFUNC Collaborative filtering cost function\n % [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...\n % num_features, lambda) returns the cost and gradient for the\n % collaborative filtering problem.\n %\n\n % Unfold the U and W matrices from params\n X = reshape(params(1:num_movies*num_features), num_movies, num_features);\n Theta = reshape(params(num_movies*num_features+1:end), ...\n num_users, num_features);\n\n\n % You need to return the following values correctly\n J = 0;\n X_Gradient = zeros(size(X));\n Theta_Gradient = zeros(size(Theta));\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Compute the cost function and gradient for collaborative\n % filtering. Concretely, you should first implement the cost\n % function (without regularization) and make sure it is\n % matches our costs. After that, you should implement the \n % gradient and use the checkCostFunction routine to check\n % that the gradient is correct. Finally, you should implement\n % regularization.\n %\n % Notes: X - num_movies x num_features matrix of movie features\n % Theta - num_users x num_features matrix of user features\n % Y - num_movies x num_users matrix of user ratings of movies\n % R - num_movies x num_users matrix, where R(i, j) = 1 if the \n % i-th movie was rated by the j-th user\n %\n % You should set the following variables correctly:\n %\n % X_grad - num_movies x num_features matrix, containing the \n % partial derivatives w.r.t. to each element of X\n % Theta_grad - num_users x num_features matrix, containing the \n % partial derivatives w.r.t. to each element of Theta\n %\n\n J_Temporary = power ((X * Theta' - Y), 2);\n J = sum (sum (J_Temporary (R == 1))) / 2 + ((lambda / 2) .* sum (sum (power (Theta, 2)))) + ((lambda / 2) .* sum (sum (power (X, 2))));\n\n X_Gradient = ((X * Theta' - Y) .* R) * Theta + lambda .* X;\n Theta_Gradient = ((X * Theta' - Y) .* R)' * X + lambda .* Theta;\n\n % =============================================================\n\n grad = [X_Gradient(:); Theta_Gradient(:)];\n\nend", "meta": {"author": "UtkarshPathrabe", "repo": "Machine-Learning-Stanford-University-Coursera", "sha": "0e5855855b5ddd475775b75bad69b47c2ebe84ef", "save_path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera", "path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera/Machine-Learning-Stanford-University-Coursera-0e5855855b5ddd475775b75bad69b47c2ebe84ef/Programming Exercises/machine-learning-ex8/ex8/cofiCostFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7946912299511192}} {"text": "function S = randsym(n, N)\n% Generates random symmetric matrices with normal entries.\n% \n% function S = randsym(n)\n% function S = randsym(n, N)\n%\n% S is an n-by-n-by-N array where each slice S(:, :, i) for i = 1..N is a\n% random symmetric matrix with upper triangular entries distributed\n% independently following a normal distribution (Gaussian, zero mean, unit\n% variance).\n%\n% By default, N = 1.\n%\n% See also: randrot randskew randherm randskewh\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Oct. 23, 2018.\n% Contributors: \n% Change log: \n% Oct. 23, 2018 (NB):\n% This is not technically necessary for the rotations factory,\n% but it is counter-intuitive to have access to a function called\n% randskew yet not have one for randsym.\n% June 19, 2019 (NB):\n% Now handles the case n = 1 properly.\n\n if nargin < 2\n N = 1;\n end\n \n if n == 1\n S = randn(1, 1, N);\n return;\n end\n\n % Subindices of the (strictly) upper triangular entries of an n-by-n\n % matrix.\n [I, J] = find(triu(ones(n), 1));\n \n K = repmat(1:N, n*(n-1)/2, 1);\n \n % Indices of the strictly upper triangular entries of all N slices of\n % an n-by-n-by-N array.\n L = sub2ind([n n N], repmat(I, N, 1), repmat(J, N, 1), K(:));\n \n % Allocate memory for N random symmetric matrices of size n-by-n and\n % populate each upper triangular entry with a random number following a\n % normal distribution and copy them on the corresponding lower\n % triangular side.\n S = zeros(n, n, N);\n S(L) = randn(size(L));\n S = S + multitransp(S);\n \n % Now populate the diagonal entries:\n \n % Subindices of the diagonal entries of an n-by-n matrix.\n [I, J] = find(eye(n));\n \n K = repmat(1:N, n, 1);\n \n % Indices of the diagonal entries of all N slices of an n-by-n-by-N\n % array.\n L = sub2ind([n n N], repmat(I, N, 1), repmat(J, N, 1), K(:));\n \n S(L) = randn(size(L));\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/rotations/randsym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7946122342012296}} {"text": "function [ w, cvx_optval ] = fdla( A ) %#ok\n\n% Computes the fastest distributed linear averaging (FDLA) edge weights\n%\n% [W,S] = FDLA(A) gives a vector of the fastest distributed linear averaging\n% edge weights for a graph described by the incidence matrix A (n x m).\n% Here n is the number of nodes and m is the number of edges in the graph;\n% each column of A has exactly one +1 and one -1.\n%\n% The FDLA edge weights are given by the SDP:\n%\n% minimize s\n% subject to -s*I <= I - L - (1/n)11' <= s*I\n%\n% where the variables are edge weights w in R^m and s in R.\n% Here L is the weighted Laplacian defined by L = A*diag(w)*A'.\n% The optimal value is s, and is returned in the second output.\n%\n% For more details see the references:\n% \"Fast linear iterations for distributed averaging\" by L. Xiao and S. Boyd\n% \"Convex Optimization of Graph Laplacian Eigenvalues\" by S. Boyd\n%\n% Written for CVX by Almir Mutapcic 08/29/06\n\n[n,m] = size(A); %#ok\nI = eye(n,n);\nJ = I - (1/n) * ones(n,n);\ncvx_begin sdp\n variable w(m,1) % edge weights\n variable s % epigraph variable\n variable L(n,n) symmetric\n minimize( s )\n subject to\n L == A * diag(w) * A'; %#ok\n -s * I <= J - L <= s * I; %#ok\ncvx_end\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/graph_laplacian/fdla.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779943094681, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7945998684869423}} {"text": "function varargout = xyy2xyz(varargin)\n%XYY2XYZ Convert chromaticity coordinates to XYZ tristimulus values.\n% [X,Y,Z] = XYY2XYZ(x,y,Y) converts the chromaticity coordinates (x\n% and y) and the Y tristimulus value to the tristimulus values X, Y,\n% and Z. Y, x, y, X, Y, and Z are all arrays with the same size.\n%\n% XYZ = XYY2XYZ(xyY) performs the conversion on a Px3 input matrix\n% where P(:,1) contains the x values, P(:,2) contains the y values,\n% and P(:,3) contains the Y values. The output matrix is also Px3.\n\n% Written by Steve Eddins to accompany Digital Image Processing Using\n% MATLAB, 3rd edition, Gatesmark Press, 2020,\n% http://imageprocessingplace.com.\n%\n% Copyright 2019 The MathWorks, Inc.\n% License: https://github.com/mathworks/matlab-color-tools/blob/master/license.txt\n\nif nargin == 3\n style = \"separate\";\n x = varargin{1};\n y = varargin{2};\n Y = varargin{3};\nelseif nargin == 1\n style = \"3-column\";\n xyY = varargin{1};\n x = xyY(:,1);\n y = xyY(:,2);\n Y = xyY(:,3);\nend\n\nX = Y .* x ./ y;\nZ = Y .* (1 - x - y) ./ y;\n\n% Handle the numerical edge case where y is 0.\nX(y == 0) = 0;\nZ(y == 0) = 0;\n\nif style == \"3-column\"\n varargout{1} = [X Y Z];\nelse\n varargout{1} = X;\n varargout{2} = Y;\n varargout{3} = Z;\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/mathworksLicensedFunctions/xyy2xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7945797402462541}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% Problem 8\n% Solve the difference equation \n% y[n]+1.5y[n-1]+0.5y[n-2]=x[n]+x[n-1] , x[n]=0.8^n u[n]\n\n\n\nsyms n z Y\nx=0.8^n;\nX=ztrans(x,z);\nX1=z^(-1)*X;\nY1=z^(-1)*Y;\nY2=z^(-2)*Y;\nG=Y+1.5*Y1+0.5*Y2-X-X1;\nSOL=solve(G,Y);\ny=iztrans(SOL,n)\n\n% a)\nn_s=0:20;\ny_s=subs(y,n,n_s);\nstem(n_s,y_s);\nlegend('Solution y[n]')\nxlim([-.5 20.5])\nylim([0 1.1])\n\n% b)\nxn=x;\nxn_1=0.8^(n-1);\nyn=y;\nyn_1=subs(y,n,n-1);\nyn_2=subs(y,n,n-2);\ntest=yn+1.5*yn_1+0.5*yn_2-xn-xn_1\nsimplify(test)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/10/c108f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7945691233533758}} {"text": "function coeff = fourier_comp(func,m,L)\n%FOURIER_COMP Numerically evaluate Fourier series coefficient.\n% coeff = fourier_comp(func,m,L) tries to approximate the function func\n% from -L to L with m term Fourier series using quad (MATLAB functions).\n% func is a function handle, should accept a vector argument x and return a\n% vector result y\n% This function return a structure with these fields:\n% coeff.a0\n% coeff.an\n% coeff.bn\n% The Fourier series for function f(x) is given below.\n% inf \n% -----\n% \\\n% f(x) = a0/2 + \\ an * sin(n*pi*x/L) + bn * con(n*pi*x/L) \n% /\n% /\n% -----\n% n = 1\n% \n% Example:\n% \n% f = @(x)x.*cos(x);\n% coeff = fourier_comp(f,3,pi)\n% coeff = \n% a0: 0\n% an: [-0.5000 1.3333 -0.7500]\n% bn: [1.4136e-016 0 7.0679e-017]\n% \n% See also\n% fourier_gui\n% \n% Author: Amin Bashi\n% Created: Jul 2009\n% Copyright 2009\n\n% func must be the function handle\n\nfor n = 1:m\n an(n) = quad(@fa,-L,L)/L;\n bn(n) = quad(@fb,-L,L)/L;\nend\na0 = quad(func,-L,L)/L;\ncoeff.a0 = a0;\ncoeff.an = an;\ncoeff.bn = bn;\n function y = fa(t)\n y = func(t).*sin(n*pi*t/L);\n end\n function y = fb(t)\n y = func(t).*cos(n*pi*t/L);\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/24779-fourier-series-calculator/fourier_comp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7944062123865715}} {"text": "function a = toeplitz_5diag ( n, d1, d2, d3, d4, d5 )\n\n%*****************************************************************************80\n%\n%% TOEPLITZ_5DIAG returns a pentadiagonal Toeplitz matrix.\n%\n% Formula:\n%\n% if ( I - J == 2 )\n% A(I,J) = D1\n% elseif ( I - J == 1 )\n% A(I,J) = D2\n% elseif ( I - J == 0 )\n% A(I,J) = D3\n% elseif ( I - J == -1 )\n% A(I,J) = D4\n% elseif ( I - J == -2 )\n% A(I,J) = D5\n% else\n% A(I,J) = 0.0\n%\n% Example:\n%\n% N = 5, D1 = 1, D2 = -10, D3 = 0, D4 = 10, D5 = 1\n%\n% 0 10 1 . .\n% -10 0 10 1 .\n% 1 -10 0 10 1\n% . 1 -10 0 10\n% . . 1 -10 0\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is Toeplitz: constant along diagonals.\n%\n% A is banded, with bandwidth 5.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% The special data D1 = 1, D2 = -10, D3 = 0, D4 = 10, D5 = 1 corresponds\n% to a matrix of Rutishauser.\n%\n% The matrix has eigenvalues lying approximately on the complex line\n% segment 2 * cos ( 2 * t ) + 20 * I * sin ( t ).\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% RM Beam, RF Warming,\n% The asymptotic spectra of banded Toeplitz and quasi-Toeplitz matrices,\n% SIAM Journal on Scientific and Statistical Computing,\n% Volume 14, Number 4, 1993, pages 971-1006.\n%\n% Heinz Rutishauser,\n% On test matrices,\n% Programmation en Mathematiques Numeriques,\n% Centre National de la Recherche Scientifique,\n% 1966, pages 349-365.\n%\n% Parameters:\n%\n% Input, integer N, the order of A. N should be at least 3.\n%\n% Input, D1, D2, D3, D4, D5, values that define the nonzero diagonals\n% of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i - j == 2 )\n a(i,j) = d1;\n elseif ( i - j == 1 )\n a(i,j) = d2;\n elseif ( i - j == 0 )\n a(i,j) = d3;\n elseif ( i - j == -1 )\n a(i,j) = d4;\n elseif ( i - j == -2 )\n a(i,j) = d5;\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/toeplitz_5diag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7944062106340517}} {"text": "function [ Grid,varargout ] = CavityGridOperators( N )\n%CAVITYGRIDOPERATORS generates the grid and operators\n[Grid]=CollocationGrid_q(N); % grid coordiuantes and indices\n\nif nargout==2\n varargout{1}= CreateOperators_psi( Grid.D,eye(N+1)); % derivative matrices\nend\n\n[~,Grid.wc] = clencurt(N);\n Grid.W = kron(Grid.wc,Grid.wc); % integration coefficients for computation of Kinetic Energy\n\nend\n\nfunction [Grid]=CollocationGrid_q(N)\n\n [Grid.D,Grid.x] = cheb(N);\n [xx,yy]=meshgrid(Grid.x,Grid.x); Grid.xx=xx(:);Grid.yy=yy(:); \n \n \n \n% Index positions for walls and interior\n Grid.Walls = find(abs(xx)==1 | abs(yy)==1);\n Grid.LeftWall = find(xx==-1); Grid.RightWall=find(xx==1);\n Grid.BottomWall=find(yy==-1); Grid.TopWall=find(yy==1);\n Grid.Interior = setdiff((1:length(Grid.xx)),Grid.Walls);\n\n \n % operators\n I = eye(N+1);\n Grid.D2 = (diag(1-Grid.x.^2)*Grid.D^2 - 4*diag(Grid.x)*Grid.D - 2*I);\n Grid.D4 = (diag(1-Grid.x.^2)*Grid.D^4 - 8*diag(Grid.x)*Grid.D^3 - 12*Grid.D^2); % Trefethen style\n \n\n % Propagation function\n Grid.S0 = (1-Grid.xx.^2).*(1-Grid.yy.^2);\n Grid.S1 = Grid.S0;\n Grid.S1(Grid.Walls)=1;\n \n % plot on cheb grid\n Grid.cplot = @(X) contourf(reshape(xx,N+1,N+1),reshape(yy,N+1,N+1),reshape(X,N+1,N+1),50,'LineStyle','None');\n\nend\n\n function [x,w] = clencurt(N)\n theta = pi*(0:N)'/N; x = cos(theta);\n w = zeros(1,N+1); ii = 2:N; v = ones(N-1,1);\n if mod(N,2)==0 \n w(1) = 1/(N^2-1); w(N+1) = w(1);\n for k=1:N/2-1, v = v - 2*cos(2*k*theta(ii))/(4*k^2-1); end\n v = v - cos(N*theta(ii))/(N^2-1);\n else\n w(1) = 1/N^2; w(N+1) = w(1);\n for k=1:(N-1)/2, v = v - 2*cos(2*k*theta(ii))/(4*k^2-1); end\n end\n w(ii) = 2*v/N;\n end\n \n function [ Operators_psi ] = CreateOperators_psi( D,I)\n%CREATEOPERATORS_q creates the Operator acting on psi(x)\nOperators_psi.Dx = kron(D,I);\nOperators_psi.Dy = kron(I,D);\nD2= D^2; D4=D2^2;\nOperators_psi.del2 = kron(D2,I)+kron(I,D2);\n\nOperators_psi.del4 = kron(D4,I)+kron(I,D4)+2*kron(D2,I)*kron(I,D2);\n\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/CavityGridOperators.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7944062021781361}} {"text": "function p = hen_polynomial_value ( m, n, x )\n\n%*****************************************************************************80\n%\n%% HEN_POLYNOMIAL_VALUE evaluates Hen(i,x).\n%\n% Discussion:\n%\n% Hen(i,x) is the normalized probabilist's Hermite polynomial of degree I.\n%\n% These polynomials satisfy the orthonormality condition:\n%\n% Integral ( -oo < X < +oo ) exp ( - 0.5 * X^2 ) * Hen(M,X) Hen(N,X) dX \n% = delta ( N, M )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964,\n% ISBN: 0-486-61272-4,\n% LC: QA47.A34.\n%\n% Frank Olver, Daniel Lozier, Ronald Boisvert, Charles Clark,\n% NIST Handbook of Mathematical Functions,\n% Cambridge University Press, 2010,\n% ISBN: 978-0521192255,\n% LC: QA331.N57.\n%\n% Parameters:\n%\n% Input, integer M, the number of evaluation points.\n%\n% Input, integer N, the highest order polynomial to compute.\n% Note that polynomials 0 through N will be computed.\n%\n% Input, real X(M,1), the evaluation points.\n%\n% Output, real P(M,N+1), the values of the polynomials of index 0 through N.\n%\n p = zeros ( m, n + 1 );\n\n p(1:m,1) = 1.0;\n\n if ( n == 0 )\n return\n end\n\n p(1:m,2) = x(1:m,1);\n \n for j = 2 : n\n p(1:m,j+1) = x(1:m,1) .* p(1:m,j) - ( j - 1 ) * p(1:m,j-1);\n end\n%\n% Normalize.\n%\n d = diag ( 1.0 ./ sqrt ( gamma ( 1:n+1) .* sqrt ( 2.0 * pi ) ) );\n\n p = p * d;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_polynomial/hen_polynomial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.7943644361176617}} {"text": "function varargout = gabrielGraph(pts)\n%GABRIELGRAPH Gabriel Graph of a set of points.\n%\n% EDGES = gabrielGraph(PTS)\n% Computes the Gabriel graph of the input set of points PTS. The Gabriel\n% graph is based on the euclidean Delaunay triangulation, and keeps only\n% edges whose circumcircle does not contain any other input point than\n% the edge extremities.\n%\n% [NODES, EDGES] = gabrielGraph(PTS)\n% Also returns the initial set of points;\n%\n% Example\n% pts = rand(100, 2);\n% edges = gabrielGraph(pts);\n% figure; drawPoint(pts);\n% hold on; axis([0 1 0 1]); axis equal;\n% drawGraph(pts, edges);\n%\n% See also \n% graphs, drawGraph, delaunayGraph\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2012-01-22, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\n% compute Delaunay triangulation\nif verLessThan('matlab', '8.1')\n % Code for versions before R2013a\n dt = DelaunayTri(pts); %#ok\nelse\n % Code for versions R2013a and later\n dt = delaunayTriangulation(pts);\nend\n\n% extract edges (N-by-2 array)\neds = dt.edges();\n\n% radius of the circle circumscribed to each edge\nrads = edgeLength([pts(eds(:,1), :) pts(eds(:,2), :)]) / 2;\n\n% extract middle point of each edge\nmidPts = midPoint(pts(eds(:,1), :), pts(eds(:,2), :));\n\n% distance between midpoints and all points\n% closest points should be edge vertices\ndists = minDistancePoints(midPts, pts);\n\n% geometric tolerance (adapted to point set extent)\ntol = max(max(pts) - min(pts)) * eps;\n\n% keep only edges whose circumcircle does not contain any other point\nkeep = dists >= rads - tol;\nedges = eds(keep, :);\n\n% format output depending on number of output arguments\nif nargout < 2\n varargout = {edges};\nelse\n varargout = {pts, edges};\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/graphs/gabrielGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.7943644330541938}} {"text": "function fx = p01_fun ( option, nvar, x )\n\n%*****************************************************************************80\n%\n%% P01_FUN evaluates the function for problem 1.\n%\n% Title:\n%\n% The Freudenstein-Roth function\n%\n% Description:\n%\n% One way to use a continuation code as a nonlinear root finder\n% is to start with a set of nonlinear equations G(X), and an\n% approximate root A, and create a \"homotopy\" function F(X,Y)\n% with the properties that F(A,0.0) = 0 and F(X,1.0) = G(X).\n% Thus, the homotopy function F has a known exact solution\n% from which we can start with no difficulty. If the continuation\n% code can take us from Y = 0 to Y = 1, then we have found\n% an X so that F(X,1.0) = 0, so we have found a solution to G(X)=0.\n%\n% The Freudenstein-Roth function F(X) is derived in this way\n% from a homotopy of G(X):\n%\n% F ( X(1), X(2), X(3) ) =\n% G ( X(1), X(2) ) - ( 1 - X(3) ) * G ( Y1, Y2 )\n%\n% where Y1 and Y2 are some fixed values, and\n%\n% G(1) = X(1) - X(2)*X(2)*X(2) + 5*X(2)*X(2) - 2*X(2) - 13\n% G(2) = X(1) + X(2)*X(2)*X(2) + X(2)*X(2) - 14*X(2) - 29\n%\n% Options 1, 2, 3:\n%\n% The starting point is X0 = ( 15, -2, 0 ).\n%\n% A great deal of information is available about the homotopy curve\n% generated by this starting point:\n%\n% The function F(X) has the form\n%\n% F(1) = X(1) - X(2)**3 + 5*X(2)**2 - 2*X(2) - 13 + 34*(X(3)-1)\n% F(2) = X(1) + X(2)**3 + X(2)**2 - 14*X(2) - 29 + 10*(X(3)-1)\n%\n% There is a closed form representation of the curve in terms of the\n% second parameter:\n%\n% X(1) = (-11*X(2)**3 + 4*X(2)**2 + 114*X(2) + 214) / 6\n% X(2) = X(2)\n% X(3) = ( X(2)**3 - 2*X(2)**2 - 6*X(2) + 4) / 12\n%\n% The first option simply requests the production of solution points\n% along the curve until a point is reached whose third component is\n% exactly 1.\n%\n% Options 2 and 3 use the same starting point, and also stop when the\n% third component is 1. However, these options in addition search\n% for limit points in the first and third components of the solution,\n% respectively.\n%\n% The target solution has X(3) = 1, and is ( 5, 4, 1 ).\n%\n% Limit points for X1:\n%\n% ( 14.28309, -1.741377, 0.2585779 )\n% ( 61.66936, 1.983801, -0.6638797 )\n%\n% Limit points for X3:\n%\n% (20.48586, -0.8968053, 0.5875873)\n% (61.02031, 2.230139, -0.6863528)\n%\n% The curve has several dramatic bends.\n%\n%\n% Options 4, 5, and 6:\n%\n% The starting point is (4, 3, 0).\n%\n% The function F(X) has the form\n%\n% F(1) = X(1) - X(2)**3 + 5*X(2)**2 - 2*X(2) - 13 + 3*(X(3)-1)\n% F(2) = X(1) + X(2)**3 + X(2)**2 - 14*X(2) - 29 - 31*(X(3)-1)\n%\n% There is a closed form representation of the curve in terms of the\n% second parameter:\n%\n% X(1) = (14*X(2)**3 -79*X(2)**2 +52*X(2) + 245) / 17\n% X(2) = X(2)\n% X(3) = ( X(2)**3 - 2*X(2)**2 - 6*X(2) + 9) / 17\n%\n% The correct value of the solution at X(3)=1 is:\n%\n% (5, 4, 1)\n%\n% In option 5, limit points in the first component are sought,\n% and in option 6, limit points in the third component are\n% sought.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Ferdinand Freudenstein, Bernhard Roth,\n% Numerical Solutions of Nonlinear Equations,\n% Journal of the Association for Computing Machinery,\n% Volume 10, 1963, Pages 550-556.\n%\n% Parameters:\n%\n% Input, integer OPTION, the option index.\n%\n% Input, integer NVAR, the number of variables.\n%\n% Input, real X(NVAR), the argument of the function.\n%\n% Output, real FX(NVAR-1), the value of the function at X.\n%\n\n% Get the starting point, Y.\n%\n y = p01_start ( option, nvar );\n%\n% G is the function value at the starting point,\n% F the function value at the current point.\n%\n gy = p01_gx ( y );\n\n gx = p01_gx ( x );\n%\n% The parameter X3 generates the homotopy curve.\n%\n fx(1:nvar-1) = gx(1:nvar-1) + ( x(3) - 1.0 ) * gy(1:nvar-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_con/p01_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7943644282749952}} {"text": "function value = i4_rise ( x, n )\n\n%*****************************************************************************80\n%\n%% I4_RISE computes the rising factorial function [X]^N.\n%\n% Discussion:\n%\n% [X]^N = X * ( X + 1 ) * ( X + 2 ) * ... * ( X + N - 1 ).\n%\n% Note that the number of ways of arranging N objects in M ordered\n% boxes is [M]^N. (Here, the ordering of the objects in each box matters).\n% Thus, 2 objects in 2 boxes have the following 6 possible arrangements:\n%\n% -|12, 1|2, 12|-, -|21, 2|1, 21|-.\n%\n% Moreover, the number of non-decreasing maps from a set of\n% N to a set of M ordered elements is [M]^N / N!. Thus the set of\n% nondecreasing maps from (1,2,3) to (a,b,c,d) is the 20 elements:\n%\n% aaa, abb, acc, add, aab, abc, acd, aac, abd, aad\n% bbb, bcc, bdd, bbc, bcd, bbd, ccc, cdd, ccd, ddd.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X, the argument of the rising factorial function.\n%\n% Input, integer N, the order of the rising factorial function.\n% If N = 0, RISE = 1, if N = 1, RISE = X. Note that if N is\n% negative, a \"falling\" factorial will be computed.\n%\n% Output, integer VALUE, the value of the rising factorial function.\n%\n value = 1;\n\n arg = x;\n\n if ( 0 < n )\n\n for i = 1 : n\n value = value * arg;\n arg = arg + 1;\n end\n\n elseif ( n < 0 )\n\n for i = -1 : -1 : n\n value = value * arg;\n arg = arg - 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/test_mat/i4_rise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7943644232305478}} {"text": "function Z = xkron(X,Y)\n%XKRON Kronecker tensor product.\n%\n% XKRON(X,Y), where X and Y are matrices, is the Kronecker tensor product\n% of X and Y. The result is a large matrix formed by taking all possible\n% products between the elements of X and those of Y.\n%\n% For example, if X is 2-by-3, and Y is any N-dimensional array, then\n% KRON(X,Y) is\n%\n% [ X(1,1)*Y X(1,2)*Y X(1,3)*Y\n% X(2,1)*Y X(2,2)*Y X(2,3)*Y ]\n%\n% If either X or Y is sparse, and neither X nor Y has dimension\n% greater than 2, then only nonzero elements are multiplied in the\n% computation, and the result is sparse.\n%\n% XKRON works also when X and/or Y are N-dimensional arrays. There does\n% not seem to be a unique definition of an N-dimensional Kronecker tensor\n% product, so I simply picked the one I found most logical.\n%\n% If X is 3-by-4-by-2, and Y is any N-dimensional array, then\n%\n% cat( 3, [ X(1,1,1)*Y X(1,2,1)*Y X(1,3,1)*Y X(1,4,1)*Y ; ...\n% X(2,1,1)*Y X(2,2,1)*Y X(2,3,1)*Y X(2,4,1)*Y ; ...\n% X(3,1,1)*Y X(3,2,1)*Y X(3,3,1)*Y X(3,4,1)*Y ], ...\n% [ X(1,1,2)*Y X(1,2,2)*Y X(1,3,2)*Y X(1,4,2)*Y ; ...\n% X(2,1,2)*Y X(2,2,2)*Y X(2,3,2)*Y X(2,4,2)*Y ; ...\n% X(3,1,2)*Y X(3,2,2)*Y X(3,3,2)*Y X(3,4,2)*Y ] )\n\n% Author: Peter J. Acklam\n% Time-stamp: 2002-03-03 13:50:29 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n xs = size(X);\n ys = size(Y);\n xd = length(xs);\n yd = length(ys);\n\n if ( issparse(X) | issparse(Y) ) & ( xd <= 2 ) & ( yd <= 2 )\n\n % When at least one input is sparse, and neither argument has\n % dimension greater than 2, the result is sparse.\n\n mx = xs(1); nx = xs(2);\n my = ys(1); ny = ys(2);\n\n [ix, jx, sx] = find(X);\n [iy, jy, sy] = find(Y);\n ix = ix(:); jx = jx(:); sx = sx(:);\n iy = iy(:); jy = jy(:); sy = sy(:);\n kx = ones(size(sx));\n ky = ones(size(sy));\n t = my*(ix-1)';\n ik = t(ky,:)+iy(:,kx);\n t = ny*(jx-1)';\n jk = t(ky,:)+jy(:,kx);\n Z = sparse(ik, jk, sy*sx.', mx*my, nx*ny);\n\n else\n\n dz = max(xd, yd);\n xs = [ xs ones(1,dz-xd) ];\n ys = [ ys ones(1,dz-yd) ];\n\n v = reshape( reshape( 1:2*dz, dz, 2 )', 1, 2*dz );\n Z = reshape( Y(:)*X(:).', [ ys xs ] );\n Z = reshape( permute( Z, v ), xs.*ys );\n\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/xkron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.794364422781302}} {"text": "function geometry_test20325 ( )\n\n%*****************************************************************************80\n%\n%% TEST20325 tests TETRAHEDRON_SIZE_3D, TETRAHEDRON_SHAPE_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST20325\\n' );\n fprintf ( 1, ' For the tetrahedron,\\n' );\n fprintf ( 1, ' TETRAHEDRON_SIZE_3D returns dimension information;\\n' );\n fprintf ( 1, ' TETRAHEDRON_SHAPE_3D returns face and order info.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We will use this information to compute the\\n' );\n fprintf ( 1, ' areas and centers of each face.\\n' );\n\n [ point_num, edge_num, face_num, face_order_max ] = ...\n tetrahedron_size_3d ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of points = %d\\n', point_num );\n fprintf ( 1, ' Number of edges = %d\\n', edge_num );\n fprintf ( 1, ' Number of faces = %d\\n', face_num );\n fprintf ( 1, ' Maximum face order = %d\\n', face_order_max );\n\n [ point_coord, face_order, face_point ] = ...\n tetrahedron_shape_3d ( point_num, face_num, face_order_max );\n\n shape_print_3d ( point_num, face_num, face_order_max, ...\n point_coord, face_order, face_point );\n%\n% Compute the area of each face.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Face Order Area\\n' );\n fprintf ( 1, '\\n' );\n\n for face = 1 : face_num\n\n for j = 1 : face_order(face)\n point = face_point(j,face);\n v(1:dim_num,j) = point_coord(1:dim_num,point);\n end\n\n [ area, normal ] = polygon_area_3d ( face_order(face), v );\n\n fprintf ( 1, ' %6d %5d %8f\\n', face, face_order(face), area );\n\n end\n%\n% Find the center of each face.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Face Center\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : face_num\n\n vave(1:dim_num) = 0.0;\n\n for j = 1 : face_order(i)\n k = face_point(j,i);\n vave(1:dim_num) = vave(1:dim_num) + point_coord(1:dim_num,k)';\n end\n\n vave(1:dim_num) = vave(1:dim_num) / face_order(i);\n\n fprintf ( 1, ' %6d %10f %10f %10f\\n', i, vave(1:dim_num) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/geometry_test20325.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7943644212495679}} {"text": "function v = r8vec_house_column ( n, a, k )\n\n%*****************************************************************************80\n%\n%% R8VEC_HOUSE_COLUMN defines a Householder premultiplier that \"packs\" a column.\n%\n% Discussion:\n%\n% The routine returns a vector V that defines a Householder\n% premultiplier matrix H(V) that zeros out the subdiagonal entries of\n% column K of the matrix A.\n%\n% H(V) = I - 2 * v * v'\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% Parameters:\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, real A(N,1), column K of the matrix A.\n%\n% Input, integer K, the column of the matrix to be modified.\n%\n% Output, real V(N,1), a vector of unit L2 norm which defines an\n% orthogonal Householder premultiplier matrix H with the property\n% that the K-th column of H*A is zero below the diagonal.\n%\n\n%\n% Destroy all row vectors!\n%\n a = a(:);\n\n v(1:n,1) = 0.0;\n\n if ( k < 1 || n <= k )\n return\n end\n\n s = sqrt ( sum ( a(k:n,1).^2 ) );\n\n if ( s == 0.0 )\n return\n end\n\n if ( a(k,1) < 0.0 )\n v(k,1) = a(k,1) - abs ( s ) ;\n else\n v(k,1) = a(k,1) + abs ( s );\n end\n v(k+1:n,1) = a(k+1:n,1);\n\n s = sqrt ( sum ( v(k:n,1).^2 ) );\n v(k:n,1) = v(k:n,1) / 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/test_mat/r8vec_house_column.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8670357598021708, "lm_q1q2_score": 0.7942997909088729}} {"text": "function [ pn, dist ] = circle_imp_point_near_2d ( r, center, p )\n\n%*****************************************************************************80\n%\n%% CIRCLE_IMP_POINT_NEAR_2D: nearest ( implicit circle, point ) in 2D.\n%\n% Discussion:\n%\n% This routine finds the distance from a point to an implicitly\n% defined circle, and returns the point on the circle that is\n% nearest to the given point.\n%\n% If the given point is the center of the circle, than any point\n% on the circle is \"the\" nearest.\n%\n% An implicit circle in 2D satisfies the equation:\n%\n% ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 = R**2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2), the center of the circle.\n%\n% Input, real P(2), the point to be checked.\n%\n% Output, real PN(2), the nearest point on the circle.\n%\n% Output, real DIST, the distance of the point to the circle.\n%\n ndim = 2;\n\n if ( p(1:ndim) == center(1:ndim) )\n dist = r;\n pn(1:ndim) = center(1:ndim) + r / sqrt ( ndim );\n return\n end\n\n r2 = sqrt ( sum ( ( p(1:ndim) - center(1:ndim) ).^2 ) );\n\n dist = abs ( r2 - r );\n\n pn(1:ndim) = center(1:ndim) + r * ( p(1:ndim) - center(1:ndim) ) / r2;\n\n return\nend\n", "meta": {"author": "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/circle_imp_point_near_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7942997846138194}} {"text": "%% DEMO of vectorization of elementwise matrix vector multiplication in MATLAB\n% D(i,:,:) is a 3x3 or 2x2 matrix on the i-th element\n% D can be the tensorial diffusion coefficient of a PDE\n% v(i,:) is a 3x1 or 2x1 vector on the i-th element\n% v can be the elementwise gradient of a certain nodal basis, e.g., \n% v(i,:) = Dphi(i,:,k) which is the k-th nodal basis's gradient\n% We want to compute b(i,:) = D(i,:,:)*v(i,:)\n% Even though MATLAB greatly improves the efficiency of for loop after 2016b\n% using built-in vectorization operation is still faster.\n% Depending on your computer the speed up is about 100x to 150x.\n%\n% see also Maxwell\n\n%% set up mesh and gradient matrix\n[node,elem] = cubemesh([0,1,0,1,0,1],1/32);\ncenter = (node(elem(:,1),:) + node(elem(:,2),:) + ...\n node(elem(:,3),:) + node(elem(:,4),:))/4;\nDlambda = gradbasis3(node,elem);\nfprintf('\\nSize of gradient of lambda (%d, %d, %d)\\n', size(Dlambda));\nNT = size(elem,1);\n\n%% set up coefficient matrix (unfortunately arrayfun is not vectorization)\ntic;\nc = @(p) [1+p(:,1).^2/10 p(:,1).*p(:,2) 0.*p(:,1); ...\n p(:,1).*p(:,2) 1+p(:,2).^2/10 0*p(:,2); ...\n 0*p(:,2) 0*p(:,2) 1+p(:,3).^2/10];\ntmp = arrayfun(@(rowidx) c(center(rowidx,:)), 1:size(center,1), 'UniformOutput',0);\nc2elem = cat(3,tmp{:});\nc2elem = permute(c2elem,[3,1,2]); \n% permute switch the element idx to the 1st dim\n% if the Dlambda tensor has D(:,:,j) corresponds to the j-th element\n% then this operation is not neccessary\nfprintf('Time to generate elementwise coefficient matrix %5.4g s\\n',toc);\n\n%% benchmark the elementwise product\ntic;\nb = zeros(NT,3,4);\nfor j = 1:4\n for i = 1:size(elem,1)\n b(i,:,j) = Dlambda(i,:,j)*squeeze(c2elem(i,:,:));\n end\nend\nt1 = toc;\nfprintf('Time to perform elementwise operation %5.4g s\\n',t1);\n\n\n%% benchmark the vectorized routine\ntic;\nb = zeros(NT,3,4);\nfor j = 1:4\n b(:,:,j) = sum(bsxfun(@times, c2elem, Dlambda(:,:,j)), 2);\nend\nt2= toc;\nfprintf('Time to perform vectorized operation %5.4g s\\n',t2);\nfprintf('Speed up factor is %4d.\\n', floor(t1/t2));\n\n%% benchmark the vectorized routine\n% label for K 1 4 6\n% 4 2 5\n% 5 6 3\n\ntic;\nK(:,4) = center(:,1).*center(:,2);\nK(:,3) = 1+center(:,3).^2/10;\nK(:,1) = 1+center(:,1).^2/10;\nK(:,2) = 1+center(:,2).^2/10;\ntoc;\n\ntic;\n% b1 = K1*D1 + K4*D2 + K6*D3\n% b2 = K4*D1 + K2*D2 + K5*D3\n% b3 = K5*D1 + K6*D2 + K3*D3\nb = zeros(NT,3,4);\nfor j = 1:4\n b(:,1,j) = K(:,1).*Dlambda(:,1,j) + K(:,4).*Dlambda(:,3,j);\n b(:,2,j) = K(:,4).*Dlambda(:,1,j) + K(:,2).*Dlambda(:,2,j);\n b(:,3,j) = K(:,3).*Dlambda(:,3,j);\nend\nt3= toc;\nfprintf('Time to perform vectorized operation %5.4g s\\n',t3);\nfprintf('Speed up factor is %4d.\\n', floor(t1/t3));\n\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/polyFEM/demoTensorProd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7942708923809857}} {"text": "function lp = lagrange_derivative ( nd, xd, ni, xi ) \n\n%*****************************************************************************80\n%\n%% LAGRANGE_DERIVATIVE evaluates the derivative of the Lagrange basis polynomials.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 November 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ND, the number of data points.\n%\n% Input, real XD(ND,1), the data nodes.\n%\n% Input, integer NI, the number of evaluation points.\n%\n% Input, real XI(NI,1), the evaluation points.\n%\n% Output, real LP(NI,ND), the value, at the I-th point XI, of the\n% Jth basis function.\n%\n lp = zeros ( ni, nd );\n \n for i = 1 : ni\n for j = 1 : nd\n\n for j1 = 1 : nd\n\n if ( j1 ~= j )\n p = 1.0;\n for j2 = 1 : nd\n if ( j2 == j1 )\n p = p / ( xd(j) - xd(j2) );\n elseif ( j2 ~= j )\n p = p * ( xi(i) - xd(j2) ) / ( xd(j) - xd(j2) );\n end\n end\n lp(i,j) = lp(i,j) + p;\n end\n\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_lagrange/lagrange_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7942708843599218}} {"text": "%%****************************************************************\n%% orthbasis: Compute an orthonomal basis from \n%% the power basis {I,A,A^2, .... ,A^m}\n%% via an Arnoldi-type iteration. \n%%\n%% [Q,H,C] = orthbasis(A,m);\n%% \n%% Output: Q = a cell array containing the orthonormal basis\n%% obtained from {I,A,A^2, .... ,A^m}. \n%%\n%% use in chebymat.m, igmres.m\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 [Q,H,C] = orthbasis(A,m);\n\n N = length(A); \n C(1,1) = 1/sqrt(N); \n Q = cell(1,m+1); \n Q{1} = eye(N)/sqrt(N); \n for k = 1:m\n V = A*Q{k}; \n Vold = V; \n for j = 1:k\n H(j,k) = sum(sum(conj(Q{j}).*V)); \n V = V - H(j,k)*Q{j};\n end; \n if (norm(V,'fro') < norm(Vold,'fro')); \n for j = 1:k\n s(j,1) = sum(sum(conj(Q{j}).*V));\n V = V - s(j)*Q{j}; \n end; \n H(1:k,k) = H(1:k,k) + s; \n end; \n nrm = norm(V,'fro'); \n H(k+1,k) = nrm;\n Q{k+1} = V/nrm; \n C(1:k+1,k+1) = ([0; C(1:k,k)] - [C(1:k,1:k)*H(1:k,k); 0])/nrm; \n end; \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/sdpt3/Examples/orthbasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7942089583847386}} {"text": "function quad = fibonacci_lattice_q1 ( k, f )\n\n%*****************************************************************************80\n%\n%% FIBONACCI_LATTICE_Q1 applies a Fibonacci lattice integration rule in 2D.\n%\n% Discussion:\n%\n% This is a modification of the algorithm in FIBONACCI_LATTICE_Q.\n% It uses a nonlinear transformation on the integrand, which makes\n% the lattice rule more suitable for nonperiodic integrands.\n%\n% The transformation replaces the integration variable X by\n%\n% PHI(X) = 3*X^2 - 2*X**3\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 K, the index of the Fibonacci number to be used.\n% K must be at least 3.\n%\n% Input, external real F, the name of the user-supplied routine\n% which evaluates the function, of the form:\n% function f ( dim_num, x )\n% integer dim_num\n% real f\n% real x(dim_num)\n% f = ...\n%\n% Output, real QUAD, the estimated integral.\n%\n dim_num = 2;\n\n quad = 0.0;\n\n m = fibonacci ( k );\n\n z(1) = 1;\n z(2) = fibonacci ( k - 1 );\n\n for j = 0 : m - 1\n x(1:dim_num) = mod ( j * z(1:dim_num) / m, 1.0 );\n dphi = 1.0;\n for i = 1 : dim_num\n y(i) = ( 3.0 - 2.0 * x(i) ) * x(i) * x(i);\n dphi = dphi * 6.0 * ( 1.0 - x(i) ) * x(i);\n end\n quad = quad + f ( dim_num, y ) * dphi;\n end\n\n quad = quad / 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/lattice_rule/fibonacci_lattice_q1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.794208957939303}} {"text": "classdef DirichletD\n%%DIRICHLETD Functions to handle the Dirichlet distribution.\n%Implemented methods are: mean, cov, PDF, rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n \nfunction val=mean(alph)\n%%MEAN Obtain the mean of the Dirichlet distribution for the given\n% concentration parameters.\n%\n%INPUTS: alph An NX1 vector of positive, real concentration parameters.\n% The length of alpha determines the length of the random\n% vector. If one wishes for the mean of all of the parameters\n% to be equal, then just set alph to all ones.\n%\n%OUTPUTS: val The mean of the Dirichlet distribution under consideration.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=alph/sum(alph);\nend\n\nfunction covMat=cov(alph)\n%%VAR Obtain the covariance matrix of the Dirichlet distribution for the\n% given concentration parameters.\n%\n%INPUTS: alph An NX1 vector of positive, real concentration parameters. The\n% length of alpha determines the length of the random vector.\n% If one wishes for the mean of all of the parameters to be\n% equal, then just set alph to all ones.\n%\n%OUTPUTS: covMat The covariance matrix of the Dirichlet distribution under\n% consideration.\n%\n%Note that since the elements of the Dirichlet random variable must sum to\n%one (i.e. are somewhat dependent), the covariance matrix is singular.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n numVals=length(alph);\n alpha0=sum(alph);\n denom=alpha0^2*(alpha0+1);\n \n %First, fill in the diagonal elements.\n covMat=diag(alph.*(alpha0-alph)/denom);\n \n %Then, fill in the off-diagonal elements.\n for curRow=1:numVals\n for curCol=(curRow+1):numVals\n covMat(curRow,curCol)=-alph(curRow)*alph(curCol)/denom;\n covMat(curCol,curRow)=covMat(curRow,curCol);\n end\n end\nend\n \nfunction val=PDF(X,alph)\n%%PDF Evaluate the PDF of the Dirichlet distribution at a particular vector\n% for the given concentration parameters.\n%\n%INPUTS: X An NX1 dirichlet random variable. Its elements must sum to one.\n% alph An NX1 vector of positive, real concentration parameters. If one\n% wishes for the mean of all of the parameters to be equal, then\n% just set alph to all ones.\n%\n%OUTPUTS: val The value of the Dirichlet distribution at X given alph.\n%\n%The Dirichlet distribution is given in Appendix B of [1].\n%\n%REFERENCES:\n%[1] C. M. Bishop, Pattern Recognition and Machine Learning. Cambridge,\n% United Kingdom: Springer, 2007.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n C=gamma(sum(alph))/prod(gamma(alph));\n val=C*prod(X.^(alph-1));\nend\n\nfunction val=rand(alph)\n%%RAND Generate a Dirichlet random vector with concentration vector\n% parameter vector alpha.\n%\n%INPUTS: alph An NX1 vector of positive, real concentration parameters. The\n% length of alpha determines the length of the random vector\n% generated. If one wishes for the mean of all of the\n% parameters to be equal, then just set alph to all ones.\n%\n%OUTPUTS: val An NX1 Dirichlet random vector.\n%\n%Dirichlet random vectors have elements that sum to one and whose\n%elements are bounded between 0 and 1. Thus, Dirichlet random vectors are\n%useful for generating weights for random mixture distributions.\n%\n%The Dirichlet random vector is generated by transforming a set of gamma\n%distributed random variables. The relationship between the Dirichlet\n%distribution and the gamma distribution is discussed in [1].\n%\n%REFERENCES:\n%[1] B. A. Frigyik, A. Kapila, and M. R. Gupta, \"Introduction to the\n% Dirichlet Distribution and Related processes\", University of\n% Washington Technical Report, No. UWEETR-20-0006, Dec. 2010.\n% https://www.ee.washington.edu/techsite/papers/documents/UWEETR-2010-0006.pdf\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n numVals=length(alph);\n gVals=zeros(numVals,1);\n for curVal=1:numVals\n gVals(curVal)=randGamma(1,alph(curVal),1);\n end\n \n val=gVals/sum(gVals);\nend\n \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/DirichletD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.7942022125387219}} {"text": "function sysdfod=dfod3(n,T,r)\n%\n% sysdfod=dfod3(n,T,r): digital fractional - order differentiator (r > 0)\n% and integrator (r < 0) in form of the IIR filter; \n% Recommended restriction for order r: (-1 < r < 1)\n% Output: =>\n% Discrete system in the form of the IIR filter of the given order 'n'\n% obtained by power series expansion of the trapezoidal (Tustin) rule.\n%\n% Inputs: <=\n% n: order of truncation (min. n = 20 is recommended) --> filter order\n% T: sampling period in [sec]\n% r: approximated fractional order (s^r), r is an arbitrary real number\n%\n% Copyright (c), 2011, Ivo Petras (ivo.petras@tuke.sk)\n%\n% Note: It requires a Matlab Control System Toolbox (->FILT function<-)\n% \n% Example: fractional half order integrator for T=0.1 sec and n = 20 :\n% >> FHOI=dfod3(20, 0.1, -0.5); bode(FHOI); figure; step(FHOI);\n\nbcN(1)=1.0; bcD(1)=1.0;\nfor i=1:n\n bcN(i+1)=((-1)^i)*(gamma(abs(r)+1)./(gamma(i+1).*gamma(abs(r)-i+1))); \n bcD(i+1)=gamma(abs(r)+1)./(gamma(i+1).*gamma(abs(r)-i+1));\nend\nif r>=0\n sysdfod=((2/T)^r)*(filt(bcN,bcD,T));\nend\nif r<0\n sysdfod=((2/T)^r)*(filt(bcD,bcN,T));\nend\n%", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31358-digital-fractional-order-differentiator-and-integrator-new-iir-type/dfod3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7941469077758448}} {"text": "%% Examples of Numerical Solutions of PDEs\n% We shall use a sequence of examples to introduce basic components of\n% numerical solutions of PDEs.\n\n%% Smooth solutions on regular domains\n% We solve the Poisson equation $-\\Delta u =1$ in the unit square $\\Omega =\n% (0,1)\\times (0,1)$ with homogenous Dirichlet boundary condition\n% $u|_{\\partial \\Omega}=0$ using linear finite element discrization on a\n% sequence of uniform and structured grids.\n\nclose all; clear all\nfigure(1); set(gcf,'Units','normal'); set(gcf,'Position',[0,0,0.45,0.3]);\nnode = [0,0; 1,0; 1,1; 0,1]; % nodes\nelem = [2,3,1; 4,1,3]; % elements\nsubplot(1,3,1); showmesh(node,elem)\n[node,elem] = uniformrefine(node,elem);\nsubplot(1,3,2); showmesh(node,elem)\n[node,elem] = uniformrefine(node,elem);\nsubplot(1,3,3); showmesh(node,elem)\n\n%%\nsquarePoisson\n% See squarePoisson for details of computation.\n\n%% Smooth solutions on irregular domains\n% We solve the Poisson equation in a Lake-type domain. This example shows\n% the flexibility of FEM to complex domains.\n\nload lakemesh\nf = inline('ones(size(x,1),1)'); % right hand side\ng_D = inline('zeros(size(x,1),1)'); % Dirichlet boundary condition\nu = Poisson(node,elem,[],f,g_D,[]); % Poisson equation\n% graphic\nfigure(1); set(gcf,'Units','normal'); set(gcf,'Position',[0,0,0.45,0.3]);\nsubplot(1,2,1); showmesh(node,elem); pause(0.05)\nsubplot(1,2,2); showsolution(node,elem,u,[0,90]);axis equal; colorbar;\n\n%% Tutorial of iFEM \n\n%% Features of iFEM\n% \n% * Simple data structures\n% * Mesh adaptation in two- and three-dimensions\n% * Fast solvers of algebraic equations\n% * Easy to use, Easy to code, Easy to debug\n% * Efficient programming\n\n%% Basic Data Stucture\n%\n% *Mesh: node and elem.* \n%\n% Two matrices |node(1:N,1:d)| and |elem(1:NT,1:d+1)| are used to represent\n% a d-dimensional triangulation embedded in $R^d$, where |N| is the number\n% of vertices and |NT| is the number of elements. \n% \n% |node(k,1)| and |node(k,2)| are the x- and y-coordinates of the k-th node\n% for points in 2-D. In 3-D, |node(k,3)| gives the additional z-coordinates\n% of the k-th node.\n%\n% |elem(t,1:d+1)| are the global indices of |d+1| vertices which form the\n% abstract $d$-simplex |t|. By convention, the vertices of a simplex is ordered\n% such that the signed volume is positive. Therefore in 2-D, three vertices\n% of a triangle is ordered counterclockwise and in 3-D, the ordering of\n% vertices follows the right-hand rule.\n% \n% Related functions: ,\n% , \n%\n% Documentation: \n\nclear all; close all;\n\n%%\n% *Example: L-shape domain in 2-D.*\n\nnode = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; \nelem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; \nfigure(1)\nshowmesh(node,elem)\naxis on\nfindnode(node)\nfindelem(node,elem)\n\n%%\n% *Example: Cube in 3-D.*\n\nnode = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \nelem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];\nfigure(2)\nshowmesh3(node,elem,[],'FaceAlpha',0.25);\nview([-53,8]);\naxis on\nfindnode3(node)\nfindelem3(node,elem)\n\n%%\n% *Boundary: bdEdge or bdFace.* \n%\n% For 2-D triangulations, we use |bdEdge(1:NT,1:3)| to record the type of\n% three edges of each element. Similarly in 3-D, we use |bdFace(1:NT,1:4)|\n% to record the type of four faces of each element. \n% The value is the type of boundary condition listed as follows.\n%\n% * 0: non-boundary, i.e., an interior edge or face.\n% * 1: first type, i.e., a Dirichlet boundary edge or face. \n% * 2: second type, i.e., a Neumann boundary edge or face. \n% * 3: third type, i.e., a Robin boundary edge or face.\n%\n% We label three edges of a triangle such that |bdEdge(t,i)| is the edge\n% opposite to the i-th vertex. Similarly |bdFace(t,i)| is the face opposite\n% to the i-th vertex.\n%\n% Related functions: ,\n% , \n% .\n%\n% Documentation: \n\nnode = [1,0; 1,1; 0,0];\nelem = [1 2 3];\nedge = [2 3; 1 3; 1 2];\nsubplot(1,2,1);\nshowmesh(node,elem);\nfindedge(node,edge);\nfindnode(node);\nnode = [1,1,1; 0,0,0; 1,1,0; 1,0,0];\nelem = [1,2,3,4];\nsubplot(1,2,2);\nshowmesh3(node,elem,[],'FaceAlpha',0.35); view([-10,18]);\nfindnode3(node);\nfindelem3(node,[2,3,4; 1,3,4; 1,2,4; 1,2,3])\n\n%% Finite Element Method\n%\n%\n%% \n% * Example 1: The Poisson equation in 2-D\n% * Example 2: The Poisson equation: complex domains\n% * Example 2: The Poisson equation in 3-D with multigrid solvers\n\n%% Adaptive Finite Element Method\n%\n%\n%% \n% * Example 1: The Poisson equation on a 2-D L-shaped domain\n% * Example 2: The Poisson equation in 3-D with jump diffusion coefficients\n\n%% Time-dependent Problems\n%% \n% * Example 1: Heat equation\n% * Example 2: Moving interface\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/doc/temp/examples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8902942232112239, "lm_q1q2_score": 0.7939742270693447}} {"text": "function [node,elem] = cubehexmesh(cube,h)\n%% CUBEHEXMESH uniform mesh of cube\n%\n% [node,elem] = cubehexmesh([x0,x1,y0,y1,z0,z1],h) generates a uniform\n% cubic mesh of the cube [x0,x1]*[y0,y1]*[z0,z1] with mesh size h.\n%\n% Example\n% [node,elem] = cubehexmesh([0 1 0 2 0 3],0.5);\n%\n% See also: squarequadmesh, cubehexgradmesh\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nx0 = cube(1); x1 = cube(2); \ny0 = cube(3); y1 = cube(4);\nz0 = cube(5); z1 = cube(6);\n[z,x,y] = ndgrid(z0:h:z1,x0:h:x1,y0:h:y1);\nnode = [x(:),y(:),z(:)];\n% findnode3(node); view([83 10]);\n\n%% Generate elements\nni = size(x,1); % number of rows\nnj = size(x,2); % number of columns\nnk = size(x,3); % number of pages\nnij = ni*nj; % number of elements in one page\nN = size(node,1);\nnodeidx = reshape(1:N,ni,nj,nk);\nt2nidxMap = nodeidx(1:ni-1,1:nj-1,1:nk-1);\ns = t2nidxMap(:);\nelem = [s s+ni s+ni+nij s+nij s+1 s+ni+1 s+ni+nij+1 s+nij+1]; \n% s+1 s+ni*nj\n% | /\n% s - s + ni ", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/mesh/cubehexmesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.793826645840823}} {"text": "function K = curvature_2D(X,Y,degree)\n% CURVATURE_2D estimate curvature of a curve defined by points\n%\n% K = CURVATURE_2D(X, Y, DEGREE)\n%\n% DEGREE is the degree of the polynom used for the interpolation\n%\n\n%\n% Created by Alexandre Gramfort on 2008-12-15.\n% Copyright (c) 2007 Alexandre Gramfort. All rights reserved.\n%\n\n% $Id: curvature_2D.m 2 2009-06-16 19:24:10Z gramfort $\n% $LastChangedBy: gramfort $\n% $LastChangedDate: 2009-06-16 15:24:10 -0400 (Mar, 16 jui 2009) $\n% $Revision: 2 $\n\nif nargin<3\n % default values\n degree = 5; % degree of polynum used for interpolation\nend\n\n% Find a parametrization of the curve\nt = cumsum(sqrt(diff(X).^2 + diff(Y).^2));\nt = [0,t];\nt = t / t(end); % normalize between 0 and 1\n\n% compute coefficients of interpolation functions\nx0 = polyfit(t, X, degree);\ny0 = polyfit(t, Y, degree);\n\n% compute coefficients of first and second derivatives. In the case of a\n% polynom, it is possible to compute coefficient of derivative by\n% multiplying with a matrix.\nderive = diag(degree:-1:0);\nxp = circshift(x0*derive, [0 1]);\nyp = circshift(y0*derive, [0 1]);\nxs = circshift(xp*derive, [0 1]);\nys = circshift(yp*derive, [0 1]);\n\n% compute values of first and second derivatives for needed points \nxprime = polyval(xp, t);\nyprime = polyval(yp, t);\nxsec = polyval(xs, t);\nysec = polyval(ys, t);\n\n% compute value of curvature\nK = (xprime.*ysec - xsec.*yprime)./ ...\n power(xprime.*xprime + yprime.*yprime, 3/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/lagextraction/private/curvature_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159725, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7938266411859031}} {"text": "% Return the total number of edges given the adjacency matrix\n% INPUTs: adjacency matrix, nxn\n% OUTPUTs: m - total number of edges/links\n%\n% Note: Valid for both directed and undirected, simple or general graph\n% Other routines used: selfLoops.m, isSymmetric.m\n% GB, last updated Sep 19, 2012\n\nfunction m = numEdges(adj)\n\nsl=selfLoops(adj); % counting the number of self-loops\n\nif isSymmetric(adj) && sl==0 % undirected simple graph\n m=sum(sum(adj))/2;\n \nelseif isSymmetric(adj) && sl>0\n m=(sum(sum(adj))-sl)/2+sl; % counting the self-loops only once\n\nelseif not(isSymmetric(adj)) % directed graph (not necessarily simple)\n m=sum(sum(adj));\n \nend", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/numEdges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8688267643505194, "lm_q1q2_score": 0.7938266256695027}} {"text": "%% Example A.1: Linear Advection in a Periodic Domain\n% \n% The linear advection problem with periodic boundary conditions\n%\n% $$u_t + u_x = 0, \\qquad u(x,0)=u_0(x), \\qquad u(0,t)=u(1,t)$$\n%\n% is well suited for studying error mechanisms in numerical schemes for\n% hyperbolic conservation laws. In particular, to study dissipative and\n% oscillatory errors, we will use initial data consisting of a combination\n% of a smooth, squared cosine wave and double step function.\n\n%%\n% We consider two first-order methods (Lax-Friedrichs and the upwind\n% method) and two second-order methods (Lax-Wendroff and MacCormack)\nT = 10;\nN = 100; h=1/N; x=h*(1:N);\nu0 = (abs(x-.25)<=0.15).*(cos(pi*(10/3)*(x-0.25))).^2 + ...\n 1.0*(abs(x-0.75)<0.15);\nxx = linspace(0,1,1001);\nuf = (abs(xx-.25)<=0.15).*(cos(pi*(10/3)*(xx-0.25))).^2 + ...\n 1.0*(abs(xx-0.75)<0.15);\n\nmethod = {'LxF', 'upwind', 'LxW', 'McC'};\nname = {'Lax-Friedrichs', 'Upwind', 'Lax-Wendroff', 'MacCormack'};\nfor i=1:4\n u=finvol('linearfunc',u0,T,h,1,'periodic',method{i},.9);\n subplot(2,2,i);\n plot(xx,uf,'-',x,u,'o','MarkerSize',2); axis([0 1 -0.2 1.3]);\n title(name{i});\nend\n%%\n% We see that the two first-order schemes smear both the smooth part and\n% the discontinuous path of the advected profile and that the\n% Lax-Friedrichs method is more diffusive than the upwind method. The\n% second-order schemes, on the other hand, preserve the smooth profile\n% quite accurately, but introduce spurious oscillations around the two\n% discontinuities.", "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/demoA_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.7937484119775303}} {"text": "function v = r8vec_house_column ( n, a, k )\n\n%*****************************************************************************80\n%\n%% R8VEC_HOUSE_COLUMN defines a Householder premultiplier that \"packs\" a column.\n%\n% Discussion:\n%\n% The routine returns a vector V that defines a Householder\n% premultiplier matrix H(V) that zeros out the subdiagonal entries of\n% column K of the matrix A.\n%\n% H(V) = I - 2 * v * v'\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, real A(N), column K of the matrix A.\n%\n% Input, integer K, the column of the matrix to be modified.\n%\n% Output, real V(N), a vector of unit L2 norm which defines an\n% orthogonal Householder premultiplier matrix H with the property\n% that the K-th column of H*A is zero below the diagonal.\n%\n v(1:n) = 0.0;\n\n if ( k < 1 | n <= k )\n return\n end\n\n s = sqrt ( sum ( a(k:n).^2 ) );\n\n if ( s == 0.0 )\n return\n end\n\n v(k) = a(k) + abs ( s ) * r8_sign ( a(k) );\n v(k+1:n) = a(k+1:n);\n\n v(k:n) = v(k:n) / sqrt ( v(k: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/test_eigen/r8vec_house_column.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7936849401946793}} {"text": "function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)\n%GRADIENTDESCENTMULTI Performs gradient descent to learn theta\n% theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by\n% taking num_iters gradient steps with learning rate alpha\n\n% Initialize some useful values\nm = length(y); % number of training examples\nJ_history = zeros(num_iters, 1);\n\nfor iter = 1:num_iters\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCostMulti) and gradient here.\n %\n\n predictions = X * theta;\n updates = X' * (predictions - y);\n theta = theta - alpha * (1/m) * updates;\n\n\n\n % ============================================================\n\n % Save the cost J in every iteration \n J_history(iter) = computeCostMulti(X, y, theta);\n\nend\n\nend\n", "meta": {"author": "vkosuri", "repo": "CourseraMachineLearning", "sha": "b11d4152c323a084fa3bc942e108ed456b77cbd3", "save_path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning", "path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning/CourseraMachineLearning-b11d4152c323a084fa3bc942e108ed456b77cbd3/home/week-2/exercises/machine-learning-ex1/ex1/gradientDescentMulti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632856092014, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7936849384632553}} {"text": "%book : Signals and Systems Laboratory with MATLAB \n%by Alex Palamides & Anastasia Veloni\n\n% Fourier Series properties \n\n\n%time shifting \n\nt0=0;\nT=10;\nw=2*pi/T;\nsyms t\nx=t*exp(-5*t) \nk=-5:5;\na=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T);\na1=eval(a);\nsubplot(211);\nstem(k,abs(a1));\ntitle(' Coefficients of x(t)=te^-^5^t');\nlegend('Magnitude');\nsubplot(212);\nstem(k,angle(a1));\nlegend('Angle');\n\nfigure\nt1=3;\nright= exp(-j*k*w*t1).*a;\nright =eval(right);\nsubplot(211);\nstem(k,abs(right));\nlegend('Magnitude');\ntitle('Right part');\nsubplot(212);\nstem(k,angle(right));\nlegend('Angle');\n\nfigure\nx=(t-t1).*exp(-5*(t-t1));\na=(1/T)*int(x*exp(-j*k*w*t),t,t0+t1,t0+T+t1);\ncoe=eval(a);\nsubplot(211);\nstem(k,abs(coe));\nlegend('Magnitude');\ntitle(' Coefficient of (t-3)exp(-5(t-3)) ');\nsubplot(212);\nstem(k,angle(coe));\nlegend('Angle');\n", "meta": {"author": "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/5/c59b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.7936849351334084}} {"text": "function y=PSNR(noisyImage,restoredImage)\n \n% Compute the PSNR of two gray scale image\n% Traditional progarmming using loops \n% Class input : [0,1] \n% july, 25 , 2012\n% KHMOU Youssef\n \nN=size(noisyImage);\nif length(N)> 2\n error('Input must be grayscale image');\nend\nif size(noisyImage)~=size(restoredImage)\n error('The images must have the same size');\nend\n \n%if ~isa(noisyImage,'double') \n% noisyImage=double(noisyImage)./255.00;\n%end\n%if ~isa(restoredImage,'double')\n% restoredImage=double(restoredImage)./255.00;\n%end\n \n% begin\n \nd1=max(noisyImage(:));\nd2=max(restoredImage(:));\nd=max(d1,d2);\n\nMSE=0;\nfor i=1:N(1)\n for j=1:N(2)\n if isnan(noisyImage(i,j)) || isinf(restoredImage(i,j))...\n || isnan(restoredImage(i,j)) || isinf(noisyImage(i,j))\n continue;\n end\n MSE=MSE+((abs(noisyImage(i,j)-restoredImage(i,j))).^2);\n end\nend\n \nMSE=MSE./(N(1)*N(2));\n \ny=10*log10((d.^2) /MSE)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37691-psnr-for-rgb-images/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7936723476658148}} {"text": "function [x,y] = EquiNodes2D(N);\n\n% function [x,y] = EquiNodes2D(N);\n% Purpose : Compute (x,y) nodes in equilateral triangle for polynomial of order N\n\n% total number of nodes\nNp = (N+1)*(N+2)/2;\n\n% Create equidistributed nodes on equilateral triangle\nL1 = zeros(Np,1); L2 = zeros(Np,1); L3 = zeros(Np,1);\nsk = 1;\nfor n=1:N+1\n for m=1:N+2-n\n L1(sk) = (n-1)/N; L3(sk) = (m-1)/N;\n sk = sk+1;\n end\nend\nL2 = 1.0-L1-L3;\n\nx = -L2+L3; y = (-L2-L3+2*L1)/sqrt(3.0);\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/EquiNodes2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.793661015769458}} {"text": "function value = r4_atanh ( x )\n\n%*****************************************************************************80\n%\n%% R4_ATANH evaluates the arc-hyperbolic tangent of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the arc-hyperbolic tangent of X.\n%\n persistent atnhcs;\n persistent dxrel;\n persistent nterms;\n persistent sqeps;\n\n if ( isempty ( nterms ) )\n atnhcs = [ ...\n 0.094395102393195492E+00;\n 0.049198437055786159E+00;\n 0.002102593522455432E+00;\n 0.000107355444977611E+00;\n 0.000005978267249293E+00;\n 0.000000350506203088E+00;\n 0.000000021263743437E+00;\n 0.000000001321694535E+00;\n 0.000000000083658755E+00;\n 0.000000000005370503E+00;\n 0.000000000000348665E+00;\n 0.000000000000022845E+00;\n 0.000000000000001508E+00;\n 0.000000000000000100E+00;\n 0.000000000000000006E+00 ];\n nterms = r4_inits ( atnhcs, 15, 0.1 * r4_mach ( 3 ) );\n dxrel = sqrt ( r4_mach ( 4 ) );\n sqeps = sqrt ( 3.0 * r4_mach ( 3 ) );\n end\n\n y = abs ( x );\n\n if ( y <= sqeps )\n value = x;\n elseif ( y <= 0.5 )\n value = x * ( 1.0 ...\n + r4_csevl ( 8.0 * x * x - 1.0, atnhcs, nterms ) );\n elseif ( y < 1.0 )\n value = 0.5 * log ( ( 1.0 + x ) / ( 1.0 - x ) );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_ATANH - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= |X|.\\n' );\n error ( 'R4_ATANH - Fatal error!' )\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_atanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.85776809953619, "lm_q1q2_score": 0.7936327419287886}} {"text": "function halton_dataset ( )\n\n%*****************************************************************************80\n%\n%% HALTON_DATASET generates a Halton dataset and writes it to a file.\n%\n% Discussion:\n%\n% This program is meant to be used interactively. It's also\n% possible to prepare a simple input file beforehand and use it\n% in batch mode.\n%\n% The program requests input values from the user:\n%\n% * NDIM, the spatial dimension,\n% * N, the number of points to generate,\n% * STEP, the index of the first subsequence element to be computed.\n% * SEED(1:NDIM), the Halton sequence index corresponding\n% to STEP = 0.\n% * LEAP(1:NDIM), the successive jumps in the Halton sequence.\n% * BASE(1:NDIM), the Halton bases (usually distinct primes).\n%\n% The program generates the data, writes it to the file\n%\n% halton_NDIM_N.txt\n%\n% where \"NDIM\" and \"N\" are the numeric values specified by the user,\n% and then asks the user for more input. To indicate that no further\n% computations are desired, it is enough to input a nonsensical\n% value, such as -1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Generate a Halton dataset.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This program is meant to be used interactively.\\n' );\n fprintf ( 1, ' It is also possible to prepare a simple input \\n' );\n fprintf ( 1, ' file beforehand and use it in batch mode.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program requests input values from the user:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * NDIM, the spatial dimension,\\n' );\n fprintf ( 1, ' * N, the number of points to generate,\\n' );\n fprintf ( 1, ' * STEP, the index of the first subsequence element.\\n' );\n fprintf ( 1, ' * SEED(1:NDIM), the Halton sequence element\\n' );\n fprintf ( 1, ' corresponding to STEP = 0\\n' );\n fprintf ( 1, ' * LEAP(1:NDIM), the successive jumps in the\\n' );\n fprintf ( 1, ' Halton sequence.\\n' );\n fprintf ( 1, ' * BASE(1:M), the Halton bases,\\n' );\n fprintf ( 1, ' usually distinct primes.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program generates the data, writes it to the file\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' halton_NDIM_N.txt\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' where \"NDIM\" and \"N\" are the numeric values specified\\n' );\n fprintf ( 1, ' by the user, and then asks the user for more input.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' To indicate that no further computations are \\n' );\n fprintf ( 1, ' desired, it is enough to input a nonsensical value, \\n' );\n fprintf ( 1, ' such as -1.\\n' );\n\n while ( 1 )\n\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '* Ready to generate a new dataset:\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NDIM is the spatial dimension.\\n' );\n fprintf ( 1, ' (Try ''2'' if you have no preference.)\\n' );\n fprintf ( 1, ' Any value less than 1 terminates execution.\\n' );\n ndim = input ( ' Enter NDIM: ' );\n\n fprintf ( 1, ' User input NDIM = %d\\n', ndim );\n\n if ( ~halham_ndim_check ( ndim ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The input value of NDIM = %d\\n', ndim );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N is the number of points.\\n' );\n fprintf ( 1, ' (Try ''25'' if you have no preference.)\\n' );\n fprintf ( 1, ' Any value less than 1 terminates execution.\\n' );\n n = input ( ' Enter N: ' );\n\n fprintf ( 1, ' User input N = %d\\n', n );\n\n if ( ~halham_n_check ( n ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The input value of N = %d\\n', n );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP is the index of the first subsequence element.\\n' );\n fprintf ( 1, ' (Try ''0'' or ''1'' if you have no preference.)\\n' );\n fprintf ( 1, ' Any value less than 0 terminates execution.\\n' );\n step = input ( ' Enter STEP: ' );\n\n fprintf ( 1, ' User input STEP = %d\\n', step );\n\n if ( ~halham_step_check ( step ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The input value of STEP = %d\\n', step );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SEED(1:NDIM) is the starting element index\\n' );\n fprintf ( 1, ' for each coordinate.\\n' );\n fprintf ( 1, ' (Try ''[0,0,...,0]'' if you have no preference.)\\n' );\n fprintf ( 1, ' (Any value less than 0 terminates execution.)\\n' );\n seed = [];\n seed(1:ndim) = input ( ' Enter SEED(1:NDIM): ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, seed, 'SEED:' );\n\n if ( ~halham_seed_check ( ndim, seed ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The negative input value of at least one entry of\\n' );\n fprintf ( 1, ' SEED is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEAP(1:NDIM) is the leaping multiplier\\n' );\n fprintf ( 1, ' for each coordinate.\\n' );\n fprintf ( 1, ' (Try ''[1,1,...,1]'' if you have no preference.)\\n' );\n fprintf ( 1, ' (Another choice is a prime bigger than all the bases.)\\n' );\n fprintf ( 1, ' (Any value less than 1 terminates execution.)\\n' );\n leap = [];\n leap(1:ndim) = input ( ' Enter LEAP(1:NDIM): ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, leap, 'LEAP:' );\n\n if ( ~halham_leap_check ( ndim, leap ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The input value of at least one entry of\\n' );\n fprintf ( 1, ' LEAP is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BASE(1:NDIM) is the base for each coordinate,\\n' );\n fprintf ( 1, ' usually distinct primes.\\n' );\n fprintf ( 1, ' (Try ''[2,3,5,7,11,13,...]'' if you have no preference.)\\n' );\n fprintf ( 1, ' (Any value less than 2 terminates execution.)\\n' );\n base = [];\n base(1:ndim) = input ( ' Enter BASE: ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, base, 'BASE:' );\n\n if ( ~halton_base_check ( ndim, base ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALTON_DATASET\\n' );\n fprintf ( 1, ' The input value of at least one entry of\\n' );\n fprintf ( 1, ' BASE is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n r = i4_to_halton_sequence ( ndim, n, step, seed, leap, base );\n\n file_out_name = ...\n strcat ( 'halton_', num2str ( ndim ), '_', num2str ( n ), '.txt' );\n\n halham_write ( ndim, n, step, seed, leap, base, r, file_out_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data was written to the file \"%s\".\\n', ...\n file_out_name );\n\n end\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/halton_dataset/halton_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8976953023710936, "lm_q1q2_score": 0.7935979158201176}} {"text": "function turn = angle_turn_2d ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% ANGLE_TURN_2D computes a turning angle in 2D.\n%\n% Discussion:\n%\n% This routine is most useful when considering the vertices of a\n% polygonal shape. We wish to distinguish between angles that \"turn\n% in\" to the shape, (between 0 and 180 degrees) and angles that\n% \"turn out\" (between 180 and 360 degrees), as we traverse the boundary.\n%\n% If we compute the interior angle and subtract 180 degrees, we get the\n% supplementary angle, which has the nice property that it is\n% negative for \"in\" angles and positive for \"out\" angles, and is zero if\n% the three points actually lie along a line.\n%\n% Assuming P1, P2 and P3 define an angle, the TURN can be\n% defined to be either:\n%\n% * the supplementary angle to the angle formed by P1=P2=P3, or\n%\n% * the angle between the vector ( P3-P2) and the vector -(P1-P2),\n% where -(P1-P2) can be understood as the vector that continues\n% through P2 from the direction P1.\n%\n% The turning will be zero if P1, P2 and P3 lie along a straight line.\n%\n% It will be a positive angle if the turn from the previous direction\n% is counterclockwise, and negative if it is clockwise.\n%\n% The turn is given in radians, and will lie between -PI and PI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2), P2(2), P3(2), the points that form\n% the angle.\n%\n% Output, real TURN, the turn angle, between -PI and PI.\n%\n p(1) = ( p3(1) - p2(1) ) * ( p1(1) - p2(1) ) ...\n + ( p3(2) - p2(2) ) * ( p1(2) - p2(2) );\n\n p(2) = ( p3(1) - p2(1) ) * ( p1(2) - p2(2) ) ...\n - ( p3(2) - p2(2) ) * ( p1(1) - p2(1) );\n\n if ( p(1) == 0.0 & p(2) == 0.0 )\n turn = 0.0;\n else\n turn = pi - r8_atan ( p(2), p(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/geometry/angle_turn_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7935978943255086}} {"text": "function area = polygon_area_3d_2 ( n, v, area )\n\n%*****************************************************************************80\n%\n%% POLYGON_AREA_3D_2 computes the area of a polygon in 3D.\n%\n% Discussion:\n%\n% The computation is not valid unless the vertices of the polygon\n% lie in a plane, so that the polygon that is defined is \"flat\".\n%\n% The polygon does not have to be \"regular\", that is, neither its\n% sides nor its angles need to be equal.\n%\n% The area is computed as the sum of the areas of the triangles \n% formed by the last node with consecutive pairs of nodes (1,2),\n% (2,3), ..., and (N-2,N-1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n%\n% Input, real V(3,N), the coordinates of the vertices.\n%\n% Output, real AREA, the area of the polygon.\n%\n area_vector(1:3) = 0.0;\n\n for i = 1 : n - 2\n\n t(1:3,1:3) = [ v(1:3,i)'; v(1:3,i+1)'; v(1:3,n)' ]';\n\n area_vector_triangle = triangle_area_vector_3d ( t );\n\n area_vector(1:3) = area_vector(1:3) + area_vector_triangle(1:3);\n\n end\n\n area = 0.5 * sqrt ( sum ( area_vector(1:3).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_area_3d_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.793562101233618}} {"text": "function rotated=uniform_rotation_3D(v)\n% This function perform a unformly random rotation 3D.\n% It is clear that in 2 dimensions that this means the \n% rotation angle is uniformly distributed between (0, 2pi).\n% However, it is NOT correct and does NOT carry over to \n% higher dimensions. \n%\n% More information see Le?n, Carlos A.; Mass?, Jean-Claude; \n% Rivest, Louis-Paul (February 2006), \"A statistical model \n% for random rotations\", Journal of Multivariate Analysis 97 \n% (2): 412?430, doi:10.1016/j.jmva.2005.03.009, ISSN 0047-259X\n\n% Arguments (input):\n% v - 3*1 vector needs to be rotated\n%\n%\n% arguments (output):\n% rotated - 3*1 vector after unformly random rotation\n%\n% \n% References: J. Arvo (1992), Fast Random Rotation Matrices\n%\n% Author: Yaming Wang. ETH Zurich.\n% email: yaming.wang@sed.ethz.ch\n% Release: 1.00\n% Release data: 18.09.2012\n\nrot_1=2*pi*rand(1);\nmatrix_1=[cos(rot_1),sin(rot_1),0;...\n -sin(rot_1),cos(rot_1),0;...\n 0,0,1];\n\nrot_2a=2*pi*rand(1);\nrot_2b=rand(1);\n\nHouseholder_v=[cos(rot_2a)*sqrt(rot_2b)\n sin(rot_2a)*sqrt(rot_2b)\n sqrt(1-rot_2b)];\n\n% Householder matrix\nmatrix_2=eye(3)-2*Householder_v*Householder_v';\n\nrotated=-matrix_2*matrix_1*v;\n\nfprintf(1,'rotation finished.\\n');\n\n\n% ====================================================\n% end of function\n% ====================================================", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43550-uniformrotation3d/uniform_rotation_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381048137938, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7935452749637473}} {"text": "\n% LegendrePoly.m by David Terr, Raytheon, 5-10-04\n\n% Given nonnegative integer n, compute the \n% Legendre polynomial P_n. Return the result as a vector whose mth\n% element is the coefficient of x^(n+1-m).\n% polyval(LegendrePoly(n),x) evaluates P_n(x).\n\n\nfunction pk = LegendrePoly(n)\n\nif n==0 \n pk = 1;\nelseif n==1\n pk = [1 0]';\nelse\n \n pkm2 = zeros(n+1,1);\n pkm2(n+1) = 1;\n pkm1 = zeros(n+1,1);\n pkm1(n) = 1;\n\n for k=2:n\n \n pk = zeros(n+1,1);\n\n for e=n-k+1:2:n\n pk(e) = (2*k-1)*pkm1(e+1) + (1-k)*pkm2(e);\n end\n \n pk(n+1) = pk(n+1) + (1-k)*pkm2(n+1);\n pk = pk/k;\n \n if k 500, Very Good!\n% cvx_solver('Gurobi');\n\nhRunTime = tic();\n\ncvx_begin('quiet')\n% cvx_begin()\n % cvx_precision('best');\n variable vX(numCols, 1);\n minimize( 0.5 * sum_square(mA * vX - vB) + (0.5 * paramLambda * square_pos(norm(vX))) );\n subject to\n vX >= 0;\ncvx_end\n\nrunTime = toc(hRunTime);\n\n% vX = mX(:);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The ', solverString, ' Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\nsCvxSol.vXCvx = vX;\nsCvxSol.cvxOptVal = hObjFun(vX);\n\n\n%% Solution by Projected Gradient Descent\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Method'];\n\nhRunTime = tic();\n\n[vX, mX] = ProjectedGd(zeros(numCols, 1), hG, hP, numIterations, stepSizeGd);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with Momentum\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with Momentum'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdMomentum(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd, stepSizeMomentum);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with Nesterov Acceleration\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with Nesterov Acceleration'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdAccel(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd, stepSizeAccel);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with FISTA\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with FISTA Acceleration'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdFista(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd);\n% [vX, mX] = SolveLsFista(zeros(numCols, 1), mA, vB, paramLambda, numIterations, stepSizeGd);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Display Results\n\nfigureIdx = figureIdx + 1;\n\nhFigure = figure('Position', figPosLarge);\n\nhAxes = subplot(2, 1, 1);\nhLineSeries = plot(1:numIterations, 10 * log10(mObjFunValMse));\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nset(get(hAxes, 'Title'), 'String', ['Objective Function Value vs. Optimal Value (CVX)'], ...\n 'FontSize', fontSizeTitle);\nset(get(hAxes, 'XLabel'), 'String', 'Iteration Number', ...\n 'FontSize', fontSizeAxis);\nset(get(hAxes, 'YLabel'), 'String', '$ 10 \\log_{10} {\\left( \\left| f \\left( x \\right) - f \\left( {x}_{CVX} \\right) \\right| \\right)}^{2} $', ...\n 'FontSize', fontSizeAxis, 'Interpreter', 'latex');\nset(hAxes, 'XLim', [1, numIterations]);\nhLegend = ClickableLegend(cLegendString);\n\nhAxes = subplot(2, 1, 2);\nhLineSeries = plot(1:numIterations, 10 * log10(mSolMse));\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nset(get(hAxes, 'Title'), 'String', ['Solution Error Norm'], ...\n 'FontSize', fontSizeTitle);\nset(get(hAxes, 'XLabel'), 'String', 'Iteration Number', ...\n 'FontSize', fontSizeAxis);\nset(get(hAxes, 'YLabel'), 'String', '$ 10 \\log_{10} \\left( {\\left\\| x - {x}_{CVX} \\right\\|}_{2}^{2} \\right) $', ...\n 'FontSize', fontSizeAxis, 'Interpreter', 'latex');\nset(hAxes, 'XLim', [1, numIterations]);\nhLegend = ClickableLegend(cLegendString);\n\nif(generateFigures == ON)\n % saveas(hFigure,['Figure', num2str(figureIdx, figureCounterSpec), '.png']);\n print(hFigure, ['Figure', num2str(figureIdx, figureCounterSpec), '.png'], '-dpng', '-r0'); % 0\n if size(elec_labels,1) > size(elec_labels,2)\n elec_labels = cellstr(strcat(num2str(elec_labels)));\n else\n elec_labels = cellstr(strcat(num2str(elec_labels')));\n end\n end\n \n A = [ (X-xo) (Y-yo) (Z-zo) ]; B = A; % define electrode vectors A,B, given centroid (xo,yo,zo)\n rows = 50; % progress indicator\n for a = 1:length(X)\n fprintf('.'); if( a == rows ) fprintf('\\n'); rows = rows + 50; end % progress indicator\n \n Aa = A(a,:);\n A_len = sqrt( sum( Aa.^2 ) ); % length of electrode vector A\n \n for b = 1:length(X)\n \n Bb = B(b,:);\n B_len = sqrt ( sum(Bb.^2) ); % length of electrode vector B\n \n if( Aa == Bb )\n arc_len = 0; % no distance from electrode to itself\n else\n r = (A_len + B_len)/2; % estimate sphere radius from A_len and B_len\n theta = acos( dot(Aa,Bb) / (A_len * B_len) ); % Angle between A & B, in radians\n arc_len = r * theta; % arc length = radius * theta\n end\n \n distances(a, b) = arc_len;\n labels(a, b) = strcat(elec_labels(a), ', ', elec_labels(b));\n end\n end\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/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/elec_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7933892824714142}} {"text": "function breadth = polyhedronMeanBreadth(vertices, edges, faces)\n%POLYHEDRONMEANBREADTH Mean breadth of a convex polyhedron\n%\n% BREADTH = polyhedronMeanBreadth(V, E, F)\n% Return the mean breadth (average of polyhedron caliper diameter over\n% all direction) of a convex polyhedron.\n%\n% The mean breadth is computed using the sum, over the edges of the\n% polyhedron, of the edge dihedral angles multiplied by the edge length, \n% the final sum being divided by (4*PI).\n%\n% Note: the function assumes that the faces are correctly oriented. The\n% face vertices should be indexed counter-clockwise when considering the\n% supporting plane of the plane, with the outer normal oriented outwards\n% of the polyhedron.\n%\n% Typical values for classical polyhedra are:\n% cube side a breadth = (3/2)*a\n% cuboid sides a, b, c breadth = (a+b+c)/2\n% tetrahedron side a breadth = 0.9123*a\n% octaedron side a beradth = 1.175*a\n% dodecahedron, side a breadth = 15*arctan(2)*a/(2*pi)\n% icosaehdron, side a breadth = 15*arcsin(2/3)*a/(2*pi)\n%\n% Example\n% [v e f] = createCube;\n% polyhedronMeanBreadth(v, e, f)\n% ans = \n% 1.5\n%\n% See also\n% meshes3d, meshEdgeFaces, meshDihedralAngles, checkMeshAdjacentFaces\n% trimeshMeanBreadth\n%\n% References\n% Stoyan D., Kendall W.S., Mecke J. (1995) \"Stochastic Geometry and its\n% Applications\", John Wiley and Sons, p. 26\n% Ohser, J., Muescklich, F. (2000) \"Statistical Analysis of\n% Microstructures in Materials Sciences\", John Wiley and Sons, p.352\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\n% compute dihedral angle of each edge\nalpha = meshDihedralAngles(vertices, edges, faces);\n\n% compute length of each edge\nlengths = meshEdgeLength(vertices, edges);\n\n% compute product of length by angles \nbreadth = sum(alpha.*lengths)/(4*pi);\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/polyhedronMeanBreadth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7932954942477775}} {"text": "function w = map ( code, element_order )\n\n%*****************************************************************************80\n%\n%% MAP returns the interpolation matrix for any available element.\n%\n% Formula:\n%\n% For an element of order ELEMENT_ORDER, we suppose we are given \n% ELEMENT_ORDER items of data Q associated with the nodes.\n%\n% Let PHI(J)(R,S) be the Lagrange basis polynomial associated with\n% node J. PHI(J)(R,S) is 1 at node J, and 0 at each of the other nodes.\n%\n% Let P(R,S) be the polynomial of ELEMENT_ORDER terms which interpolates the\n% data Q, that is,\n%\n% P(R(J),S(J)) = Q(J)\n%\n% where the coordinates of node J are (R(J),S(J)). Then we know\n% that we can write\n%\n% P(R,S) = sum ( 1 <= J <= ELEMENT_ORDER ) Q(J) * PHI(J)(R,S)\n%\n% But P(R,S) also has a standard representation as\n%\n% P(R,S) = sum ( 1 <= I <= ELEMENT_ORDER ) A(I) * R**REXP(I) * S**SEXP(I)\n%\n% where REXP(I) and SEXP(I) are the exponents of R and S and\n% the A(I) are the appropriate coefficients.\n%\n% The interpolation matrix W allows us to immediately compute\n% the standard basis coefficients A from the data Q to be interpolated\n% using the formula:\n%\n% A(I) = sum ( 1 <= J <= ELEMENT_ORDER ) W(I,J) * Q(J)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character CODE(*), identifies the element.\n% Legal values include 'Q4', 'Q8', 'Q9', 'Q12', 'Q16', 'QL',\n% 'T3', 'T6' and 'T10'.\n%\n% Input, integer ELEMENT_ORDER, the order associated with the code.\n%\n% Output, real W(ELEMENT_ORDER,ELEMENT_ORDER), the interpolation matrix.\n%\n\n%\n% Get the (R,S) location of the nodes.\n%\n [ r, s, area ] = node_reference ( code );\n%\n% Get the associated monomials.\n%\n [ rexp, sexp ] = poly ( code );\n%\n% Set up the Vandermonde matrix.\n% Factors of the form 0**0 are to be understood as 1.\n%\n for i = 1 : element_order\n for j = 1 : element_order\n\n if ( rexp(j) == 0 )\n rfact = 1.0;\n else\n rfact = r(i)^rexp(j);\n end\n\n if ( sexp(j) == 0 )\n sfact = 1.0;\n else\n sfact = s(i)^sexp(j);\n end\n\n w(i,j) = rfact * sfact;\n\n end\n end\n%\n% Factor the Vandermonde matrix.\n%\n [ w_lu, pivot, info ] = r8ge_fa ( element_order, w );\n\n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MAP - Fatal error!\\n' );\n fprintf ( 1, ' The Vandermonde matrix is singular.\\n' );\n error ( 'MAP - Fatal error!' );\n end\n%\n% Invert the Vandermonde matrix.\n%\n w = r8ge_inverse ( element_order, w_lu, pivot );\n\n return\nend\n", "meta": {"author": "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/map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7932954895586521}} {"text": "function result=halfspacedepth(u,v,x,y)\n\n%HALFSPACEDEPTH computes the halfspace depth of a (two-dimensional) point theta \n% relative to a bivariate data set. \n%\n% The algoritm is described in: \n% Rousseeuw, P., Ruts, I. (1996),\n% \"AS 307: Bivariate Location Depth\",\n% Applied Statistics (JRSS-C), 45, 516-526.\n% \n% Required input arguments:\n% u : first coordinate of the point theta\n% v : second coordinate of the point theta\n% x : vector containing the first coordinates of all the data\n% points\n% y : vector containing the second coordinates of all the data\n% points\n%\n% I/O: [result] = halfspacedepth(u,v,x,y);\n%\n% This function is part of the Matlab Library for Robust Analysis,\n% available at: \n% http://wis.kuleuven.be/stat/robust.html\n%\n% Written by Fabienne Verwerft\n%\n%\n% Checking input\n%\nif not(length(x)==length(y))\n error('The vectors x and y must have the same length.')\nend\nif sum(isnan(x))>=1 || sum(isnan(y))>=1\n error('Missing values are not allowed')\nend\n%\n% m is the number of data points that coincide with theta\n%\neps=0.000001;\nn=length(x);\nnorm=sqrt((x-u).^2 + (y-v).^2);\nm=sum(norm<=eps);\nll=find(norm>eps);\nnorm=norm(ll);\nxn=(x(ll)-u)./norm;\nyn=(y(ll)-v)./norm;\n%\n% The vector containes the indices of the elements of x and y that satisfy\n% the conditions.\n%\nk=find((abs(x(ll))>abs(y(ll))) & (xn>=0));\nalfa(k)=asin(yn(k));\nt=find(alfa(k)<0);\nalfa(k(t))=2*pi+alfa(k(t));\nk=find((abs(x(ll))>abs(y(ll))) & (xn<0));\nalfa(k)=pi-asin(yn(k));\nk=find((abs(x(ll))<=abs(y(ll))) & (yn>=0));\nalfa(k)=acos(xn(k));\nk=find((abs(x(ll))<=abs(y(ll))) & (yn<0));\nalfa(k)=2*pi-acos(xn(k));\ng=find(alfa>=(2*pi-eps));\nalfa(g)=0;\n%\nnn=n-m;\nif nn <= 1\n hdepth=m;\n result=hdepth;\n return\n % all data points coincide with theta\nend\n%\nalfa=sort(alfa);\n%\nhoek=max(alfa(1)-alfa(nn)+2*pi,max(diff(alfa)));\nif hoek > pi+eps\n hdepth=m;\n result=hdepth;\n return\n % hdepth=0 because theta lies outside the datacloud\nend\n%\n% rotation around theta\n% nu is the number of angles in the upper halfcircle\n%\nalfa=alfa-alfa(1);\nnu=sum(alfa < (pi-eps));\n\nif nu >= nn \n hdepth=m;\n result=hdepth;\n return\n % hdepth=0 every angle in the upper halfcircle so theta outside the\n % datacloud.\nend\n%\n% construction of the array F\n%\nbeta=alfa+pi;\nalfatwee=alfa+2*pi;\nA=[alfa,alfatwee,beta];\nAindex(1:2*nn)=1;\nAindex((2*nn+1):3*nn)=0;\n[As,Asin]=sort(A);\nAindexs=Aindex(Asin);\npp=cumsum(Aindexs);\njuisten=find(Aindexs==0);\nF=pp(juisten);\n%\n% Adjust the array F for the angles that coincide with beta.\n%\ngelijkab=intersect(find(diff(As)<=eps)+1,juisten);\nbetagelijka=Asin(gelijkab);\nif length(gelijkab)>0\n for i=1:length(gelijkab)\n aantal=sum((As(Aindexs==1)+eps)0\n for i=1:length(gindex)\n aantal=sum(alfa(1:gindex(i)) 1e-12;\n\tx = ones(size(t));\n\tt = t(j);\n\td = d(j);\n\tx(j) = sin(pi*t) ./ d / K;\nelse\n\tx = nufft_diric(t, K, K, 1);\n%\txo = diric(2*pi*t/K,K); % would require matlab's signal toolbox\n%\tmax_percent_diff(xo, x)\nend\n\n\n%\n% self test\n%\nfunction sinc_periodic_test\n\nKlist = [4 5];\nim clf, pl=220;\nfor kk=1:2\n\tK = Klist(kk);\n\tn = [0:(4*K)]';\n\tt = linspace(0,4*K,401)';\n\tx = @(t,K) sinc_periodic(t, K);\n%\ty = @(t,K) diric(2*pi*t/K,K); % would require matlab's signal toolbox\n\ty = @(t,K) nufft_diric(t,K,K,1);\n\tif im\n\t\tsubplot(pl+kk+0)\n\t\tplot(t, x(t,K), '-', n, x(n,K), 'o')\n\t\ttitlef('Sinc-Periodic K=%d', K)\n\t\taxis([0 4*K -1 1]), xtick([0:4]*K), grid\n\t\tsubplot(pl+kk+2)\n\t\tplot(t, y(t,K), '-', n, y(n,K), 'o')\n\t\ttitlef('Dirichlet K=%d', K)\n\t\taxis([0 4*K -1 1]), xtick([0:4]*K), grid\n\t\tylabelf('K=%d', K)\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/utilities/sinc_periodic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8670357632379241, "lm_q1q2_score": 0.7932518437758337}} {"text": "% solution of Poisson equation using sparse matrix\n%\n% E.Holzbecher, 18.3.2011 \n%\n%--------------------------------------------------\nnx = 12; ny = 12; % dimensions in x- and y-direction\nh = 1/4; % grid spacing\n\n% boundary type indicators (1=Dirichlet, 0=Neumann no-flow)\nltop = logical(zeros(1,nx)); % top\nlbottom = logical(zeros(1,nx)); % bottom\nlleft = logical([ones(6,1) zeros(6,1)]); % left\nlright = logical([zeros(6,1) ones(6,1)]); % right\n\n% boundary values (Dirichlet only)\nbtop = ones(1,nx); % top\nbbottom = zeros(1,nx); % bottom\nbleft = ones(ny,1); % left\nbright = zeros(ny,1); % right\n\nq = 1*ones(nx,ny); % right hand side (source term)\n\nN = nx*ny;\nd = [-nx,-1,0,1,nx];\nB = [ones(N,2) -4*ones(N,1) ones(N,2)];\nq = reshape(q,N,1);\nb = -h*h*q.*ones(N,1);\nfor i = 1:nx\n if ltop(i)\n b(i) = b(i)-btop(i);\n else\n B(i,3) = -3;\n %B(i-1,1) = 0;\n end\n if lbottom(i)\n b(N-nx+i) = b(N-nx+i)-bbottom(i);\n else\n B(N-nx+i,3) = -3;\n % B(N-nx+i,5) = 0;\n end\nend\nfor i = 1:ny\n B(i*nx,2) = 0; \n if i> BVP_Galerkin1(a,b,c,t1,t2,x1,x2,n)\n% where \"n\" is the number of trial functions\n% The output of this program is \n% 1- The approximated solution of x(t) vs. exact solution of x(t)\n% 2- The approximated x'(t) vs. exact x'(t)\n% 3- The approximated x\"(t) vs. exact x\"(t)\n% ======Example============================================================\n% Equation x\"(t)+ x'(t)+ x(t)=0\n% Boundary values x(1)=2, x(10)=0;\n% Solution: We have:\n% a=1; b=1; c=1;\n% t1=1; t2=10; \n% x1=2; x2=0;\n% Using n=8 tiral functions,\n% >>BVP_Galerkin(1,2,3,1,10,2,0,8)\n%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n% October.26, 2010, Ramin Shamshiri \n% ramin.sh@ufl.edu\n% Doctoral student at the University of Florida\n%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nfunction BVP_Galerkin1(a,b,c,t1,t2,x1,x2,n) % Declare function\ndt=0.001; % increment\n%% Begin Approximate solution via Galerkin method over the entire domain\n\n\nfor i=1:n\n for j=1:n\n K1(i,j)=(i*j)*(t2^(j+i-1)-t1^(j+i-1))/(i+j-1); % K1 matrix corresponding to the x\"(t)\n K2(i,j)=j*((t2^(i+j))-(t1^(i+j)))/(i+j); % K2 matrix corresponding to the x'(t)\n K3(i,j)=(t2^(i+j+1)-(t1^(i+j+1)))/(i+j+1); % K3 matrix corresponding to the x(t)\n end\nend\n% Overall Matrix\nK=-a*K1+b*K2+c*K3;\n\n%Applying boundary conditions and Solving nxn system of equations \nfor i=1:n-1\n for j=1:n\n A(i,j)=K(i,j)+((j*a*t2^(j+i-1))-(j*a*t1^(j+i-1)));\n \n end\nend\n\n%Applying boundary conditions\nfor j=1:n\n A(n-1,j)=(t1^j);\n A(n,j)=(t2^j);\nend\n\nfor i=1:n-1\n B(i,1)=0;\nend\nB(n-1,1)=x1;\nB(n,1)=x2;\n\nC=inv(A)*B; % Ci: Coefficients of terms \n\nt=t1:dt:t2;\nt=t'; \n% Creating vertical axis values, x(t)\nx= zeros((t2-t1)/dt+1,1);\nfor i=1:(t2-t1)/dt+1\n for j=1:n\n x(i,1)=x(i,1)+ C(j,1)*(t(i,1)^j);\n end\nend\n\n% calculating x'(t)\ndx=zeros((t2-t1)/dt+1,1);\nfor i=2:(t2-t1)/dt+1\n dx(i,1)=(x(i)-x(i-1))/dt;\nend\n% calculating x\"(t)\nd2x=zeros((t2-t1)/dt+1,1);\nfor i=3:(t2-t1)/dt+1\n d2x(i,1)=(dx(i)-dx(i-1))/dt;\nend\n\n figure1 = figure('Color',[1 1 1]); \n% Plotting approximate solution via Galerkin method over the entire domain\nsubplot(3,1,1,'Parent',figure1);\n% Plotting the Approximate solution in green (Galerkin method over the entire domain)\nplot(t,x,'-.', 'Color','r', 'LineWidth',2), grid on; hold on; \n% Plotting the approximate dx\nsubplot(3,1,2,'Parent',figure1);\nplot(t,dx, '-.', 'Color','r', 'LineWidth',2), grid on; hold on; \n% Plotting the approximate d2u\nsubplot(3,1,3,'Parent',figure1);\nplot(t,d2x, '-.', 'Color','r', 'LineWidth',2), grid on; hold on; \n%% End of approximate solution via Galerkin method over the entire domain\n\n\n\n\n%% ==============Begin Calculating Exact Soution========================== \nr=roots([a b c]); % Roots of auxiliary equation\nr1=r(1); r2=r(2);\n\n% Bulding t-axis values\nt=t1:dt:t2; t=t'; \ns=size(t);\n\n% Bulding x(t) axis values\nx=zeros(s(1),1);\nif r1==r2 % For critically damped case\n \n C=inv([exp(r1*t1) t1*exp(r2*t1);exp(r1*t2) t2*exp(r2*t2)])*([x1;x2]);\n C1=C(1);\n C2=C(2);\n \n for i=1:s(1)\n x(i)=C1*exp(r1*t(i))+C2*t(i)*exp(r2*t(i));\n end\n \nelse % For Under-damped or Over-damped case\n \n C=inv([exp(r1*t1) exp(r2*t1);exp(r1*t2) exp(r2*t2)])*([x1;x2]);\n C1=C(1);\n C2=C(2);\n \n for i=1:s(1)\n x(i)=C1*exp(r1*t(i))+C2*exp(r2*t(i));\n end\nend\n\n% calculating x'(t)\ndx=zeros(s(1),1);\nfor i=2:s(1)\n dx(i,1)=(x(i)-x(i-1))/dt;\nend\n\n% calculating x\"(t)\nd2x=zeros(s(1),1);\nfor i=3:s(1)\n d2x(i,1)=(dx(i)-dx(i-1))/dt;\nend\n\n% Plotting Exact solution \nsubplot(3,1,1,'Parent',figure1);\n% Plotting the exact solution x(t) in blue\nplot(t,x, 'Color','b', 'LineWidth',2); \nxlabel('Time (sec)','FontSize',12);\nylabel('x(t) (m)','FontSize',12);\nlegend1 = legend(subplot(3,1,1),'show');\nlegend('Approximate x(t)','Exact x(t)')\n\n% Plotting the exact solution x'(t) in blue\nsubplot(3,1,2,'Parent',figure1);\nplot(t,dx, 'Color','b', 'LineWidth',2); \nxlabel('Time (sec)','FontSize',12);\nylabel('dx/dt (m/s)','FontSize',12);\nlegend1 = legend(subplot(3,1,2),'show');\nlegend('Approximate dx(t)','Exact dx(t)')\n\n% Plotting the exact solution x\"(t) in blue\nsubplot(3,1,3,'Parent',figure1);\nplot(t,d2x, 'Color','b', 'LineWidth',2);\nxlabel('Time (sec)','FontSize',12);\nylabel('d^2x/dt^2 m/s^2','FontSize',12);\nlegend1 = legend(subplot(3,1,3),'show');\nlegend('Approximate d2x(t)','Exact dx(t)')\nclc\n%% =====================End of exact solution============================== \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/39794-galerkins-method-for-solving-2nd-order-homogeneous-constant-coefficients-bvp/BVP_Galerkin1/BVP_Galerkin1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7928573842406845}} {"text": "function [S,C]=allsums(varargin)\n% ALLSUMS Distribution of unique sums among all combinations of vectors.\n% [S,C]=ALLSUMS(IN) depending on input IN, will do one of two different\n% procedures for calculating all unique combinations of sums.\n%\n% The output vectors, S and C, are respectively the list of unique\n% sums, and the count distribution for those sums among all combinations.\n%\n%\n% SINGLE INPUT: \n%\n% [S,C]=ALLSUMS(VEC) for a single input vector of length N, returns the\n% distribution of unique sums among the (2^N)-1 combinations of\n% non-empty subsets of elements within VEC.\n%\n% EXAMPLE:\n% Number of ways to have a total of 250 using only the odd numbers\n% from 1 to 100.\n% [S,C]=allsums(1:2:100);\n% num=C(S==250)\n%\n%\n% MULTIPLE INPUTS:\n%\n% [S,C]=ALLSUMS(VEC,K) with vector VEC of length N, assumes the\n% equivalent scenario of rolling a N-sided die, with values VEC, \n% K times and returns the distributions of unique sums among all\n% N^K combinations of values.\n%\n% [S,C]=ALLSUMS(VEC1,K1,VEC2,K2,...) with vectors of length N1, N2, ...\n% assumes the equivalent scenario of rolling a N1-sided die, with\n% values VEC1, K1 times; then rolling a N2-sided dice, with values VEC2,\n% K2 times; etc. and returns the distribution of unique sums among\n% all (N1^K1)*(N2^K2)*... combinations of values\n%\n% SINGLE VECTOR, REPEATED\n% Probability distribution of rolling a regular 6-sided die 100 times\n% [S,C]=allsums(1:6,100);\n% plot(S,C./sum(C)), grid on\n%\n% MULTIPLE VECTORS, REPEATED\n% Probability of the total yielding exactly zero when rolling a\n% A) six-sided die with values [-5:0] ten times, and then a\n% B) ten-sided die with values [-4:5] twenty times.\n% [S,C]=allsums([-5:0],10,[-4:5],20);\n% prob=C(S==0)/sum(C)\n%\n\n% Mike Sheppard\n% Last Modified: 27-Oct-2011\n\n\n\n%ERROR CHECKING\nninputs=numel(varargin);\nswitch ninputs\n case 0\n error('allsums:Inputs','Requires at least one input');\n case 1\n VEC=varargin{1}; %Input vector\n if any(~isfinite(VEC))\n error('allsums:Inputs','Requires input vector to be numeric');\n end\n otherwise\n num=ninputs/2;\n if mod(ninputs,2)~=0\n error('allsums:Inputs','Requires inputs to be in [Vector],[Number] order');\n end\n for k=1:num\n ALLVEC{k}=varargin{2*k-1}; ALLNUMR{k}=varargin{2*k}; numr=ALLNUMR{k};\n if any(~isfinite(ALLVEC{k}))\n error('allsums:Inputs','Requires all input vectors to be numeric');\n end\n if any([~isfinite(numr) ~isscalar(numr) numr~=round(numr) numr<=0])\n error('allsums:Inputs','Requires number of repetitions to be a positive scalar integer');\n end\n end\nend\n\n\n\n%ALGORITHM\nswitch ninputs\n case 1\n % Distribution of unique sums among the (2^N)-1 combinations of\n % non-empty subsets of elements within VEC.\n S=[]; C=[];\n for k=1:numel(VEC)\n [S,ign,indx]=unique([S VEC(k) S+VEC(k)]);\n C=accumarray(indx',[C 1 C])';\n end\n S=S(:); C=C(:);\n otherwise\n % Distribution of unique sums among all (N1^K1)*(N2^K2)*... \n % combinations of vectors of length N_k repeated K_k times,\n % with values VEC_k each.\n S=0; C=1;\n for k=1:num\n VEC=ALLVEC{k}; VEC=VEC(:); numr=ALLNUMR{k};\n for n=1:numr\n tempv=bsxfun(@plus,S',VEC);\n tempc=repmat(C',length(VEC),1);\n [S,ign,indx]=unique(tempv(:));\n C=accumarray(indx,tempc(:));\n end\n end\nend\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/33454-all-sums/allsums.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7928263899150048}} {"text": "% \n% Computing the numerical rank of a downdated matrix.\n%\n% \n% [r,Basis,C] = NumericalRankDowndate(A,pth,C,RC)\n%\n% \n% 1. A -- the target matrix;\n% 2. pth -- the index of row/column to be deleted;\n% 3. C -- cell array contains information required by updating/downdating;\n% 4. RC -- Set to 'row', then the pth row will be deleted.\n% Set to 'column', then the pth column will be deleted.\n%\n% \n% 1. r -- the numerical rank of the downdated matrix;\n% 2. Basis --\n% For high rank cases...\n% a matrix whose columns form an orthonormal basis of\n% the numerical kernel;\n%\n% For low rank cases...\n% a matrix whose columns form an orthonormal basis of\n% the numerical range;\n%\n% 3. C -- Matlab cell array\n%\n% For high rank cases...\n% C{1,1} = rank : the numerical rank of the downdated matrix;\n% C{2,1} = Basis : matrix whose columns form an orthonormal kernel basis;\n% C{3,1} = Q : the Q in the QR decomposition of the kernel stacked matrix;\n% C{4,1} = R : the R in the QR decomposition of the kernel stacked matrix;\n% C{5,1} = tau : scaling factor in the kernel stacked matrix;\n% C{6,1} = tol : the rank decision threshold;\n%\n% For low rank cases...\n% C{1,1} = rank : the numerical rank of the downdated matrix;\n% C{2,1} = U : the U in the USV+E decomposition of the downdated matrix;\n% C{3,1} = V : the V in the USV+E decomposition of the downdated matrix;\n% C{4,1} = S : the S in the USV+E decomposition of the downdated matrix;\n% C{5,1} = tol : the rank decision threshold;\n%\n% \n% [1] T.Y. Li and Z. Zeng, \"A Rank-Revealing Method with Updating, Downdating\n% and Applications\", SIAM J. Matrix Anal. and Appl., 26 (2005), pp. 918--946.\n%\n% [2] T.L. Lee, T.Y. Li and Z. Zeng, \"A Rank-Revealing Method with Updating, \n% Downdating and Applications, Part II\", SIAM J. Matrix Anal. and Appl. (2009).\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/NumericalRankDowndate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7928263844548811}} {"text": "function value = r8vec_length ( dim_num, x )\n\n%*****************************************************************************80\n%\n%% R8VEC_LENGTH returns the Euclidean length of an R8VEC\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real X(DIM_NUM), the vector.\n%\n% Output, real VALUE, the Euclidean length of the vector.\n%\n value = sqrt ( sum ( ( x(1:dim_num) ).^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/tet_mesh/r8vec_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7927801181984498}} {"text": "function value = g_hofstadter ( n )\n\n%*****************************************************************************80\n%\n%% G_HOFSTADTER computes the Hofstadter G sequence.\n%\n% Discussion:\n%\n% G(N) = 0 if N = 0\n% = N - G ( G ( N - 1 ) ), otherwise.\n%\n% G(N) is defined for all nonnegative integers.\n%\n% The value of G(N) turns out to be related to the Zeckendorf\n% representation of N as a sum of non-consecutive Fibonacci numbers.\n% To compute G(N), determine the Zeckendorf representation:\n%\n% N = sum ( 1 <= I <= M ) F(I)\n%\n% and reduce the index of each Fibonacci number by 1:\n%\n% G(N) = sum ( 1 <= I <= M ) F(I-1)\n%\n% However, this is NOT how the computation is done in this routine.\n% Instead, a straightforward recursive function call is defined\n% to correspond to the definition of the mathematical function.\n%\n% Table:\n%\n% N G(N) Zeckendorf Decremented\n% -- ---- ---------- -----------\n%\n% 1 1 1 1\n% 2 1 2 1\n% 3 2 3 2\n% 4 3 3 + 1 2 + 1\n% 5 3 5 3\n% 6 4 5 + 1 3 + 1\n% 7 4 5 + 2 3 + 1\n% 8 5 8 5\n% 9 6 8 + 1 5 + 1\n% 10 6 8 + 2 5 + 1\n% 11 7 8 + 3 5 + 2\n% 12 8 8 + 3 + 1 5 + 2 + 1\n% 13 8 13 8\n% 14 9 13 + 1 8 + 1\n% 15 9 13 + 2 8 + 1\n% 16 10 13 + 3 8 + 2\n% 17 11 13 + 3 + 1 8 + 2 + 1\n% 18 11 13 + 5 8 + 3\n% 19 12 13 + 5 + 1 8 + 3 + 1\n% 20 12 13 + 5 + 2 8 + 3 + 1\n% 21 13 21 13\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Douglas Hofstadter,\n% Goedel, Escher, Bach,\n% Basic Books, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the argument of the function.\n%\n% Output, integer VALUE, the value of the function.\n%\n if ( n <= 0 )\n value = 0;\n else\n value = n - g_hofstadter ( g_hofstadter ( 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/polpak/g_hofstadter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7927086338229852}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all\nclose all\nclc\n% E: modulus of elasticity\n% A: area of cross section\n% L: length of bar\nE=8; L=4;\nu_exact=@(x) (56-8*(x-2)-24*heaviside(x-5))/2/x;\nhold on;\nezplot(u_exact,[2 6])\ntitle('Exact Solution v.s. FEM','interpreter','latex');\nxlabel('x','interpreter','latex');\nylabel('Axial stress, $\\it{\\sigma}_{x}$','interpreter','latex','FontSize',12);\n\nfor i=1:4 %For NEL = 1, 2, 4, 8 \nfprintf( '\\nNumber of elements:%d\\n\\n',2^(i-1) );\n% numberElements: number of elements\nnumberElements=2^(i-1); \n% numberNodes: number of nodes\nnumberNodes=2*numberElements+1;\nA=zeros(1,numberElements);\n% generation of coordinates and connectivities \nNNOD=3; \nnodeCoordinates=linspace(2,L+2,numberNodes);\n%Generate element length vector\nfor i=1:numberElements\n Le(i)=L/numberElements;\n elementNodes(i,:)=[(i-1)*2+1 (i-1)*2+2 (i-1)*2+3];\n A(i)=(nodeCoordinates(2*i-1)+Le(i)/2)*2;\nend\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n ngp = 3;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(end)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A(e);\n force(elementDof)=force(elementDof)+...\n 8*shape'*detJacobian*w(ip);\n end\n if(nodeCoordinates(elementDof(end))==5)\n x=(5-xc)/detJacobian;\n [s,n]=shapeFunctionL3(x);\n force(elementDof)= force(elementDof)+...\n 24*s';\n end\n if(nodeCoordinates(elementDof(1))<5&&...\n nodeCoordinates(elementDof(3))>5)\n x=(5-xc)/detJacobian;\n [s,n]=shapeFunctionL3(x);\n force(elementDof)= force(elementDof)+...\n 24*s';\n end\nend \n% boundary conditions and solution\n% prescribed dofs\nprescribedDof=[1];\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactionsPretty(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\nfprintf('Axial stress\\n')\nfprintf('element\\t\\taxial stress\\n')\n%Stress and strain recovery\nngp = 3;\nelementNodeCoor=zeros(numberElements*NNOD,1);\nelementNodeStr=zeros(numberElements*NNOD,1);\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:);\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n xi=[-1 0 1];\n for ip=1:NNOD;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip));\n B=naturalDerivatives*invJacobian;\n elementNodeCoor(ip+(e-1)*NNOD,1)=nodeCoordinates(elementDof(ip));\n elementNodeStr(ip+(e-1)*NNOD,1)=E*B*displacements(elementDof,1);\n fprintf('%2.0f\\t%2.0fth node\\t%10.4e\\n', e, ip,elementNodeStr(ip+(e-1)*NNOD,1))\n end\nend \n\n%post process\nswitch numberElements\n case 1\n str='r*--';\n case 2\n str='g*--';\n case 4\n str='k*--';\n case 8\n str='m*--';\nend\n\nplot(elementNodeCoor,elementNodeStr,str)\nhold on;\nend\nlegend('Exact solution','NEL=1','NEL=2','NEL=4','NEL=8','interpreter','latex');\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/FEM/BarSimple_solution/Prob_4/Quad/ex4_quad_stress_direct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7927086212341932}} {"text": "function [H A b] = affineLS(X1, X2, normalization)\n\n% [H A b] = affineLS(X1, X2, normalization)\n%\n% DESC:\n% computes the affine transformation between the point pairs X1, X2\n%\n% VERSION:\n% 1.0.0\n%\n% INPUT:\n% X1, X2 = point matches (cartesian coordinates)\n% normalization = true (default) or false to enable/disable point \n% normalzation\n%\n% OUTPUT:\n% H = homography representing the affine transformation\n% A = 4x4 affine coefficient matrix\n% b = affine translation vector\n\n\n% AUTHOR:\n% Marco Zuliani, email: marco.zuliani@gmail.com\n% Copyright (C) 2010 by Marco Zuliani \n% \n% LICENSE:\n% This toolbox is distributed under the terms of the GNU GPL.\n% Please refer to the files COPYING.txt for more information.\n\n\n% HISTORY\n% 1.0.0 11/22/10 - intial version\n\nif (nargin < 3)\n normalization = true;\nend;\n\nN = size(X1, 2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% checks\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif (size(X2, 2) ~= N)\n error('AffineLS:inputError', ...\n 'The set of input points should have the same cardinality')\nend;\nif N < 2\n error('AffineLS:inputError', ...\n 'At least 3 point correspondences are needed')\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% normalize the input\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif normalization\n % fprintf('\\nNormalizing...')\n [X1, T1] = normalize_points(X1);\n [X2, T2] = normalize_points(X2);\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% estimation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n% Traditional LS\nP = zeros(2*N, 6);\nq = zeros(2*N, 1);\n\nind = 1:2;\nfor n = 1:N\n \n P(ind, :) = [X1(1,n) 0 X1(2,n) 0 1 0; 0 X1(1,n) 0 X1(2,n) 0 1];\n \n q(ind) = X2(1:2, n);\n \n ind = ind + 2;\n \nend;\n\n% solve the linear system in a least square sense\nTheta = P\\q;\n\n% compute the corresponding homography\nH = [Theta(1) Theta(3) Theta(5); Theta(2) Theta(4) Theta(6); 0 0 1];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% de-normalize the parameters\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif normalization\n H = T2\\H*T1;\nend;\nH = H/H(9);\n\n% prepare the output\nif nargout > 1\n \n A = H(1:2, 1:2);\n b = H(1:2, 3);\n \nend;\n\nreturn", "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/Models/Affine/affineLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7927065179886875}} {"text": "function centroid = triangle_centroid_3d ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_CENTROID_3D computes the centroid of a triangle in 3D.\n%\n% Discussion:\n%\n% The centroid of a triangle can also be considered the\n% center of gravity or center of mass, assuming that the triangle\n% is made of a thin uniform sheet of massy material.\n%\n% The centroid of a triangle is the intersection of the medians.\n% A median of a triangle is a line connecting any vertex to the\n% midpoint of the opposite side.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(3,3), the triangle vertices.\n%\n% Output, real CENTROID(3,1), the coordinates of the centroid.\n%\n dim_num = 3;\n\n for i = 1 : dim_num\n centroid(i,1) = sum ( t(i,1:3) ) / 3.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/triangle_centroid_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7926993831536001}} {"text": "function [D,P] = dijk(A,s,t)\n%DIJK Shortest paths from nodes 's' to nodes 't' using Dijkstra algorithm.\n% [D,p] = dijk(A,s,t)\n% A = n x n node-node weighted adjacency matrix of arc lengths\n% (Note: A(i,j) = 0 => Arc (i,j) does not exist;\n% A(i,j) = NaN => Arc (i,j) exists with 0 weight)\n% s = FROM node indices\n% = [] (default), paths from all nodes\n% t = TO node indices\n% = [] (default), paths to all nodes\n% D = |s| x |t| matrix of shortest path distances from 's' to 't'\n% = [D(i,j)], where D(i,j) = distance from node 'i' to node 'j' \n% P = |s| x n matrix of predecessor indices, where P(i,j) is the\n% index of the predecessor to node 'j' on the path from 's(i)' to 'j'\n% (use PRED2PATH to convert P to paths)\n% = path from 's' to 't', if |s| = |t| = 1\n%\n% (If A is a triangular matrix, then computationally intensive node\n% selection step not needed since graph is acyclic (triangularity is a \n% sufficient, but not a necessary, condition for a graph to be acyclic)\n% and A can have non-negative elements)\n%\n% (If |s| >> |t|, then DIJK is faster if DIJK(A',t,s) used, where D is now\n% transposed and P now represents successor indices)\n%\n% (Based on Fig. 4.6 in Ahuja, Magnanti, and Orlin, Network Flows,\n% Prentice-Hall, 1993, p. 109.)\n\n% Copyright (c) 1998-2001 by Michael G. Kay\n% Matlog Version 5 22-Aug-2001\n\n% Input Error Checking ******************************************************\nerror(nargchk(1,3,nargin));\n\n[n,cA] = size(A);\n\nif nargin < 2 | isempty(s), s = (1:n)'; else s = s(:); end\nif nargin < 3 | isempty(t), t = (1:n)'; else t = t(:); end\n\nif ~any(any(tril(A) ~= 0)) % A is upper triangular\n isAcyclic = 1;\nelseif ~any(any(triu(A) ~= 0)) % A is lower triangular\n isAcyclic = 2;\nelse % Graph may not be acyclic\n isAcyclic = 0;\nend\n\nif n ~= cA\n error('A must be a square matrix');\nelseif ~isAcyclic & any(any(A < 0))\n error('A must be non-negative');\nelseif any(s < 1 | s > n)\n error(['''s'' must be an integer between 1 and ',num2str(n)]);\nelseif any(t < 1 | t > n)\n error(['''t'' must be an integer between 1 and ',num2str(n)]);\nend\n% End (Input Error Checking) ************************************************\n\nA = A'; % Use transpose to speed-up FIND for sparse A\n\nD = zeros(length(s),length(t));\nif nargout > 1, P = zeros(length(s),n); end\n\nfor i = 1:length(s)\n j = s(i);\n \n Di = Inf*ones(n,1); Di(j) = 0;\n \n isLab = logical(zeros(length(t),1));\n if isAcyclic == 1\n nLab = j - 1;\n elseif isAcyclic == 2\n nLab = n - j;\n else\n nLab = 0;\n UnLab = 1:n;\n isUnLab = logical(ones(n,1));\n end\n \n while nLab < n & ~all(isLab)\n if isAcyclic\n Dj = Di(j);\n else\t% Node selection\n [Dj,jj] = min(Di(isUnLab));\n j = UnLab(jj);\n UnLab(jj) = [];\n isUnLab(j) = 0;\n end\n \n nLab = nLab + 1;\n if length(t) < n, isLab = isLab | (j == t); end\n \n [jA,kA,Aj] = find(A(:,j));\n Aj(isnan(Aj)) = 0;\n \n if isempty(Aj), Dk = Inf; else Dk = Dj + Aj; end\n \n if nargout > 1, P(i,jA(Dk < Di(jA))) = j; end\n Di(jA) = min(Di(jA),Dk);\n \n if isAcyclic == 1 % Increment node index for upper triangular A\n j = j + 1;\n elseif isAcyclic == 2 % Decrement node index for lower triangular A\n j = j - 1;\n end\n end\n D(i,:) = Di(t)';\nend\n\nif nargout > 1 & length(s) == 1 & length(t) == 1\n P = pred2path(P,s,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/graph/dijkstra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.792699365568745}} {"text": "function varargout = cylinderMesh(cyl, varargin)\n%CYLINDERMESH Create a 3D mesh representing a cylinder\n%\n% [V F] = cylinderMesh(CYL)\n% Computes vertex coordinates and face vertex indices of a mesh\n% representing a 3D cylinder given as [X1 Y1 Z1 X2 Y2 Z2 R].\n%\n% Example\n% % Draw a rotated cylinder\n% cyl = [0 0 0 10 20 30 5];\n% [v f] = cylinderMesh(cyl);\n% figure;drawMesh(v, f, 'FaceColor', 'r');\n% view(3); axis equal;\n%\n% % Draw three mutually intersecting cylinders\n% p0 = [30 30 30];\n% p1 = [90 30 30];\n% p2 = [30 90 30];\n% p3 = [30 30 90];\n% [v1 f1] = cylinderMesh([p0 p1 25]);\n% [v2 f2] = cylinderMesh([p0 p2 25]);\n% [v3 f3] = cylinderMesh([p0 p3 25]);\n% figure; hold on;\n% drawMesh(v1, f1, 'FaceColor', 'r');\n% drawMesh(v2, f2, 'FaceColor', 'g');\n% drawMesh(v3, f3, 'FaceColor', 'b');\n% view(3); axis equal\n% set(gcf, 'renderer', 'opengl')\n% \n% See also\n% drawCylinder, torusMesh, sphereMesh\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% extract cylinder data\np1 = cyl(:, 1:3);\np2 = cyl(:, 4:6);\nr = cyl(:, 7);\n\n% compute length and orientation\n[theta, phi, rho] = cart2sph2d(p2 - p1);\n\n% parametrisation on x\nt = linspace(0, 2*pi, 20);\nlx = r * cos(t);\nly = r * sin(t);\n\n% parametrisation on z\nlz = linspace(0, rho, 10);\n\n% generate surface grids\nx = repmat(lx, [length(lz) 1]);\ny = repmat(ly, [length(lz) 1]);\nz = repmat(lz', [1 length(t)]);\n\n% transform points \ntrans = localToGlobal3d(p1, theta, phi, 0);\n[x, y, z] = transformPoint3d(x, y, z, trans);\n\n% convert to FV mesh\n[vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true);\n\n% format output\nvarargout = formatMeshOutput(nargout, vertices, faces);\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/cylinderMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7926400931680356}} {"text": "function [ area, radout, side ] = polygon_inrad_data_2d ( n, radin )\n\n%*****************************************************************************80\n%\n%% POLYGON_INRAD_DATA_2D determines polygonal data from its inner radius in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sides of the polygon.\n% N must be at least 3.\n%\n% Input, real RADIN, the inner radius of the polygon, that is,\n% the radius of the largest circle that can be inscribed within\n% the polygon.\n%\n% Output, real AREA, the area of the regular polygon.\n%\n% Output, real RADOUT, the outer radius of the polygon, that is,\n% the radius of the smallest circle that can be described about\n% the polygon.\n%\n% Output, real SIDE, the length of one side of the polygon.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_INRAD_DATA_2D - Fatal error!\\n' );\n fprintf ( 1, ' Input value of N must be at least 3\\n' );\n fprintf ( 1, ' but your input value was N = %d\\n', n );\n error ( 'POLYGON_INRAD_DATA_2D - Fatal error!' );\n end\n\n angle = pi / n;\n area = n * radin * radin * tan ( angle );\n side = 2.0 * radin * tan ( angle );\n radout = 0.5 * side / sin ( angle );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_inrad_data_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7926304501327429}} {"text": "function value = i4_bit_lo1 ( n )\n\n%*****************************************************************************80\n%\n%% I4_BIT_LO1 returns the position of the low 1 bit base 2 in an integer.\n%\n% Example:\n%\n% N Binary Lo 1\n% ---- -------- ----\n% 0 0 0\n% 1 1 1\n% 2 10 2\n% 3 11 1\n% 4 100 3\n% 5 101 1\n% 6 110 2\n% 7 111 1\n% 8 1000 4\n% 9 1001 1\n% 10 1010 2\n% 11 1011 1\n% 12 1100 3\n% 13 1101 1\n% 14 1110 2\n% 15 1111 1\n% 16 10000 5\n% 17 10001 1\n% 1023 1111111111 1\n% 1024 10000000000 11\n% 1025 10000000001 1\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 N, the integer to be measured.\n% N should be nonnegative.\n%\n% Output, integer I4_BIT_LO1, the position of the low 1 bit.\n%\n bit = 0;\n i = n;\n\n while ( 1 )\n\n bit = bit + 1;\n i2 = floor ( i / 2 );\n\n if ( i ~= 2 * i2 )\n break\n end\n\n i = i2;\n\n end\n\n value = bit;\n\n return\nend\n", "meta": {"author": "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_bit_lo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8902942370375485, "lm_q1q2_score": 0.7926238265586659}} {"text": "function jacobi_eigenvalue_test03 ( )\n\n%*****************************************************************************80\n%\n%% JACOBI_EIGENVALUE_TEST03 uses a 5x5 test matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 July 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_EIGENVALUE_TEST03\\n' );\n fprintf ( 1, ' For a symmetric matrix A,\\n' );\n fprintf ( 1, ' JACOBI_EIGENVALUE computes the eigenvalues D\\n' );\n fprintf ( 1, ' and eigenvectors V so that A * V = D * V.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use the discretized second derivative matrix.\\n' );\n \n n = 5;\n\n a = zeros ( n, n );\n for i = 1 : n\n a(i,i) = -2.0;\n end\n for i = 1 : n - 1\n a(i,i+1) = +1.0;\n a(i+1,i) = +1.0;\n end\n\n r8mat_print ( n, n, a, ' Input matrix A:' );\n\n it_max = 100;\n\n [ v, d, it_num, rot_num ] = jacobi_eigenvalue ( n, a, it_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n fprintf ( 1, ' Number of rotations = %d\\n', rot_num );\n\n r8vec_print ( n, d, ' Eigenvalues D:' );\n\n r8mat_print ( n, n, v, ' Eigenvector matrix V:' );\n%\n% Compute eigentest.\n%\n error_frobenius = r8mat_is_eigen_right ( n, n, a, v, d );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm error in eigensystem A*V-D*V = %g\\n', ...\n error_frobenius );\n\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/jacobi_eigenvalue/jacobi_eigenvalue_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8902942341267434, "lm_q1q2_score": 0.7926238161927737}} {"text": "function out = proj_l1ball_box(x,w,r,u)\n%PROJ_L1BALL_BOX computes the orthogonal projection onto the intersection of an l1 ball and a box\n% {x: norm(w(:).*x(:),1)<=r, -u<=x<=u} \n% \n% Usage: \n% out = PROJ_L1BALL_BOX(x,[w],[r],[u])\n% =============================================================\n% INPUT:\n% x - point to be projected (vector/matrix)\n% w - weights vecotr - [default: 1]\n% r - positive scalar - [default: 1]\n% u - box paramters (scalar/vector/matrix)- [default: Inf]\n% ==============================================================\n% Assumptions:\n% r,u >= 0\n% w >= 0\n% ==============================================================\n% Output:\n% out - projection vector\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n%reading the user x and setting defalut values when required.\nif (nargin < 1)\n error ('usage: proj_l1_inter_box(x,[w],[r],[u])') ;\nend\n\nif (nargin < 4)\n %box parameters are not given, setting to defalut value :inf\n u = inf*(ones(size(x))) ;\nend\n\nif ((nargin < 3) || (isempty(r)))\n %ball radius is not given, setting to defalut value :1\n r = 1;\nend\n\nif ((nargin < 2) || (isempty(w)))\n %weight vector is not given, setting to default value: ones\n w=ones(size(x)) ;\nend\n\nif ((r < 0) || (min(min(u)) < 0))\n error('Set is infeasible') ;\nend\n\nif (min(min(w)) < 0)\n error('usage: proj_l1_inter_box(x,[w],[r],[u]) - w should be a non-negative vector or matrix');\nend\n\n%checking the simple projection \nout = min(max(x,-u),u) ;\nif ((sum(sum(w .* abs (out)))) <= r)\n return;\nend\n\n%defining f on lambda - to be used by the bisetion\n\nf= @(lam) trace(w' * abs(min(max(abs(x)-lam*w,0),u) .* sign(x)))- r;\nlambda_min = 0;\n\nlambda_max = 1;\nwhile(f(lambda_max)>0)\n lambda_max = lambda_max *2 ;\nend\n\neps = 1e-10 ;\nfinal_lam = bisection(f,lambda_min,lambda_max,eps) ;\nout= min(max(abs(x)-final_lam*w,0),u) .* sign(x) ;\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/proj_l1ball_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.7926048944586152}} {"text": "function d = mahalanobis(varargin)\n%MAHALANOBIS Computes the Mahalanobis distance.\n% D = MAHALANOBIS(Y, X) computes the Mahalanobis distance between\n% each vector in Y to the mean (centroid) of the vectors in X, and\n% outputs the result in vector D, whose length is size(Y, 1). The\n% vectors in X and Y are assumed to be organized as rows. The\n% input data can be real or complex. The outputs are real\n% quantities.\n%\n% D = MAHALANOBIS(Y, CX, MX) computes the Mahalanobis distance\n% between each vector in Y and the given mean vector, MX. The\n% results are output in vector D, whose length is size(Y, 1). The\n% vectors in Y are assumed to be organized as the rows of this\n% array. The input data can be real or complex. The outputs are\n% real quantities. In addition to the mean vector MX, the\n% covariance matrix CX of a population of vectors X also must be\n% provided. Use function COVMATRIX (Section 11.5) to compute MX and\n% CX.\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: 2005/01/18 13:44:47 $\n\n% Reference: Acklam, P. J. [2002]. \"MATLAB Array Manipulation Tips\n% and Tricks.\" Available at\n% home.online.no/~pjacklam/matlab/doc/mtt/index.html \n% or at\n% www.prenhall.com/gonzalezwoodseddins\n\nparam = varargin; % Keep in mind that param is a cell array.\nY = param{1};\nny = size(Y, 1); % Number of vectors in Y.\n\nif length(param) == 2\n X = param{2};\n % Compute the mean vector and covariance matrix of the vectors\n % in X.\n [Cx, mx] = covmatrix(X);\nelseif length(param) == 3 % Cov. matrix and mean vector provided.\n Cx = param{2};\n mx = param{3};\nelse \n error('Wrong number of inputs.')\nend\nmx = mx(:)'; % Make sure that mx is a row vector.\n\n% Subtract the mean vector from each vector in Y.\nYc = Y - mx(ones(ny, 1), :);\t\n\n% Compute the Mahalanobis distances.\nd = real(sum(Yc/Cx.*conj(Yc), 2));", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/_internal/metrics/mahalanobis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8499711680567799, "lm_q1q2_score": 0.7925584264950003}} {"text": "function ncomb = multinomial_coef2 ( nfactor, factor )\n\n%*****************************************************************************80\n%\n%% MULTINOMIAL_COEF2 computes a Multinomial coefficient.\n%\n% Discussion:\n%\n% The multinomial coefficient is a generalization of the binomial\n% coefficient. It may be interpreted as the number of combinations of\n% N objects, where FACTOR(1) objects are indistinguishable of type 1,\n% ... and FACTOR(NFACTOR) are indistinguishable of type NFACTOR,\n% and N is the sum of FACTOR(1) through FACTOR(NFACTOR).\n%\n% NCOMB = N! / ( FACTOR(1)! FACTOR(2)! ... FACTOR(NFACTOR)! )\n%\n% A direct method is used, which should be exact. However, there\n% is a possibility of intermediate overflow of the result.\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% Parameters:\n%\n% Input, integer NFACTOR, the number of factors.\n% 1 <= NFACTOR.\n%\n% Input, integer FACTOR(NFACTOR), contains the factors.\n% 0.0 <= FACTOR(I).\n%\n% Output, integer NCOMB, the value of the multinomial coefficient.\n%\n ncomb = 1;\n k = 0;\n\n for i = 1 : nfactor\n\n for j = 1 : factor(i)\n k = k + 1;\n ncomb = ( ncomb * k ) / 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/prob/multinomial_coef2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7925427912625242}} {"text": "%% example \nfunction [Y, X, U] = example(U, varargin)\n\n%% Syntax\n% function [Y, X, U] = example(U, varargin)\n\n%% Description\n% Function for simulating the nonlinear dynamic system: \n% \n% y(k)\n% y(k+1) = --------------- + [u(k)]^3\n% 1 + y(k)*y(k)\n%\n% which is used to demonstrate the use of this toolbox. \n% [1] K.S. Narendra and K. Parthasarathy. Identification\n% and Control of Dynamical Systems Using Neural Networks, \n% IEEE Transactions on NN, Vol.1 No. 1, 4-27, 1990.\n%\n% Usage: \n% (1) [Y, X, U] = example(u, y0), u is vector, y0 is optional \n% (2) [Y, X, U] = example(U, y0), U is Nx2 matrix \n% Inputs:\n% u .. vector of inputs \n% U .. matrix U=[x u], where x is vector of past states nad u is vector of\n% inputs\n% y0 .. intial state of the system, optional \n% Outputs: \n% Y .. vector of outputs \n% X .. vector of past outputs: X(k) = Y(k-1)\n% U .. vector of inputs \n% \n% \n\n%% Examples\n% demo_example_gp_data.m\n\n%% See Also\n% EXAMPLE_DERIVATIVE, EXAMPLE_LM_IDENT\n\n\nif(nargin==1)\n y0 = 0; \nelse \n y0 = varargin{1}; \nend \n\nif (size(U,2)>2 || size(U,2)<1)\n error('input U must have size 1 or 2'); \nelseif (size(U,2)==2) \n % first coloumn = y\n % second coloumn = u \n X = U(:,1); \n U = U(:,2); \n Y = X./(1+X.^2) + U.^3; \nelse % size(U,2)=1 \n % step1 \n X = y0; \n % steps \n for ii=1:length(U)\n Y(ii) = X(ii)/(1+X(ii).^2) + U(ii).^3; \n X(ii+1) = Y(ii); \n end \n \n X = X(1:end-1); \n X = X'; Y = Y'; \nend \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-demos/system/demo_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7925427875741721}} {"text": "function f = mckinnon ( x )\n\n%*****************************************************************************80\n%\n%% MCKINNON computes the McKinnon function.\n%\n% Discussion:\n%\n% This function has a global minimizer:\n%\n% X* = ( 0.0, -0.5 ), F(X*) = -0.25.\n%\n% There are three parameters, TAU, THETA and PHI.\n%\n% 1 < TAU, then F is strictly convex.\n% and F has continuous first derivatives.\n% 2 < TAU, then F has continuous second derivatives.\n% 3 < TAU, then F has continuous third derivatives.\n%\n% However, this function can cause the Nelder-Mead optimization\n% algorithm to \"converge\" to a point which is not the minimizer\n% of the function F.\n%\n% Sample parameter values which cause problems for Nelder-Mead \n% include:\n%\n% TAU = 1, THETA = 15, PHI = 10;\n% TAU = 2, THETA = 6, PHI = 60;\n% TAU = 3, THETA = 6, PHI = 400;\n%\n% To get the bad behavior, we also assume the initial simplex has the form\n%\n% X1 = (0,0),\n% X2 = (1,1),\n% X3 = (A,B), \n%\n% where \n%\n% A = (1+sqrt(33))/8 = 0.84307...\n% B = (1-sqrt(33))/8 = -0.59307...\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Ken McKinnon,\n% Convergence of the Nelder-Mead simplex method to a nonstationary point,\n% SIAM Journal on Optimization,\n% Volume 9, Number 1, 1998, pages 148-158.\n%\n% Parameters:\n%\n% Input, real X(2), the argument of the function.\n%\n% Output, real F, the value of the function at X.\n%\n if ( length ( x ) ~= 2 )\n error ( 'Error: function expects a two dimensional input\\n' );\n end\n\n tau = 2.0;\n theta = 6.0;\n phi = 60.0;\n\n if ( x(1) <= 0.0 )\n f = theta * phi * abs ( x(1) ).^tau + x(2) * ( 1.0 + x(2) );\n else\n f = theta * x(1).^tau + x(2) * ( 1.0 + x(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/nelder_mead/mckinnon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8596637523076224, "lm_q1q2_score": 0.7925427838858197}} {"text": "function [xi,w]=secondOrderPrismCubPoints()\n%%SECONDORDERPRISMCUBPOINTS Generate second-order cubature points for\n% integration over a standard prism in 3D. This is a triangle that has\n% been extruded upward. The vertices are (1,-1,-1), (-1,-1,-1), (-1,1,-1),\n% (1,-1,1), (-1,-1,1), and (-1,1,1).\n% \n%INPUTS: None\n%\n%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard prism.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard prism (4).\n%\n%This function implements the points given in [1] (5 points).\n%\n%EXAMPLE:\n%We compare a 2nd-order moment computed using these cubature points\n%to one computed using monomialIntPrism. The results are the same within\n%typical finite precision limits.\n% [xi,w]=secondOrderPrismCubPoints();\n% alpha=[2;0;0];\n% theMoment=findMomentFromSamp(alpha,xi,w);\n% intVal=monomialIntPrism(alpha);\n% RelErr=(theMoment-intVal)/intVal\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=[-0.33333333333333333333333333333333333333, -0.33333333333333333333333333333333333333, -0.99999999999999985119303811076522004183, 0.66666666666666686507594918564641756458;\n-0.33333333333333333333333333333333333333, -0.33333333333333333333333333333333333333, 0.99999999999999985119303811076522004183, 0.66666666666666686507594918564641756458;\n-0.74158162379719638007464124598498266439, 0.48316324759439276014928249196996532878, 0, 0.88888888888888875661603387623572162361;\n 0.48316324759439276014928249196996532878, -0.74158162379719638007464124598498266439, 0, 0.88888888888888875661603387623572162361;\n-0.74158162379719638007464124598498266439, -0.74158162379719638007464124598498266439, 0, 0.88888888888888875661603387623572162361];\n\nw=M(:,4);\nxi=M(:,1:3)';\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Prism/secondOrderPrismCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.7924536903934691}} {"text": "function variance = f_variance ( m, n )\n\n%*****************************************************************************80\n%\n%% F_VARIANCE returns the variance of the F central PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the parameters of the PDF.\n% 1 <= M,\n% 1 <= N.\n% Note, however, that the variance is not defined unless 5 <= N.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n if ( n < 5 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'F_VARIANCE - Fatal error!\\n' );\n fprintf ( 1, ' The variance is not defined for N < 5.\\n' );\n error ( 'F_VARIANCE - Fatal error!' );\n end\n\n variance = 2 * n * n * ( m + n - 2 ) / ( m * ( n - 2 )^2 * ( n - 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/prob/f_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7924384515751997}} {"text": "function [P,varargout] = laplace(xs,A,b,AEq,bEq,varargin)\n% LAPLACE Smooth compact 1,2 or 3 dimensional atomic probability distribution subject to linear and moment constraints \n% \n% LAPLACE('demo') or LAPLACE() runs univariate, bivariate and trivariate examples\n%\n% P = LAPLACE({xs1,xs2},[],[],[],[],[mu1 mu2],[mu11,mu12,mu22]) returns an\n% matrix of size length(xs1) x length(xs2). The value P(i,j) is interpreted \n% as a probability assigned to lattice point (xs1(i), xs2(j)). This 2d atomic\n% probability minimizes the square of the discrete laplacian assuming zero\n% boundary condition, subject to moment constraints E[x1]=mu1, E[x2]=mu2,\n% E[x1.*x2] = mu11, E[x1.*x2]=mu12, E[x2.*x2]=mu22 where E denotes the expectation\n% operator E(f) = sum(sum(f.*P)) and x1,x2,x3 are arrays of n-d coordinates \n% function generated by [x1,x2,x3] = ndgrid(xs{:}). \n% \n% P = LAPLACE({xs1,xs2},A,b,AEq,bEq) returns a matrix of size length(xs1) x length(xs2). \n% The value P(i,j) is interpreted as a probability assigned to lattice point (xs1(i), xs2(j)).\n% The 2-d atomic probability minimizes the square of the discrete laplacian subject to inequality\n% constraint A*P(:) < b and/or equality constraint AEq*P(:) = bEq. Supplied vectors\n% b and bEq should be of length length(xs1) x length(xs2). A,b, AEq and bEq\n% may be empty. In particular ...\n%\n% P = LAPLACE(xs1,[],[],[f1;f2;...],[Ef1;Ef2;...]) where f1,f2,... are row vectors\n% of size 1 x length(xs1) representing functions on grid points xs1, and Ef1, Ef2\n% are scalars representing their means returns a smooth compact probability\n% distribution with E[f1] = Ef1, E[f2] = Ef2 and so forth. \n%\n% P = LAPLACE(xs1,[],[],[],[],mu1,mu11,mu111,mu1111) returns a\n% vector of size length(xs1) x 1. The element P(i) is interpreted \n% as a probability assigned to lattice point xs1(i). The 1-d atomic\n% probability minimizes the square of the discrete laplacian assuming zero\n% boundary condition, subject to moment constraints E[x1]=mu1,\n% E[x1.*x1]=mu11, E[x1.*x1.*x1] = mu111 and E[x1.*x1.*x1.*x1]=mu1111.\n% Addtional moment constraints may be supplied. \n% \n% P = LAPLACE({xs1,xs2,xs3},[],[],[],[],varargin) returns an\n% matrix of size length(xs1) x length(xs2) x length(xs3). The value P(i,j,k) is interpreted \n% as a probability assigned to lattice point (xs1(i), xs2(j), xs3(j)). The 3d atomic\n% probability minimizes the sums squares of projections of the discrete laplacian assuming zero\n% boundary condition, subject to moment constraints contained in varargin.\n% Each constraint should be a vector of length NCHOOSEK(K+2,2) and contain\n% moment values (as defined above) for all polynomials in x1, x2 and x3 of\n% degree k sorted by reverse lexicographic ordering of their coefficients. \n% For example, P = LAPLACE({xs1,xs2,xs3},[],[],[],[],[mu11,mu12,mu13,mu22,mu23,mu33])\n% minimizes E[x1.^2] = mu11, E[x1.x2]= mu12 and so forth. The degree of the\n% implied polynomials is inferred from the length of the moment vector. \n% \n% P = LAPLACE(...,A,b,AEq,bEq,...) applies additional user supplied\n% inequality and equality constraints on P(:), as per the convention in\n% most optimization functions including QUADPROG\n%\n% \n% ARGUMENTS:\n% xs n x 1 cell array of vectors - Lattice points at which the probability distribution is supported (compatible with ndgrid(xs{:}))\n% A,b,AEq,bEq - Inequality and equality constraints (can be empty), as per QUADPROG \n% varargin - Listing of desired values for moments (see explanation below)\n% P m1 x m2 x ... x mn - Lattice point probabilities (n-dimensional)\n% varargout - Evaluation of moments inferred by P in the same order as they are supplied\n%\n% MOMENT CONSTRAINTS: \n% If varargin{i} has length nchoosek(k+n-1,n-1) is it intepreted as a set of moment\n% constraints on polynomials of degreee k in the n coordinate functions, listed by \n% reverse lexicographic ordering. [A shortcoming of this convention is\n% that *all* degree k moments must be supplied]. \n%\n% if n=2 then [0.1 0.3] means E[x1]=0.1 and E[x2]=0.3\n% if n=2 then [0.5 0.2 0.1] means E[x1.^2] = 0.5, E[x1.*x2] = 0.2 and E[x2.*x2] = 0.1\n% if n=3 then [0.5 0.2 0.1] means E[x1] = 0.5, E[x2] = 0.2 and E[x3] = 0.1\n%\n% LIMITATIONS:\n% The discrete laplacian and implicit boundary condition may not be the most sensible\n% objective function, especially in the 3-d case as currently implemented (I'm hoping someone\n% improves this). One might also replace the atomic measure with mixture of gaussians\n% centred at the lattice points. \n%\n% RELATED:\n% ksdensity.m - stats toolbox\n%\n% Peter Cotton\n\nmomentConstraintMultiplier = 1;\n\nif nargin==0 || ischar(xs) && strcmpi(xs,'demo'),\n laplaceDemo;\nelse\n \n %% Limitations and checks\n [m,n,xs] = laplaceArgChecks(xs,A,b,AEq,bEq,varargin{:});\n \n %% Establish grid points\n X = cell(n,1);\n switch n\n case 1,\n if ~iscell(xs),\n error('laplace: Violation of programmer intent - xs should have been set to cell by laplaceArgChecks');\n elseif iscell(xs),\n X = xs;\n else\n error('Not sure how to interpret xs');\n end\n otherwise\n [X{:}] = ndgrid(xs{:});\n end\n \n %% Ensure probs add to one.\n if isempty(AEq),\n AEq = ones(1,prod(m));\n bEq = 1;\n else\n AEq = [AEq;ones(1,prod(m))];\n bEq = [bEq;1];\n end\n \n %% Interpret additional arguments as equality constraints\n nsumk_ = nan(n,1);\n for k=1:10,\n nsumk_(k) = nsumk(n,k);\n end\n nArgs = length(varargin);\n moments = cell(nArgs,1);\n for argNo=1:length(varargin),\n arg_ = varargin{argNo};\n if isvector(arg_),\n switch n\n case 1,\n degree_ = argNo;\n expon = degree_;\n nExpon= 1;\n otherwise\n degree_ = find(nsumk_==length(arg_),1);\n if isempty(degree_),\n error([num2str(k),'th argument appears to have the wrong number of moments']);\n else\n [~,expon] = nsumk(n,degree_); % Listing of all non-negs adding to degree_\n nExpon = size(expon,1);\n expon = expon(nExpon:-1:1,:); % Reverse lexicographic ordering is more natural for moments\n end\n end\n moments_ = nan(prod(m),nExpon);\n for i=1:nExpon,\n % Tabulate pointwise value of polynomial in x1, x2 and x3\n xi = X{1}(:);\n moments_(:,i) = xi.^expon(i,1);\n for j=2:n,\n xj = X{j}(:);\n moments_(:,i) = moments_(:,i).*(xj.^expon(i,j));\n end\n end\n AEq = [AEq;momentConstraintMultiplier*moments_'];\n bEq = [bEq;momentConstraintMultiplier*arg_(:)];\n moments{argNo} = moments_;\n end\n end\n \n %% Optimize discrete laplacian\n switch n\n case 1,\n f = @(p) del(p,xs);\n otherwise\n unrol = @(P) P(:);\n f = @(p) unrol(del(reshape(p,m'),xs));\n end\n [C,shouldBeZero] = inferAffineMap(f,prod(m));\n if any(abs(shouldBeZero)),\n error('laplace: Violation of programmer intent (bug). Discrete laplacian should not have constant term');\n end\n H = full(C'*C);\n options = optimset('LargeScale','off','MaxIter',500,'TolX',1e-2,'MaxFunEvals',1000);\n lb = zeros(prod(m),1);\n ub = ones(prod(m),1);\n p = quadprog(H,zeros(prod(m),1),A,b,AEq,bEq,lb,ub,zeros(prod(m),1),options);\n if n>1,\n P = reshape(p,m');\n else\n P = p;\n end\n \n %% Return moments implied by the atomic measure\n vargout = cell(length(varargin),1);\n for argNo=1:length(varargin),\n if ~isempty(moments{argNo}),\n vargout{argNo} = (p'*moments{argNo})';\n end\n end\n varargout = cell(length(varargin),1);\n [varargout{:}] = vargout{:};\nend\n\nend\n\nfunction L = del(P,xs)\n% function L = del(P,xs)\n%\n% Augmented discrete laplacian for 1 or 2 dimensions\n% Projected, augmented discrete laplacian for 3 dimensions\n\n% Tabulate grid steps\nhs = cell(1,length(xs));\nfor dimNo=1:length(xs),\n hs{dimNo} = xs{dimNo}(2)-xs{dimNo}(1);\nend\n\nif isvector(P),\n L = del1augmented(P,hs);\nelseif length(size(P))==2,\n L = del2augmented(P,hs);\nelseif length(size(P))==3,\n L = del3augmented(P,hs);\nelse\n error('laplace is not implemented for dimension four'); % TODO: \nend\n\n function d = del1augmented(P,hs)\n d = del2([0;0;P(:);0;0],hs{:});\n end\n\n function d = del2augmented(P,hs)\n % Enlarges the area and then computes del2\n P_ = zeros(size(P)+4);\n P_(3:end-2,3:end-2) = P;\n d = del2(P_,hs{:});\n end\n\n function d = del3augmented(P,hs)\n % Enlarges the area and then computes del2\n P_ = zeros(size(P)+4);\n P_(3:end-2,3:end-2,3:end-2) = P;\n d = del3(P_,hs{:});\n end\n function L = del3(X,varargin)\n % FIXME: For now this returns the laplacians of 2-d marginals\n L = zeros(0,1);\n for k=1:3,\n idx_ = setdiff(1:3,k);\n d_ = del2(squeeze(sum(X,k)),varargin{idx_});\n if k==1,\n L = d_(:);\n else\n L = [L;d_(:)];\n end\n end\n end\n\nend\n\nfunction [m,n,xs] = laplaceArgChecks(xs,A,b,AEq,bEq,varargin)\n% function [n,m,xs] = laplaceArgChecks(xs,A,b,AEq,bEq,varargin)\n% \n% Ensure arguments make sense, and infer dimension where necessary\n\n%% Allow passing of single vector for lattice rather than cell array\nif ~iscell(xs) && isvector(xs),\n % Try to infer dimension\n if ~isempty(A),\n n_ = log(size(A,2))/log(length(xs));\n n = round(n_);\n if abs(n-n_)>1e-6,\n error('error infering dimension of problem, A looks to be inconsistent');\n end\n elseif ~isempty(AEq),\n n_ = log(size(AEq,2))/log(length(xs));\n n = round(n_);\n if abs(n-n_)>1e-6,\n error('error infering dimension of problem, AEq looks to be inconsistent');\n end\n else\n n = length(varargin{1});\n if n>3,\n error('inferred dimension exceeds 3 - better to be explicit');\n end\n end\n oldLattice = xs;\n xs = cell(n,1);\n for k1=1:n,\n xs{k1} = oldLattice;\n end\nend\n\n%% Check dimensions\nn = length(xs);\nm = nan(n,1);\nfor k2=1:n,\n latticeValues = xs{k2};\n m(k2) = length(latticeValues);\n if ~isvector(latticeValues) || any(any(diff(latticeValues)1e-6)),\n error(['laplace anticipates an evenly spaced vector of support points in increasing order: e.g. (-4:0.5:3). Problem with lattice{',num2str(k2),'}']);\n end\nend\nif ~isempty(A) && size(A,2)~=prod(m),\n error('laplace anticipates size(A,2)=prod(m), where m(k) is the number of lattice points in dimension k');\nend\nif ~isempty(AEq) && size(AEq,2)~=prod(m),\n error('laplace anticipates size(AEq,2)=prod(m), where m(k) is the number of lattice points in dimension k');\nend\nif ~isempty(b) && size(b,1)~=size(bEq,1),\n error('laplace anticipates size(b,1)=prod(m), where m(k) is the number of lattice points in dimension k');\nend\nif ~isempty(bEq) && size(bEq,1)~=size(AEq,1),\n error('laplace anticipates size(bEq,1)=prod(m), where m(k) is the number of lattice points in dimension k');\nend\n\n\nend\n\nfunction [A,b] = inferAffineMap(f,n)\n% f function_handle\n% A m x n\n%\n% Deduce affine mapping given its function handle\n\nb = feval(f,zeros(n,1));\nm = length(b);\nA = sparse(m,n);\nfor k=1:n,\n ek = zeros(n,1);\n ek(k) = 1;\n A(:,k) = feval(f,ek)-b;\nend\nend\n\nfunction [m,x] = nsumk(n,k)\n% NSUMK Number and listing of non-negative integer n-tuples summing to k\n% M = NSUMK(N,K) where N and K are positive integers returns M=nchoosek(K+N-1,N-1)\n% This is the number of ordered N-tuples of non-negative integers summing to K\n%\n% [M,X] = NSUMK(N,K) produces a matrix X with\n% nchoosek(K+N-1,N-1) rows and n columns. Each row comprises\n% non-negative integers summing to k. The ordering of rows follows the\n% same convention as NCHOOSEK, which is undocumented but with some\n% reliability appears to be lexicographic. The reverse of this presumed ordering\n% is a natural way to list coefficients of polynomials in N variables of degree K.\n% As per nchoosek, this syntax is only practical for situations where N is\n% less than about 15.\n% \n% EXAMPLES: m = nsumk(5,2) \n% [~,x] = nsumk(5,2) returns a 15 x 5 matrix x in which rows sum to 2\n\n\nif isscalar(n) && isscalar(k) && nargout<=1\n m = nchoosek(k+n-1,n-1);\nelseif isscalar(n) && isscalar(k) && nargout==2,\n m = nchoosek(k+n-1,n-1);\n dividers = [zeros(m,1),nchoosek((1:(k+n-1))',n-1),ones(m,1)*(k+n)];\n x = diff(dividers,1,2)-1;\nelse\n error('nsumk anticipates scalar k and n');\nend\nend\n\nfunction [y,expon] = kmoments(x,k)\n% KMOMENTS - Evaluate sample mean of all k'th degree polynomials in N-variables \n% Y = KMOMENTS(X,K) where X is an NSAMPLES by N matrix produces a NSUMK(N,K) x 1\n% vector Y comprising sample means for all K-degree polynomials in N variables\n% Samples for the j'th variable comprise the j'th column of X, and the\n% implied listing of k-degree polynomials follows reverse lexicographic ordering\n% \n% [Y,expon] = KMOMENTS(X,K) also returns the reverse-lex ordered polynomial exponents\n% in a matrix of size NCHOOSEK(K+N-1,N-1) x N\n\n\n%% Generate reverse lex ordering\nn = size(x,2);\nswitch n\n case 1,\n expon = k; m=1;\n otherwise\n [~,expon] = nsumk(n,k);\n m = size(expon,1);\n expon = expon(m:-1:1,:);\nend\n\ny = ones(m,1);\n\n%% Compute k-th degree polys for a sample x\nfor i=1:m,\n ys = ones(size(x,1),1);\n for j=1:n,\n ys = ys.*x(:,j).^expon(i,j);\n end\n y(i) = mean(ys);\nend\n\nend\n\n\nfunction laplaceDemo\nclose all;\n\n%% UNIVARIATE EXAMPLE: \n% An example motivated by finance\n% We are inferring a risk-neutral density from market prices\n% Prices of call options are linear constraints on the atomic density\n% We throw in a few moment constraints as well \n% Don't take this too seriously in the tails\n\nmatchExactMoments = true; % <-- Set to false to verify the dangers in fitting the wrong moments \ncompareShortAndLongSample = false; % <-- Set to true to use moments and 'prices' from 'true' distribution\nxs = (-5:0.05:5)';\n\n% Generate an imagined risk-neutral density sample\nshortSample_ = [-0.1+0.2*randn(10,1);0.3*randn(50,1);0.5+0.5*randn(100,1)];\nif compareShortAndLongSample,\n longSample_ = [-0.1+0.2*randn(10*10000,1);0.3*randn(50*10000,1);0.5+0.5*randn(100*10000,1)];\nelse\n longSample_ = shortSample_;\nend\npShort = hist(shortSample_,xs);pShort = pShort/sum(pShort);\npLong = hist(longSample_,xs);pLong = pLong/sum(pLong);\n \n% Generate imagined market prices for securities based on the risk-neutral density sample\nstrikes = [-1:0.5:1];\nsecurity = @(x) max(0,x*ones(1,length(strikes))-ones(size(x,1),1)*strikes); % (Call option) Takes column vector x of length nSamples -> nSamples x nStrikes matrix\nsecurityMarketPrice = mean(security(longSample_))';\nsecurityPayoff = security(xs)';\n\n% Infer the density subject to price and moment constraints\nallMoments = cell(5,1);\nfor mNo=1:length(allMoments),\n if matchExactMoments,\n allMoments{mNo} = kmoments(longSample_,mNo);\n else\n allMoments{mNo} = kmoments(shortSample_,mNo);\n end\nend\nfor nMomentsUsed = 0:5,\n P = laplace(xs,[],[],securityPayoff,securityMarketPrice,allMoments{1:nMomentsUsed});\n subplot(2,3,nMomentsUsed+1);plot(xs,P,xs,pLong,xs,pShort);legend('laplace','long sample','short sample');ylabel(['Matched ',num2str(nMomentsUsed), ' moments']);\n grid; plotxs = axis;axis([-2,2,plotxs(3),plotxs(4)]);\n drawnow; pause(1);\nend\n\n\n%% BIVARIATE EXAMPLE\n% Inferring a bivariate distribution from moments\nfigure;\nxs = {(-4:0.5:4)',(-4:0.5:4)};\nsample_ = mvnrnd([-0.1 0.3],[1.2,0.5;0.5,0.98],500);\nsample_(:,1) = sample_(:,1);\nsample_(:,2) = -0.5+sample_(:,2)+0.5./(1+abs(sample_(:,1)));\npEmpirical = hist3(sample_,xs);\npEmpirical = pEmpirical/sum(pEmpirical(:));\nmoments1 = kmoments(sample_,1);\nmoments2 = kmoments(sample_,2);\nmoments3 = kmoments(sample_,3);\nmoments4 = kmoments(sample_,4);\n[P,m1,m2,m3,m4] = laplace(xs,[],[],[],[],moments1,moments2,moments3,moments4);\nsubplot(1,2,1);surf(pEmpirical);zlabel('Empirical');\nsubplot(1,2,2);surf(P);zlabel('Laplace minimizing');\nbivariateMomentComparison = [[moments1;moments2;moments3;moments4],[m1;m2;m3;m4]],\ndrawnow; pause(1);\n\n\n%% TRIVARIATE EXAMPLE\n% Inferring a tri-variate distribution from moments\nfigure;\ndisp('Trivariate example takes a little while...');\nnTrivariateMomentsToUse = 3; \nxs = {(-3:1:3)',(-3:1:3),(-3:1:3)};\nsample_ = mvnrnd([-0.1 0.3 0.1],[1.2,0.5,0.2;0.5,0.98,0.35;0.2,0.35,1.2],50);\ntriMoments = cell(nTrivariateMomentsToUse,1);\nfor mNo=1:length(triMoments),\n triMoments{mNo}= kmoments(sample_,mNo);\nend\nP = laplace(xs,[],[],[],[],triMoments{:});\nPxy = squeeze(sum(P,3));\npxyEmpirical = hist3(sample_(:,[1:2]),xs(1:2)); pxyEmpirical = pxyEmpirical/sum(pxyEmpirical(:));\nsubplot(1,2,1);surf(pxyEmpirical);zlabel('Empirical (xy projection)');\nsubplot(1,2,2);surf(Pxy);zlabel('Laplace minimizing (xy projection)');\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/28400-laplace-m/laplace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7924384511718943}} {"text": "function [Q,Z,QAZ,QBZ]=HessenbergTriRed(A,B)\n%%HESSENBERGTRIRED Perform a Hessenberg triangular reduction. Given A and\n% B, two nXn matrices, find orthogonal matrices Q and Z such\n% that Q'*A*Z is an upper Hessenberg matrix and Q'*B*Z is an\n% upper triangular matrix. An upper Hessenberg matrix has zero\n% entries below the first subdisgonal and is thus almost upper\n% triangular. This implementation is only for real matrices.\n%\n%INPUTS: A, B Two nXn real matrices.\n%\n%OUTPUTS Q,Z Orthogonal nXn matrices such that Q'*A*Z is upper Hessenberg\n% and Q'*B*Z is lower triangular.\n% QAZ The matrix Q'*A*Z.\n% QBZThe matrix Q'*B*Z\n%\n%This implements algorithm 7.7.1 in Chapter 7.7.4 of [1], modified to\n%obtain the Q and Z matrices explicitly. This is similar to the hess\n%function in Matlab.\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(A,1);\n\n%The initial upper triangularization. We are just using qr and not\n%Algorithm 5.2.1.\n%Make B upper triangular\n[Q,B]=qr(B,0);\nA=Q'*A;%Adjust A accordingly\n\nZ=eye(n,n);\nfor j=1:(n-2)\n for i=n:-1:(j+2)\n %Zero A(i,j)\n [c,s]=GivensCS(A(i-1,j),A(i,j));\n A((i-1):i,j:n)=[c, s;-s,c]'*A(i-1:i,j:n);\n B((i-1):i,(i-1):n)=[c, s;-s,c]'*B(i-1:i,i-1:n);\n %Store the transformation\n Q(:,(i-1):i)=Q(:,(i-1):i)*[c,s;-s,c];\n %Zero B(i,j)\n [c,s]=GivensCS(-B(i,i),B(i,i-1));\n B(1:i,i-1:i) = B(1:i,i-1:i)*[c,s;-s,c];\n A(1:n,i-1:i) = A(1:n,i-1:i)*[c,s;-s,c];\n Z(:,(i-1):i) = Z(:,(i-1):i)*[c,s;-s,c];\n end\nend\n\n%Save the results.\nQAZ=A;\nQBZ=B;\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/HessenbergTriRed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7923369644847426}} {"text": "function [ x, w ] = jacobi_ek_compute ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% JACOBI_EK_COMPUTE: Elhay-Kautsky method for Gauss-Jacobi quadrature rule.\n%\n% Discussion:\n%\n% The integral:\n%\n% integral ( -1 <= x <= 1 ) (1-x)^alpha * (1+x)^beta * 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% 09 June 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Input, real ALPHA, BETA, the exponents of (1-X) and\n% (1+X) in the quadrature rule. For simple Gauss-Legendre quadrature,\n% set ALPHA = BETA = 0.0. -1.0 < ALPHA and -1.0 < BETA are required.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = 2.0^( alpha + beta + 1.0 ) ...\n * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) ...\n / gamma ( 2.0 + alpha + beta );\n%\n% Define the Jacobi matrix.\n%\n x(1) = ( beta - alpha ) / ( 2.0 + alpha + beta );\n\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( 3.0 + alpha + beta ) * ( 2.0 + alpha + beta )^2 );\n\n for i = 2 : n\n abi = 2.0 * i + alpha + beta;\n x(i) = ( beta + alpha ) * ( beta - alpha ) / ( ( abi - 2.0 ) * abi );\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) ...\n * ( i + alpha + beta ) ...\n / ( ( abi - 1.0 ) * ( abi + 1.0 ) * abi * abi );\n end\n\n bj(1:n) = sqrt ( bj(1:n) );\n\n w = zeros(n,1);\n\n w(1) = sqrt ( zemu );\n w(2:n) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\n\n w(1:n) = w(1:n).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/jacobi_ek_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7923071730886568}} {"text": "function [ res, jac ] = opt14_rj ( x, flag )\n\n%*****************************************************************************80\n%\n%% OPT14_RJ evaluates RES and JAC for test case #14.\n%\n% Modified:\n%\n% 07 January 2008\n%\n% Author:\n%\n% Jeff Borggaard,\n% Gene Cliff,\n% Virginia Tech.\n%\n% Reference:\n%\n% John Dennis, Robert Schnabel,\n% Numerical Methods for Unconstrained Optimization \n% and Nonlinear Equations,\n% SIAM, 1996,\n% ISBN13: 978-0-898713-64-0,\n% LC: QA402.5.D44.\n%\n% Parameters:\n%\n% Input, real X(3), the evaluation point.\n%\n% Input, string FLAG, indicates what must be computed.\n% 'f' means only the value of RES is needed,\n% 'g' means only the value of JAC is needed,\n% 'all' means RES and JAC are needed.\n% It is acceptable to behave as though FLAG was 'all'\n% on every call.\n%\n% Output, real RES(3,1), the function column vector.\n%\n% Output, real JAC(3,3), the Jacobian matrix.\n%\n n = length ( x );\n\n if ( n ~= 3 )\n fprintf ( '\\n' );\n fprintf ( 'OPT14_RJ - Fatal error!\\n' );\n fprintf ( ' The input vector X should have length 3.\\n'), \n fprintf ( ' Instead, it has length = %d.\\n', n );\n keyboard\n end\n\n res = zeros(n,1);\n\n res(1,1) = x(1)^2*x(2) + x(1)*x(2)^2;\n res(2,1) = 3 * x(1) * x(2)^2 * x(3) - x(1) * x(3) - 1;\n res(3,1) = x(1)*x(3) - 2;\n\n jac = zeros(n,n);\n\n jac(1,1) = 2 * x(1) * x(2) + x(2)^2;\n jac(1,2) = x(1)^2 + 2 * x(1) * x(2);\n jac(1,3) = 0;\n\n jac(2,1) = 3 * x(2)^2 * x(3) - x(3);\n jac(2,2) = 3 * 2 * x(1) * x(2) * x(3);\n jac(2,3) = 3 * x(1) * x(2)^2 - x(1);\n\n jac(3,1) = x(3);\n jac(3,2) = 0;\n jac(3,3) = x(1); \n", "meta": {"author": "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/opt14_rj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.7922811689554539}} {"text": "function f=chi2pdf(x,k)\n\n% f=chi2pdf(x,k)\n%\n% Return the pdf of a chi-squared distribution with k degrees of freedom\n% evaluated at x.\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas \n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nerror(nargchk(2,2,nargin));\nerror(chk_param(x,'x','numeric','real'));\nerror(chk_param(k,'k','scalar','real','integer','>=',1));\n\nf=NaN(size(x));\nf(x<0)=0;\nxgt0=x>=0;\nf(xgt0)=x(xgt0).^(k/2-1).*exp(-x(xgt0)/2)/(2^(k/2)*gamma(k/2));\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/chi2pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.7922811558608323}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters. \n% You should set p to a vector of 0's and 1's\n%\n\np = round(sigmoid(X * theta))\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "Ayatans", "repo": "Machine-Learning-homework", "sha": "4550cfc0426c9da8072dff165130fff40d138c10", "save_path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework", "path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework/Machine-Learning-homework-4550cfc0426c9da8072dff165130fff40d138c10/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7921625631272836}} {"text": "function fx = p49_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P49_FUN evaluates the integrand for problem 49.\n%\n% Discussion:\n%\n% The function is singular at two internal points, 1 and sqrt(2).\n%\n% Interval:\n%\n% 0 <= x <= 3\n%\n% Integrand:\n%\n% x^3 * log ( abs ( ( x^2 - 1 ) * ( x^2 - 2 ) ) )\n%\n% Exact Integral:\n%\n% 61 log ( 2 ) + (77/4) log ( 7 ) - 27 = 52.7408...\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Piessens, Elise de Doncker-Kapenga,\n% Christian Ueberhuber, David Kahaner,\n% QUADPACK: A Subroutine Package for Automatic Integration,\n% Springer, 1983, page 104.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n x = x ( : );\n\n fx(1:n,1) = abs ( ( x(1:n,1).^2 - 1.0 ) .* ( x(1:n,1).^2 - 2.0 ) );\n i = ( fx == 0.0 );\n fx = x.^3 .* log ( fx );\n fx(i) = 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_int/p49_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7921625509073783}} {"text": "% Fig. 6.43 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nnum=86*conv([1 1],[1 2 43.25]);\np=conv([1 2 82],[1 2 101]);\nden=conv([1 0 0],p);\nw=logspace(-1,2,1000);\n[mag,phas]=bode(num,den,w);\nfigure(1)\nloglog(w,mag,w,ones(size(w)));\naxis([.1 100 .01 10])\nxlabel('\\omega (rad/sec)');\nylabel('magnitude');\ntitle('Fig. 6.43 : Bode plot for Example 6.12 (a) magnitude');\nbodegrid;\n%pause;\nfigure(2)\nsemilogx(w,phas,w,-180*ones(size(w)));\nxlabel('\\omega (rad/sec)');\nylabel('phase (deg)');\ntitle('Fig. 6.43 : Bode plot for Example 6.13 (b) phase');\nbodegrid;\n\n% actually, the GMs and PMs are slightly different for the system here\n% than that described in the text, the differences arose from \n% roundoff because the initial design was done by hand. The ideas\n% are unchanged.\n", "meta": {"author": "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_43.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7921610004526553}} {"text": "function y = gskewness(x,n)\n%GSKEWNESS Skewness of a grouped sample.\n% In some scientific works, once the data have been gathered from a \n% population of interest, it is often difficult to get a sense of what \n% the data indicate when they are presented in an unorganized fashion. \n% Assembling the raw data into a meaningful form, such as a frequency \n% distribution, makes the data easier to understand and interpret. It is\n% in the context of frequency distributions that the importance of \n% conveying in a succinct way numerical information contained in the data\n% is encountered.\n% So, grouped data is data that has been organized into groups known as\n% classes. The raw dataset can be organized by constructing a table \n% showing the frequency distribution of the variable (whose values are \n% given in the raw dataset). Such a frequency table is often referred to\n% as grouped data.\n% Here, we developed a m-code to calculate the skewness of a grouped data.\n% One can input the returns or modified vectors n and xout containing the\n% frequency counts and the bin locations of the hist m-function, in a \n% column form matrix.\n% GSKEWNESS(X,0) adjusts the skewness for bias (correction by small sample\n% size). GSKEWNESS(X,1) is the same as GSKEWNESS(X), and does not adjust\n% for bias.\n% If skewness = 0, the data are perfectly symmetrical. But a skewness of \n% exactly zero is quite unlikely for real-world data. Here, we use the \n% Bulmers' rule of thumb criterium (1979), about how we can to\n% interpret the skewness number:\n% - Less than ?1 or greater than +1, the distribution is highly skewed\n% - Between ?1 and ?0.5 or between +0.5 and +1, the distribution is \n% moderately skewed\n% - Between ?0.5 and +0.5, the distribution is approximately symmetric\n%\n% Skewness calculation uses the formula,\n% \n% g1 = m3/m2^1.5, do not adjusted for bias\n%\n% G1 = SQRT(N*(N - 1))/(N - 2) * g1, adjusted for bias\n%\n% where:\n% m2 = second moment of the sample about its mean\n% m3 = third moment of the sample about its mean\n% N = sample size\n% \n% Syntax: function y = gskewness(x,n) \n% \n% Inputs:\n% x - data matrix (Size of matrix must be n-by-2; absolut frequency=\n% column 1, class mark=column 2) \n% n - adjusted for bias = 0 (default), do not adjust for bias = 1 \n% Outputs:\n% y - skewness of the values in x\n%\n% Example: Suppose we have the next frequency table:\n%\n% ----------------\n% MC F\n% ----------------\n% 61 5\n% 64 18\n% 67 42\n% 70 27\n% 73 8 \n% ----------------\n%\n% Taken from: http://www.tc3.edu/instruct/sbrown/stat/shape.htm\n%\n% Where we are interested to get the skewness value adjusted for bias.\n%\n% Data input:\n% x=[61 5;64 18;67 42;70 27;73 8];\n%\n% Calling on Matlab the function: \n% y = gskewness(x,0)\n%\n% Answer is:\n%\n% y = -0.1098\n%\n% Created by A. Trujillo-Ortiz, R. Hernandez-Walls and \n% C.M. Espinosa-Lagunes\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.edu.mx\n%\n% Copyright (C) September 24, 2012.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls and C.M. Espinosa-Lagunes. (2012). \n% gskewness:Skewness of a grouped sample. [WWW document].\n% URL http://www.mathworks.com/matlabcentral/fileexchange/\n% 38319-gskewness\n%\n% References: \n% Bulmer, M. G. (1979), Principles of Statistics. NY:Dover Books on\n% Mathematics. \n% Jayaraman, K. (1999), A Statistical Manual for Foresty Research. Foresty\n% Research Support Programme for Asia and the Pacific. FAO-\n% Corporate Document Repository. Forestry Statistics and Data\n% Collection. \n% URL http://www.fao.org/DOCREP/003/X6831E/X6831E00.HTM\n% PDF ftp://ftp.fao.org/docrep/fao/003/X6831E/X6831E00.pdf \n%\n\nif nargin < 2,\n n = 1; %default\nend\n\nc = size(x,2);\n\nif c ~= 2\n error('stats:gskewness:BadData','X must have two colums.');\nend\n\nmc = x(:,1); %class mark\nf = x(:,2); %absolut frequency\ns = sum(f.*mc);\nm1 = s/sum(f);\nm2 = sum(f.*(mc - m1).^2)/sum(f);\nm3 = sum(f.*(mc - m1).^3)/sum(f);\ng1 = m3/m2^1.5;\n\nif n == 0;\n y = sqrt(sum(f)*(sum(f) - 1))/(sum(f) - 2) * g1; %skewness adjusted for\n %bias\nelse n = 1; %default\n y = g1; %skewness not adjusted for bias\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/38319-gskewness/gskewness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.792043225232639}} {"text": "function u = fem1d_heat_implicit ( x_num, x, t, dt, k_fun, ...\n rhs_fun, bc_fun, element_num, element_node, quad_num, u_old )\n\n%*****************************************************************************80\n%\n%% FEM1D_HEAT_IMPLICIT: finite element method, 1D heat, implicit time steps.\n%\n% Discussion:\n%\n% This program solves\n%\n% dUdT - k * d2UdX2 = f(X,T)\n%\n% over the interval [A,B] with boundary conditions\n%\n% U(A,T) = UA(T),\n% U(B,T) = UB(T),\n%\n% over the time interval [T0,T1] with initial conditions\n%\n% U(X,T0) = U0(X)\n%\n% and specified functions k(X,T) and f(X,T).\n%\n% The code uses the finite element method to approximate the second derivative \n% in space, and an implicit backward Euler approximation to the first \n% derivative in time.\n%\n% For a test function Vi, we write\n%\n% dUdt Vi - k * d2Udx2 * Vi = f(x,t) * Vi\n%\n% Int dUdt Vi - k d2Udx2 * Vi = Int f(x,t) Vi\n% Int dUdt Vi + k dUdx * dVidx = Int f(x,t) Vi\n%\n% Take the backward Euler approximation to the derivative:\n%\n% Int ( U(x,t) - U(x,t-dt) ) / dt Vi + k dUdx dVidx = Int ( f(x,t) Vi )\n%\n% Now, assume the finite element projection:\n%\n% U(x,t) = sum ( uj * Vj )\n% U(x,t-dt) = sum ( u_oldj * Vj )\n% F(x,t) = sum ( fj * Vj ):\n%\n% Then the equation can be rewritten as:\n%\n% Sum ( Int ( Vi Vj ) * ( uj - u_oldj ) / dt + k dVidx dVjdx * uj ) =\n% Sum ( Int ( Vi Vj * fj ) )\n%\n% Carrying the old U to the right hand side, we have:\n%\n% Sum ( Int ( Vi Vj ) * u / dt + k dVidx dVjdx * uj ) =\n% Sum ( Int ( Vi Vj * ( fj + u_oldj / dt ) ) )\n%\n% or, written as a linear system for coefficients \"u\":\n%\n% ( K + M/dT ) * u = b + c\n%\n% where K is the usual stiffness matrix, M is the standard finite element\n% mass matrix, b is the usual right hand side, and c contains additions to \n% the right hand side from the time term.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X_NUM, the number of points to use in the spatial dimension.\n%\n% Input, real X(X_NUM,1), the coordinates of the nodes.\n%\n% Input, real T, the current time.\n%\n% Input, real DT, the size of the time step.\n%\n% Input, real K_FUN(), a function to evaluate the heat conductivity.\n%\n% Input, real RHS_FUN(), a function to evaluate the right hand side.\n%\n% Input, real BC_FUN(), a function to set the Dirichlet conditions.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(2,ELEMENT_NUM), the nodes belonging to \n% each element.\n%\n% Input, integer QUAD_NUM, the number of quadrature points to use.\n%\n% Input, real U_OLD(X_NUM,1), the solution at time T - dt.\n%\n% Output, real U(X_NUM,1), the solution at time T.\n%\n [ a, b ] = assemble_fem ( x_num, x, element_num, element_node, ...\n quad_num, t, k_fun, rhs_fun );\n\n [ a, b ] = assemble_backward_euler ( x_num, x, element_num, ...\n element_node, quad_num, t, dt, u_old, a, b );\n\n [ a, b ] = assemble_bc ( x_num, x, t, bc_fun, a, b );\n\n u = a \\ b;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_heat_implicit/fem1d_heat_implicit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7920432249183708}} {"text": "%% MULTIGRID FOR STOKES EQUATIONS IN 2D\n%\n% This example is to show the convergence of multigrid methods for various\n% finite element approximation of the Stokes equation on the unit square:\n%\n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% u = g_D on \\Gamma.\n%\n% with the pure Dirichlet boundary condition. The solver is based on a DGS\n% type smoother and summarized in the following reference. \n%\n% Reference\n%\n% M. Wang and L. Chen. Multigrid Methods for the Stokes equations\n% using Distributive Gauss-Seidel Relaxations based on the Least Squares\n% Commutator. Journal of Scientific Computing. 56(2): 409-431, 2013.\n\nclear variables; \nclose all;\n\n%% Setting\n% mesh\n[node,elem] = squaremesh([0,1,0,1],0.25);\n% [node,elem] = circlemesh(0,0,1,0.25);\nshowmesh(node,elem);\n[node,elem] = uniformrefine(node,elem);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nfigure; showmesh(node,elem); pause(0.5);\n% pde\npde = Stokesdata2; \n% pde = StokesZulehnerdata;\n% options\noption.L0 = 0;\noption.maxIt = 4;\noption.printlevel = 1;\noption.plotflag = 0;\noption.rateflag = 0;\n\n%% MG options\noption.solver = 'mg';\noption.smoothingstep = 2;\noption.smootherbarSp = 'SGS';\n\n%% RT0-P0\ndisp('RT0-P0')\noption.elemType = 'RT0-P0';\n% option.refType = 'bisect';\nfemStokesHdiv(mesh,pde,option);\n\n%% BDM1B-P0\ndisp('BDM1B-P0')\noption.elemType = 'BDM1B-P0';\nfemStokesHdiv(mesh,pde,option);\n\n%% CR-P0 element\ndisp('CR-P0')\noption.elemType = 'CRP0';\nfemStokes(mesh,pde,option);\n\n%% P2-P0 element\ndisp('P2-P0')\noption.elemType = 'P2P0';\nfemStokes(mesh,pde,option);\n\n%% isoP2-P0 element\ndisp('isoP2-P0')\noption.elemType = 'isoP2P0';\nfemStokes(mesh,pde,option);\n\n%% isoP2-P1 element\ndisp('isoP2-P1')\noption.elemType = 'isoP2P1';\nfemStokes(mesh,pde,option);\n\n%% P1b-P1 element\ndisp('P1b-P0')\noption.elemType = 'P1bP1';\noption.solver = 'asmg';\nfemStokes(mesh,pde,option);\n\n%% P2-P1 element\ndisp('P2-P1')\noption.elemType = 'P2P1';\n% option.smoothingStep = 3;\n% option.smootherbarSp = 'VCYCLE';\n% option.smootherbarSpPara = 0.75;\nfemStokes(mesh,pde,option);\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/solver/Stokesmgrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7919809377306731}} {"text": "function [ x, seed ] = hypersphere_uniform_sample ( m, n, r, c, seed )\n\n%*****************************************************************************80\n%\n%% HYPERSPHERE_SURFACE_UNIFORM samples hypersphere surface.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Russell Cheng,\n% Random Variate Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998, pages 168.\n%\n% George Marsaglia,\n% Choosing a point from the surface of a sphere,\n% Annals of Mathematical Statistics,\n% Volume 43, Number 2, April 1972, pages 645-646.\n%\n% Reuven Rubinstein,\n% Monte Carlo Optimization, Simulation, and Sensitivity\n% of Queueing Networks,\n% Wiley, 1986, page 234.\n%\n% Parameters:\n%\n% Input, integer M, the dimension of the space.\n%\n% Input, integer N, the number of points.\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real C(M,1), the center of the sphere.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Output, real X(M,N), the points.\n%\n [ x, seed ] = r8mat_normal_01 ( m, n, seed );\n\n v(1,1:n) = sqrt ( sum ( x.^2, 1 ) );\n vv = repmat ( v, m, 1 );\n x = x ./ vv;\n%\n% Scale by the sphere radius.\n%\n x = r * x;\n%\n% Shift to the sphere center.\n%\n x = x + repmat ( c, 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/hypersphere_properties/hypersphere_surface_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7919434666963686}} {"text": "function [parent_pop] = srn(parent_pop)\n% This procedure implements srn (Srinivas and Deb's) function.\n% The canonical srn function is defined as below --\n% f1 = 2.0 + ((x_1 - 2.0)^2.0) + ((x_2 - 1.0)^2.0)\n% f2 = (9.0 * x_1) - ((x_2 - 1.0) ^ 2.0)\n% s.t.\n% c_1(x) = 1.0 - ((x_1^2.0) + (x_2^2.0))/225.0\n% c_2(x) = (3.0 * x_2/10.0) - (x_1/10.0) - 1.0\n% where\n% -20.0 <= x_i <= 20.0 (i = 1,2)\n\nglobal nreal ;\nglobal ncon ;\nglobal nobj ;\n\ncindex = nreal + nobj + 1 : nreal + nobj + ncon ;\n\nx = parent_pop(:,1:nreal);\nf1 = 2.0 + ((x(:,1) - 2.0) .^ 2.0) + ((x(:,2) - 1.0) .^ 2.0);\nf2 = (9.0 .* x(:,1)) - ((x(:,2) - 1.0) .^ 2.0);\n\nc = parent_pop(:,cindex) ;\nc(:,1) = 1.0 - (((x(:,1) .^ 2.0) + (x(:,2) .^ 2.0)) ./ 225.0);\nc(:,2) = (3.0 .* (x(:,2) ./ 10.0)) - (x(:,1) ./ 10.0) - 1.0 ;\n\nparent_pop(:, (nreal+1)) = f1 ;\nparent_pop(:, (nreal+2)) = f2 ;\nparent_pop(:, cindex) = c ;\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/problemdef/srn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7919346334265895}} {"text": "function [dSP,sp]=grShortPath(E,s,t)\n% Function dSP=grShortPath(E) solve the task about\n% the shortest path between any vertexes of digraph.\n% Input parameter: \n% E(m,2) or (m,3) - the arrows of digraph and their weight;\n% 1st and 2nd elements of each row is numbers of vertexes;\n% 3rd elements of each row is weight of arrow;\n% m - number of arrows.\n% If we set the array E(m,2), then all weights is 1.\n% Output parameter:\n% dSP(n,n) - the matrix of shortest path.\n% Each element dSP(i,j) is the shortest path \n% from vertex i to vertex j (may be inf,\n% if vertex j is not accessible from vertex i).\n% Uses the algorithm of R.W.Floyd, S.A.Warshall.\n% [dSP,sp]=grShortPath(E,s,t) - find also\n% the shortest paths from vertex s (source) to vertex t (tail).\n% In this case output parameter sp is vector with numbers \n% of vertexes, included to shortest path from s to t.\n% Author: Sergiy Iglin\n% e-mail: siglin@yandex.ru\n% personal page: http://iglin.exponenta.ru\n% Acknowledgements to Prof. Gerard Biau \n% (Universite Montpellier II, France)\n% for testing of this algorithm.\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% ================ Initial values ===============\ndSP=ones(n)*inf; % initial distances\ndSP((E(:,2)-1)*n+E(:,1))=E(:,3);\n\n% ========= The main cycle of Floyd-Warshall algorithm =========\nfor j=1:n,\n i=setdiff((1:n),j);\n dSP(i,i)=min(dSP(i,i),repmat(dSP(i,j),1,n-1)+repmat(dSP(j,i),n-1,1));\nend\nsp=[];\nif (nargin<3)|(isempty(s))|(isempty(t)),\n return\nend\ns=s(1);\nt=t(1);\nif (~(s==round(s)))|(~(t==round(t)))|(s<1)|(s>n)|(t<1)|(t>n),\n error(['s and t must be integer from 1 to ' num2str(n)])\nend\nif isinf(dSP(s,t)), % t is not accessible from s\n return\nend\ndSP1=dSP;\ndSP1(1:n+1:n^2)=0; % modified dSP\nl=ones(m,1); % label for each arrow\nsp=t; % final vertex\nwhile ~(sp(1)==s),\n nv=find((E(:,2)==sp(1))&l); % all labeled arrows to sp(1)\n vnv=abs((dSP1(s,sp(1))-dSP1(s,E(nv,1)))'-E(nv,3))0\n ROT = eye(4);\n else\n ROT = -1*eye(4); ROT(end)=1;\n end\nelse\n a=normalizeVector3d(A);\n b=normalizeVector3d(B);\n a=reshape(a,3,1);\n b=reshape(b,3,1);\n \n v = cross(a,b);\n ssc = [0 -v(3) v(2); v(3) 0 -v(1); -v(2) v(1) 0];\n ROT = eye(3) + ssc + ssc^2*(1-dot(a,b))/(norm(v))^2;\n \n ROT = [ROT, [0;0;0]; 0 0 0 1];\nend\n\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/createRotationVector3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.7919050713445532}} {"text": "function Cs = subgraph_centrality(CIJ)\n% SUBGRAPH_CENTRALITY subgraph centrality of a network\n%\n% Cs = subgraph_centrality(CIJ)\n%\n% The subgraph centrality of a node is a weighted sum of closed walks of\n% different lengths in the network starting and ending at the node. This\n% function returns a vector of subgraph centralities for each node of the\n% network.\n%\n% Inputs: CIJ, adjacency matrix (binary)\n%\n% Outputs: Cs, subgraph centrality\n%\n% Reference: Estrada and Rodriguez-Velasquez (2005) Phys Rev E 71, 056103\n% Estrada and Higham (2010) SIAM Rev 52, 696.\n%\n% Xi-Nian Zuo, Chinese Academy of Sciences, 2010\n% Rick Betzel, Indiana University, 2012\n\n[V,lambda] = eig(CIJ); % Compute the eigenvectors and\nlambda = diag(lambda); % eigenvalues.\nV2 = V.^2; % Matrix of squares of the eigenvectors elements.\nCs = real(V2 * exp(lambda)); % Compute eigenvector centrality. Lop off imaginary part remaining due to precision error.", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/subgraph_centrality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7919011081634408}} {"text": "function value = c1_jac_monomial_integral ( alpha, beta, expon )\n\n%*****************************************************************************80\n%\n%% C1_JAC_MONOMIAL_INTEGRAL: integral of a monomial with Jacobi weight over C1.\n%\n% Discussion:\n%\n% value = integral ( -1 <= x <= +1 ) x^expon (1-x)^alpha (1+x)^beta dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the exponent of (1-X) in the weight factor.\n%\n% Input, real BETA, the exponent of (1+X) in the weight factor.\n%\n% Input, integer EXPON, the exponent.\n%\n% Output, real VALUE, the value of the integral.\n%\n c = expon;\n\n if ( mod ( expon, 2 ) == 0 )\n s = +1.0;\n else\n s = -1.0;\n end\n\n arg1 = - alpha;;\n arg2 = 1.0 + c;\n arg3 = 2.0 + beta + c;\n arg4 = - 1.0;\n\n value1 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n\n arg1 = - beta;\n arg2 = 1.0 + c;\n arg3 = 2.0 + alpha + c;\n arg4 = - 1.0;\n\n value2 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n\n value = gamma ( 1.0 + c ) ...\n * ( s * gamma ( 1.0 + beta ) * value1 / gamma ( 2.0 + beta + c ) ...\n + gamma ( 1.0 + alpha ) * value2 / gamma ( 2.0 + alpha + c ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/c1_jac_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.7918393699386673}} {"text": "function d = p02_d ( m, id, c, w, n, x )\n\n%*****************************************************************************80\n%\n%% P02_D evaluates a derivative for problem p02.\n%\n% Discussion:\n%\n% f(x) = 1 / product ( c(1:m)^(-2) + ( x(1:m) - w(1:m) )^2 )\n%\n% Default values are:\n%\n% c(1:m) = 1\n% w(1:m) = 0.5\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 August 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Alan Genz,\n% A Package for Testing Multiple Integration Subroutines,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% Reidel, 1987, pages 337-340,\n% ISBN: 9027725144,\n% LC: QA299.3.N38.\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer ID, the spatial coordinate to be differentiated.\n%\n% Input, real C(M,1), W(M,1), the problem parameters.\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(M,N), the evaluation points.\n%\n% Output, real D(N,1), the value of the ID-th derivative component at X.\n%\n d = ones ( n, 1 );\n for i = 1 : m\n d = d .* ( c(i) ^ (-2) + ( x(i,:)' - w(i) ) .^ 2 );\n end\n d = 1.0 ./ d .* ( - 2.0 ) .* ( x(id,:)' - w(id) ) ./ ...\n ( c(id) ^ (-2) + ( x(id,:)' - w(id) ) .^ 2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp_nd/p02_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7918393631147306}} {"text": "% sgwt_kernel_simple_tf : evaluates \"simple\" tight-frame kernel\n%\n% this is similar to meyer kernel, but simpler\n%\n% function is essentially sin^2(x) in ascending part,\n% essentially cos^2 in descending part.\n%\n% function r= sgwt_kernel_simple_tf(x,kerneltype)\n%\n% Inputs\n% x : array of independent variable values\n% kerneltype : string, either 'sf' or 'wavelet' \n%\n% Ouputs\n% r : array of function values, same size as x.\n%\n% simple tf wavelet kernel : supported on [1/4,1]\n% simple tf scaling function kernel : supported on [0,1/2]\n%\n\nfunction r= sgwt_kernel_simple_tf(x,kerneltype)\n% h : [0,1]->[0,1] must satisfy h(0)=0, h(1)=1 .\nh=@(x) sin(pi*x/2).^2;\n\n%r1ind=find(x>=0 & x<0.25);\nr1ind=find(x<0.25);\n\nr2ind=find(x>=.25 & x<0.5);\nr3ind=find(x>=.5 & x<1);\n\nr=zeros(size(x));\n\nswitch kerneltype\n case 'sf'\n r(r1ind)=1;\n r(r2ind)=sqrt(1-h(4*x(r2ind)-1).^2);\n case 'wavelet'\n r(r2ind)=h(4*(x(r2ind)-1/4));\n r(r3ind)=sqrt(1-h(2*x(r3ind)-1).^2);\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/sgwt_require/sgwt_kernel_simple_tf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025386, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7917812113959595}} {"text": "function node_num = fem2d_bvp_serene_node_num ( nx, ny )\n\n%*****************************************************************************80\n%\n%% FEM2D_BVP_SERENE_NODE_NUM counts the number of nodes.\n%\n% Discussion:\n%\n% The program uses the finite element method, with piecewise serendipity \n% basis functions to solve a 2D boundary value problem over a rectangle.\n%\n% The grid uses NX nodes in the X direction and NY nodes in the Y direction.\n%\n% Both NX and NY must be odd.\n%\n% Because of the peculiar shape of the serendipity elements, counting the\n% number of nodes and variables is a little tricky. Here is a grid for\n% the case when NX = 7 and NY = 5, for which there are 29 nodes \n% and variables.\n%\n% 23 24 25 26 27 28 29\n% 19 20 21 22\n% 12 13 14 15 16 17 18\n% 8 9 10 11\n% 1 2 3 4 5 6 7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 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% Output, integer NODE_NUM, the number of nodes and variables.\n%\n node_num = nx * ( ny + 1 ) / 2 ...\n + ( nx + 1 ) / 2 * ( ny - 1 ) / 2; \n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_bvp_serene/fem2d_bvp_serene_node_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7917535602445939}} {"text": "% compute squared Euclidean distance\n% ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B\nfunction d = L2_distance_1(a,b)\n% a,b: two matrices. each column is a data\n% d: distance matrix of a and b\n\n\n\nif (size(a,1) == 1)\n a = [a; zeros(1,size(a,2))]; \n b = [b; zeros(1,size(b,2))]; \nend\n\naa=sum(a.*a); bb=sum(b.*b); ab=a'*b; \nd = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab;\nd = real(d);\nd = max(d,0);\n\n% % force 0 on the diagonal? \nd = d.*(1-eye(size(d)));\n%d = d/size(a,1)^2;\n", "meta": {"author": "BatzoglouLabSU", "repo": "SIMLR", "sha": "bf44967cd40d9d4c789ecf866b3aae15ae6190f5", "save_path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR", "path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR/SIMLR-bf44967cd40d9d4c789ecf866b3aae15ae6190f5/MATLAB/src/L2_distance_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7917253546178468}} {"text": "function zbar = eval2dPoly( x, y, coeffs )\n% Given the coefficients of a polynomial as returned by fit2dPolySVD,\n% calculates the values z for input values (x,y).\n% x, y are column vectors specifying the points to be calculated.\n% The vectors must be the same length.\n% Coeffs is the coefficients array returned by fit2dPolySVD.\n\n\n[sizexR, sizexC] = size(x);\n[sizeyR, sizeyC] = size(y);\n\nif (sizexC ~= 1) || (sizeyC ~= 1)\n fprintf( 'Inputs of eval2dPoly must be column vectors' );\n return;\nend\n\nif (sizeyR ~= sizexR)\n fprintf( 'Inputs vectors of eval2dPoly must be the same length' );\n return;\nend\n\n\nnumVals = sizexR;\n\norder = 0.5 * (sqrt(8*length(coeffs)+1) - 3);\n\nzbar = zeros(numVals,1);\ncolumn = 1;\nfor xpower = 0:order\n for ypower = 0:(order-xpower)\n zbar = zbar + (coeffs(column) .* x.^xpower .* y.^ypower);\n column = column + 1;\n end\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31636-2d-polynomial-fitting-with-svd/eval2dPoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7917162803585875}} {"text": "function dy = diffxy(x,y,varargin)\n% DIFFXY - accurate numerical derivative/differentiation of Y w.r.t X. \n%\n% DY = DIFFXY(X,Y) returns the derivative of Y with respect to X using a \n% pseudo second-order accurate method. DY has the same size as Y.\n% DY = DIFFXY(X,Y,DIM) returns the derivative along the DIM-th dimension\n% of Y. The default is differentiation along the first \n% non-singleton dimension of Y.\n% DY = DIFFXY(X,Y,DIM,N) returns the N-th derivative of Y w.r.t. X.\n% The default is 1.\n%\n% Y may be an array of any dimension.\n% X can be any of the following:\n% - array X with size(X) equal to size(Y)\n% - vector X with length(X) equal to size(Y,DIM)\n% - scalar X denotes the spacing increment\n% DIM and N are both integers, with 1<=DIM<=ndims(Y)\n%\n% DIFFXY has been developed especially to handle unequally spaced data,\n% and features accurate treatment for end-points.\n%\n% Example: \n% % Data with equal spacing\n% x = linspace(-1,2,20);\n% y = exp(x);\n% \n% dy = diffxy(x,y);\n% dy2 = diffxy(x,dy); % Or, could use >> dy2 = diffxy(x,y,[],2);\n% figure('Color','white')\n% plot(x,(y-dy)./y,'b*',x,(y-dy2)./y,'b^')\n%\n% Dy = gradient(y)./gradient(x);\n% Dy2 = gradient(Dy)./gradient(x);\n% hold on\n% plot(x,(y-Dy)./y,'r*',x,(y-Dy2)./y,'r^')\n% title('Relative error in derivative approximation')\n% legend('diffxy: dy/dx','diffxy: d^2y/dx^2',...\n% 'gradient: dy/dx','gradient: d^2y/dx^2')\n%\n% Example: \n% % Data with unequal spacing. \n% x = 3*sort(rand(20,1))-1;\n% % Run the example above from y = exp(x)\n%\n% See also DIFF, GRADIENT\n% and DERIVATIVE on the File Exchange\n\n% for Matlab (should work for most versions)\n% version 1.0 (Nov 2010)\n% (c) Darren Rowland\n% email: darrenjrowland@hotmail.com\n%\n% Keywords: derivative, differentiation\n\n[h,dy,N,perm] = parse_inputs(x,y,varargin);\nif isempty(dy)\n return\nend\nn = size(h,1);\ni1 = 1:n-1;\ni2 = 2:n;\n\nfor iter = 1:N\n v = diff(dy)./h;\n if n>1\n dy(i2,:) = (h(i1,:).*v(i2,:)+h(i2,:).*v(i1,:))./(h(i1,:)+h(i2,:));\n dy(1,:) = 2*v(1,:) - dy(2,:);\n dy(n+1,:) = 2*v(n,:) - dy(n,:);\n else\n dy(1,:) = v(1,:);\n dy(n+1,:) = dy(1,:);\n end\nend\n\n% Un-permute the derivative array to match y\ndy = ipermute(dy,perm);\n\n%%% Begin local functions %%%\nfunction [h,dy,N,perm] = parse_inputs(x,y,v)\n\nnumvarargs = length(v);\nif numvarargs > 2\n error('diffxy:TooManyInputs', ...\n 'requires at most 2 optional inputs');\nend\n\nh = [];\nN = [];\nperm = [];\n\n% derivative along first non-singleton dimension by default\ndim = find(size(y)>1);\n% Return if dim is empty\nif isempty(dim)\n dy = [];\n return\nend\ndim = dim(1);\n\n% Set defaults for optional arguments\noptargs = {dim 1};\nnewVals = ~cellfun('isempty', v);\noptargs(newVals) = v(newVals);\n[dim, N] = optargs{:};\n\n% Error check on inputs\nif dim<1 || dim>ndims(y) || dim~=fix(dim) || ~isreal(dim)\n error('diffxy:InvalidOptionalArg',...\n 'dim must be specified as a non-negative integer')\nend\nif N~=fix(N) || ~isreal(N)\n error('diffxy:InvalidOptionalArg',...\n 'N must be an integer')\nend\n\n% permutation which will bring the target dimension to the front\nperm = 1:length(size(y));\nperm(dim) = [];\nperm = [dim perm];\ndy = permute(y,perm);\n\n\nif length(x)==1 % Scalar expansion to match size of diff(dy,[],1)\n sizeh = size(dy);\n sizeh(1) = sizeh(1) - 1;\n h = repmat(x,sizeh);\nelseif ndims(x)==2 && any(size(x)==1) % Vector x expansion\n if length(x)~=size(dy,1)\n error('diffxy:MismatchedXandY',...\n 'length of vector x must match size(y,dim)')\n end\n x = x(:);\n sizeh = size(dy);\n sizeh(1) = 1;\n h = repmat(diff(x),sizeh);\nelse\n if size(y) ~= size(x)\n error('diffxy:MismatchedXandY',...\n 'mismatched sizes of arrays x and y');\n end\n % Permute x as for y, then diff\n h = diff(permute(x,perm),[],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/29312-diffxy/diffxy/diffxy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.7916978490858616}} {"text": "function a = ijfact1 ( n )\n\n%*****************************************************************************80\n%\n%% IJFACT1 returns the IJFACT1 matrix.\n%\n% Formula:\n%\n% A(I,J) = (I+J)!\n%\n% Example:\n%\n% N = 4\n%\n% 2 6 24 120\n% 6 24 120 720\n% 24 120 720 5040\n% 120 720 5040 40320\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is a Hankel matrix: constant along anti-diagonals.\n%\n% A is integral: int ( A ) = A.\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% MJC Gover,\n% The explicit inverse of factorial Hankel matrices,\n% Department of Mathematics, University of Bradford, 1993.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n fact = 1;\n\n for k = 2 : 2 * n\n\n fact = fact * k;\n ilo = max ( 1, k - n );\n ihi = min ( n, k - 1 );\n\n for i = ilo : ihi\n a(i,k-i) = fact;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/ijfact1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.7916978458177064}} {"text": "function lmax = lebesgue_constant ( n, x, xfun )\n\n%*****************************************************************************80\n%\n%% LEBESGUE_CONSTANT estimates the Lebesgue constant for a set of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2014\n%\n% Author:\n%\n% John Burkardt.\n%\n% Parameters:\n%\n% Jean-Paul Berrut, Lloyd Trefethen,\n% Barycentric Lagrange Interpolation,\n% SIAM Review,\n% Volume 46, Number 3, September 2004, pages 501-517.\n%\n% Parameters:\n%\n% Input, integer N, the number of interpolation points.\n%\n% Input, real X(N), the interpolation points.\n%\n% Input, real XFUN(*), the evaluation points.\n%\n% Output, real LMAX, an estimate of the Lebesgue constant for the points.\n%\n lfun = lebesgue_function ( n, x, xfun );\n\n lmax = max ( lfun );\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/lebesgue/lebesgue_constant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.7915943350811712}} {"text": "function [A xy] = wheel_graph(n) \n% WHEEL_GRAPH Construct a wheel graph of order n\n%\n% The wheel graph is a cycle graph of order n-1 along with an additional\n% vertex that connects all the remaining vertices. (Run the example and it\n% will be extremely clear if you are still confused.)\n%\n% [A xy] = wheel_graph(n) returns the adjacency matrix for the wheel graph\n% of order n. The matrix xy stores two-dimensional coordinates for each \n% vertex.\n%\n% Example:\n% [A xy] = wheel_graph(10);\n% gplot(A,xy);\n%\n% See also CYCLE_GRAPH, STAR_GRAPH\n\n% David Gleich\n% Copyright, Stanford University, 2007-2008\n\n%% History\n% 2007-09-29: Changed output to double, fixed output for i=0,1\n%%\n\nif n>1\n i = 1:(n-1);\n j = [i(2:end) i(1)];\n i = [i i];\n j = [j n*ones(1,n-1)];\n A = sparse(i,j,1,n,n);\n A = A|A';\n A = double(A);\nelse\n i=[];\n A = sparse(n,n);\nend\n\ni = i(1:end/2);\nif n>0\n xy = [ [cos(2*pi*(i./(n-1))) 0]' [sin(2*pi*(i./(n-1))) 0]' ];\nelse\n xy = zeros(0,2);\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/matlab_bgl/wheel_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7915943345818016}} {"text": "function [x, y, h, hm, xm, ym] = generate_terrain(n, mesh_size, h0, r0, rr)\n\n% [x, y, h, hm, xm, ym] = generate_terrain(n, mesh_size, h0, r0, rr)\n% \n% This function generates a series of points that approximate terrain\n% according to a simple algorithm and very few parameters.\n%\n% Inputs:\n% n - Number of iterations of algorithm to perform, akin to the\n% order of magnitudes represented by the variation. Anything\n% beyond 7 will produce detail too fine to notice, while the\n% algorithm will require ~3 times longer for every iteration.\n% mesh_size - Size of the output mesh (e.g., 512 for 512-by-512)\n% h0 - Initial elevation\n% r0 - Initial roughness (how much terrain can vary in a step)\n% rr - Roughness roughness (how much roughness can vary in a step)\n%\n% For an example, see terrain_generation_introduction.m or \n% html/terrain_generation_introduction.html.\n%\n% Outputs:\n% x, y, and h - Vectors of points comprising terrain\n% xm, ym, and hm - Meshes over landscape, useful for surf(...)\n%\n% Tucker McClure\n% Copyright 2012, The MathWorks, Inc.\n\n % Set some defaults if the user didn't provide inputs.\n if nargin < 1, n = 7; end % Iterations\n if nargin < 2, mesh_size = 513; end % Output mesh size\n if nargin < 3, h0 = 0.1 * rand(); end % Elevation\n if nargin < 4, r0 = 0.1 * rand(); end % Roughness\n if nargin < 5, rr = 0.1 * rand(); end % Roughness roughness\n\n n0 = randi(5); % Number of initial points\n m = 3; % How many points grow from each old point\n nf = n0 * (m+1)^n; % Total number of points\n \n % Create initial x, y, and height coordinates and roughness map.\n x = [randn(n0, 1); zeros(nf-n0, 1)];\n y = [randn(n0, 1); zeros(nf-n0, 1)];\n h = [r0 * randn(n0, 1) + h0; zeros(nf-n0, 1)];\n r = [rr * randn(n0, 1) + r0; zeros(nf-n0, 1)];\n \n % Create new points from old points n times.\n for k = 1:n\n\n % Calculate the new variance for the x, y random draws and for the\n % h, r random draws.\n dxy = 0.75^k;\n dh = 0.5^k;\n\n % Number of new points to generate\n n_new = m * n0;\n\n % Parents for new points\n parents = reshape(repmat(1:n0, m, 1), [n_new, 1]);\n \n % Calculate indices for new and existing points.\n new = (n0+1):(n0+n_new);\n old = 1:n0;\n\n % Generate new x/y values.\n theta = 2*pi * rand(n_new, 1);\n radius = dxy * (rand(n_new, 1) + 1);\n x(new) = x(parents) + radius .* cos(theta);\n y(new) = y(parents) + radius .* sin(theta);\n \n % Interpolate to find nominal new r and h values and add noise to\n % roughness and height maps.\n r(new) = interpolate(x(old), y(old), r(old), x(new), y(new)) ...\n + (dh * rr) .* randn(n_new, 1);\n h(new) = interpolate(x(old), y(old), h(old), x(new), y(new)) ...\n + (dh/dxy) * radius .* r(new) .* randn(n_new, 1);\n \n % Add up the new points.\n n0 = n_new + n0;\n\n end\n\n % Normalize the distribution of the points about the median.\n x = (x - median(x))/std(x);\n y = (y - median(y))/std(y);\n\n % If the user wants a mesh output, we can do that too. Create a mesh\n % over the significant part and interpolate over it.\n if nargout > 3 && ~isempty(mesh_size)\n [xm, ym] = meshgrid(linspace(-1, 1, mesh_size));\n hm = interpolate(x, y, h, xm, ym);\n end\n \nend\n\n% Perform our particular type of interpolation.\nfunction vn = interpolate(x0, y0, v0, xn, yn)\n\n % Make an interpolator for height or roughness. We'll add safe far-away\n % points so we'll always be interpolating and not extrapolating.\n int = TriScatteredInterp([100*[-1 -1 1 1]'; x0], ...\n [100*[-1 1 -1 1]'; y0], ...\n [zeros(4, 1); v0], 'linear'); %#ok EMFF1>\n\n\t% Perform the actual interpolation.\n\tvn = int(xn, yn);\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/39559-automatic-terrain-generation/generate_terrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7915943326557415}} {"text": "function dist = circle_imp_point_dist_signed_2d ( r, center, p )\n\n%*****************************************************************************80\n%\n%% CIRCLE_IMP_POINT_DIST_SIGNED_2D: signed distance ( implicit circle, point ) in 2D.\n%\n% Discussion:\n%\n% The signed distance is zero if the point is on the circle.\n% The signed distance is negative if the point is inside the circle.\n%\n% An implicit circle in 2D satisfies the equation:\n%\n% ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 = R**2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2,1), the center of the circle.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, real DIST, the signed distance of the point\n% to the circle. If the point is inside the circle, the signed distance\n% is negative.\n%\n dim_num = 2;\n\n r2 = sqrt ( sum ( ( p(1:dim_num,1) - center(1:dim_num,1) ).^2 ) );\n\n dist = r2 - r;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/circle_imp_point_dist_signed_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7915943323194533}} {"text": "function y = sinspace(d1, d2, n, factor)\n%SINSPACE cosine spaced vector.\n% SINSPACE(X1, X2) generates a row vector of 100 sine spaced points\n% between X1 and X2. \n%\n% SINSPACE(X1, X2, N) generates N points between X1 and X2. \n% \n% A sine spaced vector clusters the elements toward X2:\n% X1 | | | | | | | | || X2\n%\n% Make n negative to cluster the elements toward X1:\n% X1 || | | | | | | | | X2 \n% \n% For -2 < N < 2, SINSPACE returns X2.\n% \n% SINSPACE(X1, X2, N, W) clusters the elements to a lesser degree as\n% dictated by W. W = 0 returns a normal sine spaced vector. W = 1 is the\n% same as LINSPACE(X1, X2, N). Experiment with W < 0 and W > 1 for\n% different clustering patterns.\n% \n% Author: Sky Sartorius\n%\n% See also COSSPACE, LINSPACE, LOGSPACE.\n\nif nargin == 2\n n = 100;\nend\nif nargin < 4\n factor = false;\nend\n\nif n<0\n n = floor(double(-n));\n y = d2 + (d1-d2)*sin(pi/2*(1-(0:(n-1))/(n-1)));\nelse\n n = floor(double(n));\n y = d1 + (d2-d1)*sin(pi/(2*(n-1))*(0:n-1));\nend\n\nif factor\n y = (1-factor)*y+factor*[d1+(0:n-2)*(d2-d1)/(n-1) d2];\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/utilities/sinspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7915192396020904}} {"text": "function cdf = levy_cdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% LEVY_CDF evaluates the Levy CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the CDF.\n% Normally, A <= X.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0 < B.\n%\n% Output, real CDF, the value of the PDF.\n%\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVY_PDF - Fatal error!\\n' );\n fprintf ( 1, ' Input parameter B <= 0.0\\n' );\n error ( 'LEVY_PDF - Fatal error!' );\n end\n\n if ( x <= a )\n cdf = 0.0;\n else\n cdf = 1.0 - error_f ( sqrt ( b / ( 2.0 * ( x - a ) ) ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/levy_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7915192335540979}} {"text": "% foo.m\n%\n% This m-file shows an example of how to use ApEn function\n% \n% More specifically, it generates three simulated data with different\n% complexity (sine, chirp, and Gaussian noise), and plots the ApEn values\n% with varying r\n\n%-------------------------------------------------------------------------\n% coded by Kijoon Lee, kjlee@ntu.edu.sg\n% Mar 21st, 2012\n%-------------------------------------------------------------------------\nclear all\n\nm = 2; % embedded dimension\ntau = 1; % time delay for downsampling\nN = 1000;\nt = 0.001*(1:N);\n\n% generate simulated data\nsint = sin(2*pi*10*t); % sine curve\nchirpt = chirp(t,0,1,150); % chirp signal\nwhitet = randn(1,N); % white noise\n\n% calculate standard deviations\nsd1 = std(sint);\nsd2 = std(chirpt);\nsd3 = std(whitet);\n\n% specify the range of r\nrnum = 30;\nresult = zeros(3,rnum);\n\n% main calculation and display\nfigure\nfor i = 1:rnum\n r = i*0.02;\n result(1,i) = ApEn(m, r*sd1, sint, tau);\n result(2,i) = ApEn(m,r*sd2,chirpt, tau);\n result(3,i) = ApEn(m,r*sd3,whitet, tau);\nend\n\nr = 0.02*(1:rnum);\nplot(r,result(1,:),'o-',r,result(2,:),'o-',r,result(3,:),'o-')\naxis([0 rnum*0.02 0 1.05*max(result(:))])\nlegend('sin','chirp','white noise')\ntitle(['ApEn, m=' num2str(m) ', \\tau=' num2str(tau)],'fontsize',14)\nxlabel 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/32427-fast-approximate-entropy/foo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7914549028803659}} {"text": "function a = clement1 ( n )\n\n%*****************************************************************************80\n%\n%% CLEMENT1 returns the CLEMENT1 matrix.\n%\n% Formula:\n%\n% if ( J = I+1 )\n% A(I,J) = sqrt(I*(N-I))\n% else if ( I = J+1 )\n% A(I,J) = sqrt(J*(N-J))\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% N = 5\n%\n% . sqrt(4) . . .\n% sqrt(4) . sqrt(6) . .\n% . sqrt(6) . sqrt(6) .\n% . . sqrt(6) . sqrt(4)\n% . . . sqrt(4) .\n%\n% Properties:\n%\n% A is tridiagonal.\n%\n% A is banded, with bandwidth 3.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% The diagonal of A is zero.\n%\n% A is singular if N is odd.\n%\n% About 64 percent of the entries of the inverse of A are zero.\n%\n% The eigenvalues are plus and minus the numbers\n%\n% N-1, N-3, N-5, ..., (1 or 0).\n%\n% If N is even,\n%\n% det ( A ) = (-1)^(N/2) * (N-1) * (N+1)^(N/2)\n%\n% and if N is odd,\n%\n% det ( A ) = 0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Clement,\n% A class of triple-diagonal matrices for test purposes,\n% SIAM Review,\n% Volume 1, 1959, pages 50-52.\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n for i = 1 : n\n for j = 1 : n\n\n if ( j == i + 1 )\n a(i,j) = sqrt ( i * ( n - i ) );\n elseif ( i == j + 1 )\n a(i,j) = sqrt ( j * ( n - j ) );\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/clement1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7914144552066067}} {"text": "% Computes log(besseli(0,x)) robustly. Computing it directly causes\n% numerical problems at high x, but the function has asymptotic linear\n% behaviour, which we approximate here for high x.\n%\n% author: Daniel C Alexander (d.alexander@ucl.ac.uk)\n%\n\nfunction lb0 = logbesseli0(x)\n\n% For very large arguments to besseli, we approximate log besseli using a\n% linear model of the asymptotic behaviour.\n% The linear parameters come from this command:\n% app=regress(log(besseli(0,500:700))',[ones(201,1) (500:700)']);\napp = [-3.61178295877576 0.99916157999904];\n\nlb0 = zeros(length(x), 1);\nexact = find(x<700);\napprox = find(x>=700);\nlb0(exact) = log(besseli(0, x(exact)));\n%lb0(approx) = x(approx)*app(2) + app(1);\n\n% This is a more standard approximation. For large x, I_0(x) -> exp(x)/sqrt(2 pi x).\nlb0(approx) = x(approx) - log(2*pi*x(approx))/2;\n\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/logbesseli0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970315, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7913928403369258}} {"text": "function Ahat = nearestSPD(A)\n% nearestSPD - the nearest (in Frobenius norm) Symmetric Positive Definite matrix to A\n% usage: Ahat = nearestSPD(A)\n%\n% From Higham: \"The nearest symmetric positive semidefinite matrix in the\n% Frobenius norm to an arbitrary real matrix A is shown to be (B + H)/2,\n% where H is the symmetric polar factor of B=(A + A')/2.\"\n%\n% http://www.sciencedirect.com/science/article/pii/0024379588902236\n%\n% arguments: (input)\n% A - square matrix, which will be converted to the nearest Symmetric\n% Positive Definite Matrix.\n%\n% Arguments: (output)\n% Ahat - The matrix chosen as the nearest SPD matrix to A.\n\nif nargin ~= 1\n error('Exactly one argument must be provided.')\nend\n\n% test for a square matrix A\n[r,c] = size(A);\nif r ~= c\n error('A must be a square matrix.')\nelseif (r == 1) && (A <= 0)\n % A was scalar and non-positive, so just return eps\n Ahat = eps;\n return\nend\n\n% symmetrize A into B\nB = (A + A')/2;\n\n% Compute the symmetric polar factor of B. Call it H.\n% Clearly H is itself SPD.\n[U,Sigma,V] = svd(B);\nH = V*Sigma*V';\n\n% get Ahat in the above formula\nAhat = (B+H)/2;\n\n% ensure symmetry\nAhat = (Ahat + Ahat')/2;\n\n% test that Ahat is in fact PD. if it is not so, then tweak it just a bit.\np = 1;\nk = 0;\nwhile p ~= 0\n [R,p] = chol(Ahat);\n k = k + 1;\n if p ~= 0\n % Ahat failed the chol test. It must have been just a hair off,\n % due to floating point trash, so it is simplest now just to\n % tweak by adding a tiny multiple of an identity matrix.\n mineig = min(eig(Ahat));\n Ahat = Ahat + (-mineig*k.^2 + eps(mineig))*eye(size(A));\n end\nend\n\n\n\n\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/base/utilities/NearestSymmetricPositiveDefinite/nearestSPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7913058254149313}} {"text": "function numgrad = computeNumericalGradient(J, theta)\n% numgrad = computeNumericalGradient(J, theta)\n% theta: a vector of parameters\n% J: a function that outputs a real-number. Calling y = J(theta) will return the\n% function value at theta. \n \n% Initialize numgrad with zeros 2x1 这是输入X的行数,其实也就是参数W的个数\nnumgrad = zeros(size(theta));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: \n% Implement numerical gradient checking, and return the result in numgrad. \n% (See Section 2.3 of the lecture notes.)\n% You should write code so that numgrad(i) is (the numerical approximation to) the \n% partial derivative of J with respect to the i-th input argument, evaluated at theta. \n% I.e., numgrad(i) should be the (approximately) the partial derivative of J with \n% respect to theta(i).\n% \n% Hint: You will probably want to compute the elements of numgrad one at a time. \n\n\nepsilon = 0.000001;\n% 2 x2 得到参数的个数\nnumW = size(theta,1);\nI = eye(numW);\nI = I * epsilon;\nfor j = 1:numW\n numgrad(j) = (J(theta+I(:,j)) - J(theta-I(:,j))) / (2 * epsilon);\nend\n\n\n\n\n\n\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/DeepLearning/UFLDL/Vectorization_sparseae_exercise/computeNumericalGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8887588023318195, "lm_q1q2_score": 0.7912568249571411}} {"text": "function [I J] = itril(sz, k)\n% function [I J] = itril(sz, k) % OR\n% I = itril(sz, k)\n%\n% Return the subindices [I J] (or linear indices I if single output call)\n% in the purpose of extracting an lower triangular part of the matrix of\n% the size SZ. Input k is optional shifting. For k=0, extract from the main\n% diagonal. For k>0 -> above the diagonal, k<0 -> below the diagonal\n% \n% This returnd same as [...] = find(tril(ones(sz),k))\n% - Output is a column and sorted with respect to linear indice\n% - No intermediate matrix is generated, that could be useful for large\n% size problem\n% - Mathematically, A(itril(size(A)) is called (lower) \"half-vectorization\"\n% of A \n%\n% Example:\n%\n% A = [ 7 5 4\n% 4 2 3\n% 9 1 9\n% 3 5 7 ]\n%\n% I = itril(size(A)) % gives [1 2 3 4 6 7 8 11 12]'\n% A(I) % gives [7 4 9 3 2 1 5 9 7]' OR A(tril(A)>0)\n%\n% Author: Bruno Luong \n% Date: 21/March/2009\n\nif isscalar(sz)\n sz = [sz sz];\nend\nm=sz(1);\nn=sz(2);\n\n% Main diagonal by default\nif nargin<2\n k=0;\nend\n\nnc = min(n,m+k); % number of columns of the triangular part\nlo = max((1:nc).'-k,1); % lower row indice for each column\nhi = m + zeros(nc,1); % upper row indice for each column\n\nif isempty(lo)\n I = zeros(0,1);\n J = zeros(0,1);\nelse\n c=cumsum([0; hi-lo]+1); % cumsum of the length\n I = accumarray(c(1:end-1), (lo-[0; hi(1:end-1)]-1), ...\n [c(end)-1 1]);\n I = cumsum(I+1); % row indice\n J = cumsum(accumarray(c,1));\n J = J(1:end-1); % column indice\nend\n\nif nargout<2\n % convert to linear indices\n I = sub2ind([m n], I, J);\nend\n\nend % itril\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23391-triangular-and-diagonal-indexing/HalfVectorization/itril.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8902942290328344, "lm_q1q2_score": 0.7912568222253078}} {"text": "function result = polygon_integral_yy ( n, v )\n\n%*****************************************************************************80\n%\n%% POLYGON_INTEGRAL_YY integrates the function Y*Y over a polygon.\n%\n% Discussion:\n%\n% The polygon is bounded by the points (X(1:N), Y(1:N)).\n%\n% INTEGRAL = (1/12) * sum ( 1 <= I <= N )\n% - ( Y(I)^3 + Y(I)^2 * Y(I-1) + Y(I) * Y(I-1)^2 + Y(I-1)^3 )\n% * ( X(I) - X(I-1) )\n%\n% where X(0) and Y(0) should be replaced by X(N) and Y(N).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% S F Bockman,\n% Generalizing the Formula for Areas of Polygons to Moments,\n% American Mathematical Society Monthly,\n% 1989, pages 131-132.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n% N should be at least 3 for a nonzero result.\n%\n% Input, real V(2,N), the coordinates of the vertices\n% of the polygon. These vertices should be given in\n% counter-clockwise order.\n%\n% Output, real RESULT, the value of the integral.\n%\n result = 0.0;\n\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_INTEGRAL_YY - Warning!\\n' );\n fprintf ( 1, ' The number of polygonal vertices must be\\n' );\n fprintf ( 1, ' at least 3, but the input polygon has N = %d\\n', n );\n error ( 'POLYGON_INTEGRAL_YY - Warning!' );\n end\n\n for i = 1 : n\n\n if ( i == 1 )\n im1 = n;\n else\n im1 = i - 1;\n end\n\n result = result - ( v(2,i).^3 + v(2,i).^2 * v(2,im1) ...\n + v(2,i) * v(2,im1).^2 + v(2,im1).^3 ) * ( v(1,i) - v(1,im1) );\n\n end\n\n result = result / 12.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polygon_properties/polygon_integral_yy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7912431678075467}} {"text": "function x=pentsolve(A,b)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% pentsolve.m\n%\n% Solve a pentadiagonal system Ax=b where A is a strongly nonsingular matrix\n% \n% If A is not a pentadiagonal matrix, results will be wrong\n%\n% Reference: G. Engeln-Muellges, F. Uhlig, \"Numerical Algorithms with C\"\n% Chapter 4. Springer-Verlag Berlin (1996)\n%\n% Written by Greg von Winckel 3/15/04\n% Contact: gregvw@chtm.unm.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[M,N]=size(A);\n\n% Check dimensions\nif M~=N\n error('Matrix must be square');\n return; \nend\n\nif length(b)~=M\n error('Matrix and vector must have the same number of rows');\n return;\nend\n\nx=zeros(N,1);\n \n% Check for symmetry\nif A==A' % Symmetric Matrix Scheme\n \n % Extract bands\n d=diag(A);\n f=diag(A,1);\n e=diag(A,2);\n \n alpha=zeros(N,1);\n gamma=zeros(N-1,1);\n delta=zeros(N-2,1);\n c=zeros(N,1);\n z=zeros(N,1);\n \n % Factor A=LDL'\n alpha(1)=d(1);\n gamma(1)=f(1)/alpha(1);\n delta(1)=e(1)/alpha(1);\n \n alpha(2)=d(2)-f(1)*gamma(1);\n gamma(2)=(f(2)-e(1)*gamma(1))/alpha(2);\n delta(2)=e(2)/alpha(2);\n \n for k=3:N-2\n alpha(k)=d(k)-e(k-2)*delta(k-2)-alpha(k-1)*gamma(k-1)^2;\n gamma(k)=(f(k)-e(k-1)*gamma(k-1))/alpha(k);\n delta(k)=e(k)/alpha(k);\n end\n \n alpha(N-1)=d(N-1)-e(N-3)*delta(N-3)-alpha(N-2)*gamma(N-2)^2;\n gamma(N-1)=(f(N-1)-e(N-2)*gamma(N-2))/alpha(N-1);\n alpha(N)=d(N)-e(N-2)*delta(N-2)-alpha(N-1)*gamma(N-1)^2;\n \n % Update Lx=b, Dc=z\n \n z(1)=b(1);\n z(2)=b(2)-gamma(1)*z(1);\n \n for k=3:N\n z(k)=b(k)-gamma(k-1)*z(k-1)-delta(k-2)*z(k-2);\n end\n \n c=z./alpha;\n \n % Backsubstitution L'x=c\n x(N)=c(N);\n x(N-1)=c(N-1)-gamma(N-1)*x(N);\n \n for k=N-2:-1:1\n x(k)=c(k)-gamma(k)*x(k+1)-delta(k)*x(k+2);\n end\n \nelse % Non-symmetric Matrix Scheme\n \n % Extract bands\n d=diag(A);\n e=diag(A,1);\n f=diag(A,2);\n h=[0;diag(A,-1)];\n g=[0;0;diag(A,-2)];\n \n alpha=zeros(N,1);\n gam=zeros(N-1,1);\n delta=zeros(N-2,1);\n bet=zeros(N,1);\n \n c=zeros(N,1);\n z=zeros(N,1);\n \n % Factor A=LR\n alpha(1)=d(1);\n gam(1)=e(1)/alpha(1);\n delta(1)=f(1)/alpha(1);\n bet(2)=h(2);\n alpha(2)=d(2)-bet(2)*gam(1);\n gam(2)=( e(2)-bet(2)*delta(1) )/alpha(2);\n delta(2)=f(2)/alpha(2);\n \n for k=3:N-2\n bet(k)=h(k)-g(k)*gam(k-2);\n alpha(k)=d(k)-g(k)*delta(k-2)-bet(k)*gam(k-1);\n gam(k)=( e(k)-bet(k)*delta(k-1) )/alpha(k);\n delta(k)=f(k)/alpha(k);\n end\n \n bet(N-1)=h(N-1)-g(N-1)*gam(N-3);\n alpha(N-1)=d(N-1)-g(N-1)*delta(N-3)-bet(N-1)*gam(N-2);\n gam(N-1)=( e(N-1)-bet(N-1)*delta(N-2) )/alpha(N-1);\n bet(N)=h(N)-g(N)*gam(N-2);\n alpha(N)=d(N)-g(N)*delta(N-2)-bet(N)*gam(N-1);\n\n % Update b=Lc\n c(1)=b(1)/alpha(1);\n c(2)=(b(2)-bet(2)*c(1))/alpha(2);\n \n for k=3:N\n c(k)=( b(k)-g(k)*c(k-2)-bet(k)*c(k-1) )/alpha(k);\n end\n \n \n % Back substitution Rx=c\n x(N)=c(N);\n x(N-1)=c(N-1)-gam(N-1)*x(N);\n\n for k=N-2:-1:1\n x(k)=c(k)-gam(k)*x(k+1)-delta(k)*x(k+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/4671-fast-pentadiagonal-system-solver/pentsolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7912431566178735}} {"text": "function [ lam, mu ] = cycle_floyd ( f, x0 )\n\n%*****************************************************************************80\n%\n%% CYCLE_FLOYD finds a cycle in an iterated mapping using Floyd's method.\n%\n% Discussion:\n%\n% Suppose we a repeatedly apply a function f(), starting with the argument\n% x0, then f(x0), f(f(x0)) and so on. Suppose that the range of f is finite.\n% Then eventually the iteration must reach a cycle. Once the cycle is reached,\n% succeeding values stay within that cycle.\n%\n% Starting at x0, there is a \"nearest element\" of the cycle, which is\n% reached after MU applications of f.\n%\n% Once the cycle is entered, the cycle has a length LAM, which is the number\n% of steps required to first return to a given value.\n%\n% This function uses Floyd's method to determine the values of MU and LAM,\n% given F and X0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\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, integer F( integer I ), the name of the function \n% to be analyzed.\n%\n% Input, integer X0, the starting point.\n%\n% Output, integer LAM, the length of the cycle.\n%\n% Output, integer MU, the index in the sequence starting\n% at X0, of the first appearance of an element of the cycle.\n%\n tortoise = f ( x0 );\n hare = f ( tortoise );\n\n while ( tortoise ~= hare )\n tortoise = f ( tortoise );\n hare = f ( f ( hare ) );\n end\n\n mu = 0;\n tortoise = x0;\n\n while ( tortoise ~= hare )\n tortoise = f ( tortoise );\n hare = f ( hare );\n mu = mu + 1;\n end\n\n lam = 1\n hare = f ( tortoise )\n while ( tortoise ~= hare )\n hare = f ( hare );\n lam = lam + 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/cycle_floyd/cycle_floyd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.8933093968230773, "lm_q1q2_score": 0.7911429149874887}} {"text": "function [auc,fpr,tpr] = fastAUC(labels,scores,plot_flag)\n% function [auc,fpr,tpr] = myauc(labels,scores,plot_flag)\n%\n% This function calculates m AUC values for m ranked lists.\n% n is the number of ranked items. \n% m is the number of different rankings.\n%\n% Input: labels is nXm binary logical.\n% scores is nXm real. For a high AUC the higher scores should have\n% labels==1.\n% plot_flag: binary flag, if TRUE then m ROC curves will be plotted\n% (default FALSE).\n%\n% Output: auc is mX1 real, the Area Under the ROC curves.\n% fpr is nXm real, the false positive rates.\n% tpr is nXm real, the true positive rates.\n\nif ~exist('plot_flag','var')\n plot_flag = 0;\nend\nif ~islogical(labels)\n error('labels input should be logical');\nend\nif ~isequal(size(labels),size(scores))\n error('labels and scores should have the same size');\nend\n[n,m] = size(labels);\nnum_pos = sum(labels);\nif any(num_pos==0)\n error('no positive labels entered');\nend\nif any(num_pos==n)\n error('no negative labels entered');\nend\n\n[~,scores_si] = sort(scores,'descend');\nclear scores\nscores_si_reindex = scores_si+ones(n,1)*(0:m-1)*n;\nl = labels(scores_si_reindex);\nclear scores_si labels \n\ntp = cumsum(l==1,1);\nfp = repmat((1:n)',[1 m])-tp;\n\nnum_neg = n-num_pos;\nfpr = bsxfun(@rdivide,fp,num_neg); %False Positive Rate\ntpr = bsxfun(@rdivide,tp,num_pos); %True Positive Rate\n\n%Plot the ROC curve\nif plot_flag==1\n plot(fpr,tpr);\n xlabel('False Positive');\n ylabel('True Positive');\nend\n\nauc = sum(tpr.*[(diff(fp)==1); zeros(1,m)])./num_neg;\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/42860-fast-auc-calculator-and-roc-curve-plotter/fastAUC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7910402573040097}} {"text": "function j = jacobi_symbol ( q, p )\n\n%*****************************************************************************80\n%\n%% JACOBI_SYMBOL evaluates the Jacobi symbol (Q/P).\n%\n% Discussion:\n%\n% If P is prime, then\n%\n% Jacobi Symbol (Q/P) = Legendre Symbol (Q/P)\n%\n% Else \n%\n% let P have the prime factorization\n%\n% P = Product ( 1 <= I <= N ) P(I)**E(I)\n%\n% Jacobi Symbol (Q/P) =\n%\n% Product ( 1 <= I <= N ) Legendre Symbol (Q/P(I))**E(I)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996, pages 86-87.\n%\n% Parameters:\n%\n% Input, integer Q, an integer whose Jacobi symbol with\n% respect to P is desired.\n%\n% Input, integer P, the number with respect to which the Jacobi\n% symbol of Q is desired. P should be 2 or greater.\n%\n% Output, integer J, the Jacobi symbol (Q/P).\n% Ordinarily, J will be -1, 0 or 1.\n% -2, not enough factorization space.\n% -3, an error during Legendre symbol calculation.\n%\n\n%\n% P must be greater than 1.\n%\n if ( p <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' P must be greater than 1.\\n' );\n l = -2;\n return\n end\n%\n% Decompose P into factors of prime powers.\n%\n [ nfactor, factor, power, nleft ] = i4_factor ( p );\n\n if ( nleft ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' Not enough factorization space.\\n' );\n j = -2;\n error ( 'JACOBI_SYMBOL - Fatal error!' );\n end\n%\n% Force Q to be nonnegative.\n%\n qq = q;\n\n while ( qq < 0 )\n qq = qq + p;\n end\n%\n% For each prime factor, compute the Legendre symbol, and\n% multiply the Jacobi symbol by the appropriate factor.\n%\n j = 1;\n for i = 1 : nfactor\n pp = factor(i);\n l = legendre_symbol ( qq, pp );\n if ( l < -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' Error during Legendre symbol calculation.\\n' );\n j = -3;\n error ( 'JACOBI_SYMBOL - Fatal error!' );\n end\n j = j * l^power(i);\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/jacobi_symbol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.7910290253857755}} {"text": "function [ x, seed ] = r4_normal_01 ( seed )\n\n%*****************************************************************************80\n%\n%% R4_NORMAL_01 returns a unit pseudonormal R4.\n%\n% Discussion:\n%\n% The standard normal probability distribution function (PDF) has\n% mean 0 and standard deviation 1.\n%\n% The Box-Muller method is used, which is efficient, but\n% generates two values at a time.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 06 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the standard normal PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ r1, seed ] = r4_uniform_01 ( seed );\n [ r2, seed ] = r4_uniform_01 ( seed );\n x = sqrt ( -2.0 * log ( r1 ) ) * cos ( 2.0 * pi * r2 );\n\n return\nend\n", "meta": {"author": "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/r4_normal_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7909825632083735}} {"text": "function [q, pval] = ljungbox(data, lags)\n% Ljung-Box tests for the presence of serial correlation in up to q lags. Returns LAGS Ljung-Box\n% statistics tests, one for tests for each lag between 1 and LAGS. Under the null of no serial\n% correlation and assuming homoskedasticity, the Ljung-Box test statistic is asymptotically\n% distributed X2(q) \n% \n% USAGE:\n% [Q,PVAL] = ljungbox(DATA,LAGS)\n% \n% INPUTS:\n% DATA - A T by 1 vector of data\n% LAGS - The maximum number of lags to compute the LB. The statistic and pval will be\n% returned for all sets of lags up to and including LAGS \n% \n% OUTPUTS:\n% Q - A LAGS by 1 vector of Q statistics\n% PVAL - A LAGS by 1 set of appropriate pvals\n% \n% COMMENTS:\n% This test statistic is common but often inappropriate since it assumes homoskedasticity. For a\n% heteroskedasticity consistent serial correlation test, see lmtest1 \n%\n% SEE ALSO:\n% LMTEST1, SACF, SPACF\n \n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 1/1/2007\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin~=2\n error('2 inputs required.')\nend\nT=length(data);\nif T<=lags\n error('At least LAGS observations requires')\nend\nif size(data,1)~=T,\n data=data';\nend\nif size(data,2)~=1\n error('DATA must be a column vector')\nend\nif ~isscalar(lags) && lags>0 && floor(lags)==lags\n error('LAGS must be a positive integer')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nac = sacf(data,lags,0,0);\n\nq = zeros(lags,1);\nT = length(data);\nfor L=1:lags\n q(L)=T*(T+2)*sum(ac(1:L).^2./(T-(1:L)'));\nend\npval = 1 - chi2cdf(q,(1:lags)');", "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/tests/ljungbox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7909613533141382}} {"text": "function s = Simpson2(a, b)\n%% Simpson Rule for a prestablished f(x)\n% a: is the lower limit of integration\n% b: is the upper limit of integration\n% for this excersice f(x)=x^2\n\nh=(b-a)/4;\nx(1)=a;\nx(2)=a+(b-a)*1/4;\nx(3)=a+(b-a)*1/2;\nx(4)=a+(b-a)*3/4;\nx(5)=b;\n\nf(1)=myfunction(x(1));\nf(2)=myfunction(x(2));\nf(3)=myfunction(x(3));\nf(4)=myfunction(x(4));\nf(5)=myfunction(x(5));\n\ns=h/3*sum([1 4 2 4 1].*f);\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/NumericalMethods/Simpson2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7909604738278346}} {"text": "function [P L U Q]=GaElCoPi(A)\n\n%Gaussian Elimination with Complete Pivoting\n%version 1.0\n\n%P*A*Q=L*U\n%Alvaro Moraes\n%KAUST 2009\n\n%Example of usage:\n%A=randn(40);\n%[P L U Q]=GaElCoPi(A);\n%norm(P*A*Q-L*U)\n\n% or this (it takes some time)\n% choose the size of A and \n% the number of simulations\n% for k=1:1000\n% k\n% A=randn(128);\n% [P L U Q]=GaElCoPi(A);\n% N1(k) =norm(P*A*Q-L*U);\n% %compute the growth factor\n% %rho(k)=max(max(abs(U)))/max(max(abs(A)))\n% end\n% plot(N1)\n% max(abs(N1)) %must be small xxe-014\n\n%and also check the worst scenario for the Partial Pivoting:\n% m=128; %(matrix 22.4 from Trefethen and Baum)\n% A=-1*tril(ones(m))+2*eye(m);\n% A(:,m)=ones(m,1);\n%[P L U Q]=GaElCoPi(A);\n%norm(P*A*Q-L*U)\n\n[n n]=size(A); \nL=zeros(n); \n%v and w record the permutations\n%of the rows and cols respect.\nv=1:n; w=1:n;\n\nfor k=1:n-1\n %in the next three lines \n %we obtain the max of abs(A(v(k:n),w(k:n)))\n %and its coordinates (imr,imc)\n [m,mc]=max(abs(A(v(k:n),w(k:n)))); \n [m,c]=max(m);\n imc=c; imr=mc(c);\n %next we transform this coordinates to the\n %coordinates of A\n imr=imr+k-1;\n imc=imc+k-1;\n %now, we perform the permutations\n v([k imr])=v([imr k]);\n w([k imc])=w([imc k]);\n %next, the gaussian elimination step\n for i=k+1:n \n L(v(i),w(k))=A(v(i),w(k))/A(v(k),w(k));\n A(v(i),:)=A(v(i),:)-L(v(i),w(k))*A(v(k),:);\n end \nend\n%by last, we use v and w to define P, Q, L and U\nP=eye(n);P=P(v,:); \nQ=eye(n);Q=Q(:,w); \nL=L(v,w)+ eye(n);\nU=A(v,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/25758-gaussian-elimination-using-complete-pivoting/GaElCoPi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7909278382881307}} {"text": "function[fs]=morsespace(varargin)\n%MORSESPACE Logarithmically-spaced frequencies for generalized Morse wavelets.\n%\n% F=MORSESPACE(GAMMA,BETA,N) generates a frequency array for the \n% generalized Morse wavelet transform of an N-point time series. The \n% wavelets are specified by GAMMA and BETA. \n%\n% LOG(F) is uniformly spaced, following convention for wavelet analysis.\n%\n% F has units of *radians* per sample point, and is a column vector with \n% the frequencies arranged in decending order. \n% \n% In this usage, the frequencies F are determined using default settings,\n% described below, which should be appropriate for most applications. \n%\n% Additional control over the frequency array F can be obtained using the\n% following alternate usages.\n%\n% For details on this calculation, see Lilly (2016).\n% __________________________________________________________________\n%\n% High- and low-frequency specification\n%\n% F=MORSESPACE(GAMMA,BETA,HIGH,LOW) explicitly sets the high-frequency\n% and low-frequency cutoffs for the frequency array. \n%\n% The first (largest) value of F is then just smaller than HIGH and the \n% smallest is just larger than LOW.\n%\n% HIGH and LOW have units of *radian* per unit sample point.\n% __________________________________________________________________\n%\n% High-frequency cutoff\n%\n% The highest frequency can be set to be the minimum of a specified value\n% and a cutoff frequency based on a Nyquist overlap condition.\n%\n% F=MORSESPACE(GAMMA,BETA,{ETA,HIGH},LOW) sets the highest frequency \n% to be the minimum of the specified value HIGH, and the largest \n% frequency for which the wavelet will satisfy the threshold level ETA. \n%\n% Here ETA be a number between zero and one specifying the ratio of a\n% frequency-domain wavelet at the Nyquist frequency to its peak value.\n%\n% Note that in this usage, {ETA,HIGH} is a cell array with two entries.\n%\n% The simplified usage F=MORSESPACE(GAMMA,BETA,N) corresponds to the \n% choice ETA=0.1, so that by default, the highest-frequency wavelet \n% will decay to at least 10% of its peak value at the Nyquist frequency.\n% __________________________________________________________________\n%\n% Low-frequency cutoff\n%\n% The lowest frequency can be set to a cutoff frequency based on an \n% endpoint overlap condition.\n%\n% F=MORSESPACE(GAMMA,BETA,HIGH,{P,N}) sets the lowest frequency such that\n% the lowest-frequency wavelet will reach some number P times its central \n% window width at the ends of the time series. \n% \n% P is called the packing number. A choice of P=1 corresponds to \n% roughly 95% of the time-domain wavelet energy being contained within \n% the time series endpoints for a wavelet at the center of the domain.\n%\n% F=MORSESPACE(GAMMA,BETA,HIGH,{P,N,LOW}) alternately chooses the maximum \n% of the R-level cutoff frequency, and a specified low frequency LOW.\n% \n% The simplified usage F=MORSESPACE(GAMMA,BETA,N) corresponds to the\n% default value P=5. At the lowest frequency, five wavelets will then\n% fit into the time series, with 5% energy overlap between them.\n% __________________________________________________________________\n%\n% Wavelet density\n%\n% F=MORSESPACE(GAMMA,BETA,HIGH,LOW,D) controls the number of points in \n% the frequency array through the 'density' D. \n%\n% Higher values of D mean more overlap in the frequency domain. The\n% default value of the density is D=4.\n%\n% When D=1, the peak of one wavelet is located at the half-power points \n% of the adjacent wavelet. D=4 means that four other wavelets will occur \n% between the peak of one wavelet and its half-power point. \n% __________________________________________________________________\n%\n% See also MORSEWAVE, WAVETRANS.\n% \n% Usage: f=morsespace(ga,be,N);\n% f=morsespace(ga,be,high,low,D);\n% f=morsespace(ga,be,{eta,high},low,D);\n% f=morsespace(ga,be,{eta,high},{p,N},D);\n% f=morsespace(ga,be,{eta,high},{p,N,low},D);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2009--2016 J.M. Lilly --- type 'help jlab_license' for details\n\n\n% Note then when HIGH and LOW are explicitly input, the time series\n% length N is no longer input as the first argument. \n\nif strcmpi(varargin{1},'--t')\n morsespace_test;return\nend\n\nif strcmpi(varargin{1},'--f')\n type makefigs_morsespace;\n makefigs_morsespace\n return\nend\n\n\n%/***************************************************************\n%Sort out input arguments \n% if ischar(varargin{end})\n% str=varargin{end};\n% varargin=varargin(1:end-1);\n% else\n% str='peak';\n% end\n\nga=varargin{1};\nbe=varargin{2};\nD=4; \n\nif length(varargin)==3\n N=varargin{3};\n \n %Default choices\n low={5,N};\n high={0.1,pi};\nelse\n high=varargin{3};\n low=varargin{4};\n if length(varargin)==5\n D=varargin{5};\n end\nend\n\n%\\***************************************************************\n\n\nif iscell(high)\n %Recall pi is Nyquist\n high=min(high{2},morsehigh(ga,be,high{1}));\n %high\nend\n\nif iscell(low)\n if length(low)==2\n low{3}=0;\n end\n low=max(low{3},morsespace_low(ga,be,low{1},low{2}));\nend\n\nr=1+frac(1,D*morseprops(ga,be));\nN=floor(frac(log(frac(high,low)),log(r)));\nfs=high*ones(N+1,1)./r.^[0:N]';\n\n% if length(fs)>1000\n% warning('F is longer than 1000 points... ')\n% end\n\n% if strfind(str,'ene')\n% [fm,fe,fi] = morsefreq(ga,be);\n% fs=frac(fe,fm).*fs;\n% end\n \nfunction[fmin]=morsespace_low(ga,be,r,N)\n\np=morseprops(ga,be);\nfmin=frac(2*sqrt(2)*p*r,N);\n\nfunction[]=morsespace_test\nmorsespace_hightest;\nmorsespace_lowtest;\n\nfunction[]=morsespace_hightest\n%Test for high-frequncy cutoff\n\nga=3;\nbe=4;\neta=0.1;\nompeak=morsefreq(ga,be);\nN=100;\n\ndom=ompeak/N+zeros(4*N,1);\nom=cumsum(dom,1);\n\n%morse=frac(1,2)*morseafun(ga,be).*(om.^be).*exp(-om.^ga);\n\nfhigh=morsehigh(ga,be,eta);\n[psi,morse] = morsewave(10000,ga,be,fhigh);\nreporttest('MORSESPACE high-frequency cutoff',aresame(morse(end/2)./2,eta,1e-3))\n\nfunction[]=morsespace_lowtest\n%Test for low-frequency cutoff\n\nN=1001;\nga1=(1/3:1:11);\nbe1=(1:1:10);\n%ga1=(1/3:.5:11);\n%be1=(1:.5:10);\n\n[ga,be]=meshgrid(ga1,be1);\nvcolon(ga,be);\n[a,sigt,sigo]=morsebox(ga,be);\n\npsi=zeros(N,length(ga));\nfor i=1:length(ga)\n fs{i}=morsespace(ga(i),be(i),{0.95,pi},{1,N/10},4);\n psi(:,i)=morsewave(N,ga(i),be(i),fs{i}(end),'energy');\nend\n%figure,plot(sum(squared(psi((end+1)/2-50:(end+1)/2+50,:)),1))\nbool=aresame(median(sum(squared(psi((end+1)/2-50:(end+1)/2+50,:)))),0.95,0.01);\n\nreporttest('MORSESPACE low-frequency cutoff, P approximates 95% energy',bool)\n\n%fs=morsespace(2,2,10000);\n%psi=morsewave(10000,2,2,fs(end),'energy');\n%Can make a figure with the wavelet shifted by 2000 points each time\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/jWavelet/morsespace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7909278348011392}} {"text": "function [ value, en ] = wew_a ( x )\n\n%*****************************************************************************80\n%\n%% WEW_A estimates Lambert's W function.\n%\n% Discussion:\n%\n% For a given X, this routine estimates the solution W of Lambert's \n% equation:\n%\n% X = W * EXP ( W )\n%\n% This routine has higher accuracy than WEW_B.\n%\n% Modified:\n%\n% 11 June 2014\n%\n% Reference:\n%\n% Fred Fritsch, R Shafer, W Crowley,\n% Algorithm 443: Solution of the transcendental equation w e^w = x,\n% Communications of the ACM,\n% October 1973, Volume 16, Number 2, pages 123-124.\n%\n% Parameters:\n%\n% Input, real X, the argument of W(X)\n%\n% Output, real VALUE, the estimated value of W(X).\n%\n% Output, real EN, the last relative correction to W(X).\n%\n c1 = 4.0 / 3.0;\n c2 = 7.0 / 3.0;\n c3 = 5.0 / 6.0;\n c4 = 2.0 / 3.0;\n%\n% Initial guess.\n%\n f = log ( x );\n\n if ( x <= 6.46 )\n\n wn = x .* ( 1.0 + c1 * x ) ./ ( 1.0 + x .* ( c2 + c3 * x ) );\n zn = f - wn - log ( wn );\n\n else\n\n wn = f;\n zn = - log ( wn );\n\n end\n%\n% Iteration 1.\n%\n temp = 1.0 + wn;\n y = 2.0 * temp .* ( temp + c4 * zn ) - zn;\n wn = wn .* ( 1.0 + zn .* y ./ ( temp .* ( y - zn ) ) );\n%\n% Iteration 2.\n%\n zn = f - wn - log ( wn );\n temp = 1.0 + wn;\n temp2 = temp + c4 * zn;\n en = zn .* temp2 ./ ( temp .* temp2 - 0.5 * zn );\n wn = wn .* ( 1.0 + en );\n\n value = wn;\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/toms443/wew_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7909075987659806}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1 \n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the \n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\n\n\nfor i=1:length(X)\n distance = inf;\n for j=1:K\n kDist = norm(X(i, :) - centroids(j, :));\n if (kDist < distance)\n distance = kDist;\n idx(i) = j;\n end\n end\nend\n\n\n\n\n% =============================================================\n\nend\n\n", "meta": {"author": "merwan", "repo": "ml-class", "sha": "0b06b73d4aac0b8d7c726325200c3781b5c9d3b0", "save_path": "github-repos/MATLAB/merwan-ml-class", "path": "github-repos/MATLAB/merwan-ml-class/ml-class-0b06b73d4aac0b8d7c726325200c3781b5c9d3b0/mlclass-ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.7908771993085744}} {"text": "% Entropy: Returns entropy (in bits) of each column of 'X'\n% by Will Dwinnell\n%\n% H = Entropy(X)\n%\n% H = row vector of calculated entropies (in bits)\n% X = data to be analyzed\n%\n% Example: Measure sample entropy of observations of variables with\n% 1, 2, 3 and 4 bits of entropy.\n%\n% Note: Estimated entropy values are slightly less than true, due to\n% finite sample size.\n%\n% X = ceil(repmat([2 4 8 16],[1e3,1]) .* rand(1e3,4));\n% Entropy(X)\n%\n% Last modified: Nov-12-2006\n\nfunction H = Entropy(X)\n\n% Establish size of data\n[n m] = size(X);\n\n% Housekeeping\nH = zeros(1,m);\n\nfor Column = 1:m,\n % Assemble observed alphabet\n Alphabet = unique(X(:,Column));\n\t\n % Housekeeping\n Frequency = zeros(size(Alphabet));\n\t\n % Calculate sample frequencies\n for symbol = 1:length(Alphabet)\n Frequency(symbol) = sum(X(:,Column) == Alphabet(symbol));\n end\n\t\n % Calculate sample class probabilities\n P = Frequency / sum(Frequency);\n\t\n % Calculate entropy in bits\n % Note: floating point underflow is never an issue since we are\n % dealing only with the observed alphabet\n H(Column) = -sum(P .* log2(P));\nend\n\n\n% God bless Claude Shannon.\n\n% EOF\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28692-entropy/Entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7908659316102814}} {"text": "function JTotal=polAngGradient(xG,systemType,lRx)\n%%POLANGGRADIENT Determine the gradient of the angle of a 2D polar\n% measurement with respect to position (gradient components for\n% velocity etc. are zero and are not provided).Atmospheric and\n% other propagation effects are not taken into account. The\n% measurement can be monostatic or bistatic, but the location of\n% the transmitter does not matter.\n%\n%INPUTS: xG A 2XN set of Cartesian locations in the format [x;y] where the\n% gradient is desired.\n% systemType An optional parameter specifying the axis from which the\n% azimuth angle is measured. It is assumed that the azimuth\n% angle is given in radians. Possible values are\n% 0 (The default if omitted) The azimuth angle is\n% counterclockwise from the x axis.\n% 1 The azimuth angle is measured clockwise from the y axis.\n% lRx The 2X1 [x;y] location vector of the receiver in Cartesian\n% coordinates. If this parameter is omitted or an empty matrix is\n% passed, then the receiver is assumed to be at the origin.\n%\n%OUTPUTS: JTotal A 1X2XN set of gradient matrices of the polar angle taken\n% with respect to the components [x,y] in 2D in that order for\n% each of the N points in xG.\n%\n%The conversion utilizing bistatic polar measurements in 2D is similar to\n%that using bistatic r-u-v measurements in 3D, which is discussed in [1].\n%Basic differentiation was analytically performed to obtain the expressions\n%used in this file.\n%\n%Note that normally we would convert the point to the local coordinate\n%system as\n%xLocal=M*(xG(1:2,curPoint)-lRx(1:2))\n%then compute the gradient J, and then undo the effects of the rotation\n%matrix M in the end to the global coordinates as JTotal=J*M.\n%However, that is not necessary with polar angles, due to cancellations.\n%Say that M=[m11,m12;m21,m22] is a rotation matrix. Then, the partial\n%derivative with respect to x is explicitly: \n%((m12*m21-m11*m22)*y)/((m11^2+m21^2)*x^2+2*(m11*m12+m21*m22)*x*y+(m12^2+m22^2)*y^2)\n%However, one will see that because M is a rotation matrix and M*M'=eye(2)\n%then m12*m21-m11*m22=-1, m11^2+m21^2=m12^2+m22^2=1, and m11*m12+m21*m22=0,\n%which is the same as if no rotation matrix were present. Basically, all M\n%does is add a constant to the direction angle; it does not change any of\n%the derivatives. Thus, M does not matter for the Jacobian.\n%\n%EXAMPLE:\n%Here, we verify that a numerically differentiated Jacobian is consistent\n%with the analytic one produced by this function.\n% x=[100;-1000];\n% lRx=[500;20];\n% epsVal=1e-5;\n% systemType=0;\n% M=randRotMat(2);\n% J=polAngGradient(x,systemType,lRx);\n% \n% theta=getPolAngle(x,systemType,lRx,M);\n% thetadX=getPolAngle(x+[epsVal;0],systemType,lRx,M);\n% thetadY=getPolAngle(x+[0;epsVal],systemType,lRx,M);\n% \n% JNumDiff=[(thetadX-theta)/epsVal;(thetadY-theta)/epsVal];\n% max(abs((J(:)-JNumDiff(:))./J(:)))\n%The relative error will be on the order of 1e-8, indicating good agreement\n%between the numerical Jacobian vector and the actual Jacobian vector.\n%\n%REFERENCES:\n%[1] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems \n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%February 2017 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=size(xG,2);\n\n%M does not matter, so we do not need to check whether it is given.\n\nif(nargin<3||isempty(lRx))\n lRx=zeros(2,1);\nend\n\nif(nargin<2||isempty(systemType))\n systemType=0; \nend\n\nJTotal=zeros(1,2,N);\nfor curPoint=1:N\n %Convert the point into the local coordinate system of the receiver.\n xLocal=xG(1:2,curPoint)-lRx(1:2);\n \n xL=xLocal(1);\n yL=xLocal(2);\n\n J=zeros(1,2);\n switch(systemType)\n case 0\n %Derivative with respect to x.\n J(1,1)=-yL/(xL^2+yL^2);\n\n %Derivative with respect to y.\n J(1,2)=xL/(xL^2+yL^2);\n case 1\n %Derivative with respect to x.\n J(1,1)=yL/(xL^2+yL^2);\n\n %Derivative with respect to y.\n J(1,2)=-xL/(xL^2+yL^2);\n otherwise\n error('Invalid system type specified.')\n end\n\n %Undo the rotation to move the gradient into the global coordinate\n %system.\n JTotal(:,:,curPoint)=J;\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Jacobians/Component_Gradients/polAngGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7908626924054755}} {"text": "function PaV = calc_Pa(H0,betaV,dkV)\n%Actuarial probability of complication using Cox model \n\nPaV = 1 - exp(-H0 .* exp(betaV.*dkV));\n\n\n%Test-1:\n% tol = 10^-5;\n% expectedp10 = 0.1;\n% H0=0.01;\n% B = 0.05;\n% d10 = 47.096;\n% p10 = calc_Pa(H0,B,d10);\n% assertAlmostEqual(p10,expectedp10,tol);\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/calc_Pa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7907795241556154}} {"text": "function Rets = Simulate_Jump_Diffusion_Log_Returns_func( N_sim, dt, r, q, sigma, jumpModel, jumpParams )\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Simulates Log Returns of Jump Diffusion Models with jumps (including simple Black-Scholes, no jumps)\n% Returns: paths of dimension (N_sim, M+1), since they include S_0 \n% ... Simulates N_sim paths, each row is a full path starting from S_0, ending with S_M (M+1 points in path)\n% Author: Justin Lars Kirkby\n%\n% -----------------\n% Params\n% -----------------\n% N_sim = # paths\n% M = #time steps on [0,T], time step is dt=T/M, so each path has M+1 points\n% T = time to maturity, ie path is on [0,T]\n% S_0 = initial underlying value (e.g. S_0=100)\n% r = interst rate (e.g. r = 0.05)\n% q = dividend yield (e.g. q = 0.05)\n% sigma = diffusion parameter (e.g. sigma = 0.2)\n%\n%===================================\n% jumpModel: 0 = NoJumps, 1 = NormalJumps, 2 = DEJumps, 3 = MixedNormalJumps\n%===================================\n% jumpParams = paramters container containing all necessary params for models,\n% : if jumpModel = 0, no jump params are needed\n% : if jumpModel > 0, jumpParams must contain lambda, kappa, and any other model specific params (see below)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%==============================\n% Initialize Jump Model Params and JumpFunc (function handle)\n%==============================\n%%% NOTE: Jump Model is of the form in LOG space\n%%% X(m+1) = X(m) + drift + Brownian Component + sum(Jumps on [m,m+1])\n%%% By Jump we mean log(Y), e.g. in Merton Model, Jump ~ Normal (since we are in log space )\n\nif jumpModel > 0 %ie if there are jumps in the model\n lambda = jumpParams.lambda;\n kappa = jumpParams.kappa;\n\n Zeta = r - q - lambda*kappa; %NOTE: we are redefining r to include compensation for jump component\n lamdt = lambda*dt;\n \n if jumpModel == 1 %Normal Jumps, e.g. Merton\n muJ = jumpParams.muJ;\n sigJ = jumpParams.sigJ;\n JumpFunc = @(n) sum(muJ +sigJ*randn(n,1)); %Generates n independent jumps and sums them\n \n elseif jumpModel == 2 %Double Exponenial Jumps \n p_up = jumpParams.p_up; \n eta1 = jumpParams.eta1;\n eta2 = jumpParams.eta2; \n JumpFunc = @(n) sum(DoubleExpoRnd(n,p_up, eta1,eta2));\n \n elseif jumpModel == 3 %Mixed normal Jumps\n p_up = jumpParams.p_up;\n a1 = jumpParams.a1; b1 = jumpParams.b1;\n a2 = jumpParams.a2; b2 = jumpParams.b2;\n JumpFunc = @(n) sum(MixedNormalRnd(n, p_up, a1,b1,a2,b2));\n end\nelse \n Zeta = r - q;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nSigsqdt = sigma*sqrt(dt);\ndrift = (Zeta - .5*sigma^2)*dt;\n \nif jumpModel == 0 % Just a drifted Brownian motion\n Rets = drift + Sigsqdt*randn(N_sim,1); \nelse\n Poi = PoissonRnd(N_sim, lamdt); %Generate Poisson Column Vector of size N_Sim\n for n = 1:N_sim\n if Poi(n)>0\n Poi(n) = JumpFunc(Poi(n)); %JumpFunc(Poi(n)) sums up Poi(n) many jumps from the jump distribution\n end\n end\n\n Rets = drift + Poi + Sigsqdt*randn(N_sim,1); \nend\n\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Monte_Carlo/Simulate_Jump_Diffusion_Log_Returns_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509314, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.790738980174847}} {"text": "function quad = gauss_legendre_integrate_fast ( f, n )\n\n%*****************************************************************************80\n%\n%% GAUSS_LEGENDRE_INTEGRATE_FAST applies a Gauss-Legendre quadrature rule.\n%\n% Discussion:\n%\n% The integration is carried out on the standard interval [-1,1].\n%\n% The computation should be very efficient in MATLAB.\n%\n% Modified:\n%\n% 03 March 2007\n%\n% Author:\n%\n% Lloyd Trefethen\n%\n% Reference:\n%\n% Lloyd Trefethen,\n% Is Gauss Quadrature Better than Clenshaw-Curtis?\n% SIAM Review,\n% Volume 50, Number 1, 2008, pages 67-87.\n%\n% Parameters:\n%\n% Input, function F ( x ), the function to be integrated.\n%\n% Input, integer N, the order of the quadrature rule.\n%\n% Output, real QUAD, the estimate for the integral of F(X).\n%\n beta = 0.5 ./ sqrt ( 1 - ( 2 * ( 1:n ) ) .^ (-2) );\n\n tridiag = diag ( beta, 1 ) + diag ( beta, -1 );\n\n [ eigval, eigvec ] = eig ( tridiag );\n\n x = diag ( eigvec );\n [ x, i ] = sort ( x );\n w = 2 * eigval(1,i) .^ 2;\n\n quad = w * feval ( f, x );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule_fast/gauss_legendre_integrate_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7907389772595768}} {"text": "function value = c8mat_norm_fro ( m, n, a )\n\n%*****************************************************************************80\n%\n%% C8MAT_NORM_FRO returns the Frobenius norm of a C8MAT.\n%\n% Discussion:\n%\n% The Frobenius norm is defined as\n%\n% C8MAT_NORM_FRO = sqrt (\n% sum ( 1 <= I <= M ) sum ( 1 <= j <= N ) A(I,J) * A(I,J) )\n%\n% The matrix Frobenius norm is not derived from a vector norm, but\n% is compatible with the vector L2 norm, so that:\n%\n% c8vec_norm_l2 ( A * x ) <= c8mat_norm_fro ( A ) * c8vec_norm_l2 ( x ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2015\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, complex A(M,N), the matrix whose norm is desired.\n%\n% Output, real VALUE, the norm of A.\n%\n value = ...\n sqrt ...\n ( ...\n sum ...\n ( ...\n sum ...\n ( ...\n ( ...\n abs ...\n ( ...\n a(1:m,1:n) ...\n ) ...\n ) .^ 2 ...\n ) ...\n ) ...\n );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/c8lib/c8mat_norm_fro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7907389750230707}} {"text": "function jac = p12_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P12_JAC evaluates the jacobian for problem p12.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 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 for i = 1 : neqn - 1\n jac(i,i) = - i;\n end\n\n for i = 2 : neqn\n jac(i,i-1) = i - 1;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_ode/p12_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7906873918170034}} {"text": "function geometry_test068 ( )\n\n%*****************************************************************************80\n%\n%% GEOMETRY_TEST068 tests the SPHERE_DISTANCE routines.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n ntest = 6;\n\n name = [ ...\n 'Atlanta, Georgia '; ...\n 'North Pole '; ...\n 'South Pole '; ...\n 'Timbuktu '; ...\n 'San Antonio, Texas'; ...\n 'Savannah, Georgia ' ];\n lat_d = [ 33, 90, -90, 16, 29, 32 ];\n lat_m = [ 11, 0, 0, 49, 25, 5 ];\n long_d = [ 82, 0, 0, 3, 98, 81 ];\n long_m = [ 34, 0, 0, 0, 30, 6 ];\n radius = 3957.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEOMETRY_TEST068\\n' );\n fprintf ( 1, ' POINTS_DIST_SPHERE_3D measures the distance between\\n' );\n fprintf ( 1, ' two points on a sphere.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' All tests uses RADIUS = %f\\n', radius );\n fprintf ( 1, ' which is the radius of the earth in miles.\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ntest-1\n\n lat1 = dms_to_radians ( lat_d(i), lat_m(i), 0.0 );\n long1 = dms_to_radians ( long_d(i), long_m(i), 0.0 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Distance from %s\\n', name(i,:) );\n\n for j = i+1 : ntest\n\n lat2 = dms_to_radians ( lat_d(j), lat_m(j), 0.0 );\n long2 = dms_to_radians ( long_d(j), long_m(j), 0.0 );\n\n dist1 = sphere_distance1 ( lat1, long1, lat2, long2, radius );\n dist2 = sphere_distance2 ( lat1, long1, lat2, long2, radius );\n dist3 = sphere_distance3 ( lat1, long1, lat2, long2, radius );\n\n fprintf ( 1, ' to %s is %16.8f %16.8f %16.8f\\n', ...\n name(j,:), dist1, dist2, dist3 );\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_test068.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7906873763462848}} {"text": "function [ u, it_num ] = monogrid_poisson_1d ( n, a, b, ua, ub, force, exact )\n\n%*****************************************************************************80\n% \n%% MONOGRID_POISSON_1D solves a 1D PDE, using the Gauss-Seidel method.\n%\n% Discussion:\n%\n% This routine solves a 1D boundary value problem of the form\n%\n% - U''(X) = F(X) for A < X < B,\n%\n% with boundary conditions U(A) = UA, U(B) = UB.\n%\n% The Gauss-Seidel method is used. \n%\n% This routine is provided primarily for comparison with the\n% multigrid solver.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% William Hager,\n% Applied Numerical Linear Algebra,\n% Prentice-Hall, 1988,\n% ISBN13: 978-0130412942,\n% LC: QA184.H33.\n%\n% Parameters:\n%\n% Input, integer N, the number of intervals.\n%\n% Input, real A, B, the left and right endpoints of the region.\n%\n% Input, real UA, UB, the left and right boundary values.\n%\n% Input, function value = FORCE ( x ), the name of the function \n% which evaluates the right hand side.\n%\n% Input, function value = EXACT ( x ), the name of the function \n% which evaluates the exact solution.\n%\n% Output, integer IT_NUM, the number of iterations.\n%\n% Output, real U(N+1,1), the computed solution.\n%\n\n%\n% Initialization.\n%\n tol = 0.0001;\n%\n% Set the nodes.\n%\n x = ( linspace ( a, b, n + 1 ) )';\n%\n% Set the right hand side.\n%\n r = zeros ( n + 1, 1 );\n\n r(1) = ua;\n r(2:n) = force ( x(2:n) ) / n / n;\n r(n+1) = ub;\n\n u = zeros ( n + 1, 1 );\n\n it_num = 0;\n%\n% Gauss-Seidel iteration.\n%\n while ( 1 )\n\n it_num = it_num + 1;\n\n [ u, d1 ] = gauss_seidel ( n + 1, r, u );\n\n if ( d1 <= tol )\n break\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/multigrid_poisson_1d/monogrid_poisson_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7905515707325755}} {"text": "function point = intersectLinePlane(line, plane, varargin)\n%INTERSECTLINEPLANE Intersection point between a 3D line and a plane.\n%\n% PT = intersectLinePlane(LINE, PLANE)\n% Returns the intersection point of the given line and the given plane.\n% LINE: [x0 y0 z0 dx dy dz]\n% PLANE: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n% PT: [xi yi zi]\n% If LINE and PLANE are parallel, return [NaN NaN NaN].\n% If LINE (or PLANE) is a matrix with 6 (or 9) columns and N rows, result\n% is an array of points with N rows and 3 columns.\n% \n% PT = intersectLinePlane(LINE, PLANE, TOL)\n% Specifies the tolerance factor to test if a line is parallel to a\n% plane. Default is 1e-14.\n%\n% Example\n% % define horizontal plane through origin\n% plane = [0 0 0 1 0 0 0 1 0];\n% % intersection with a vertical line\n% line = [2 3 4 0 0 1];\n% intersectLinePlane(line, plane)\n% ans = \n% 2 3 0\n% % intersection with a line \"parallel\" to plane\n% line = [2 3 4 1 2 0];\n% intersectLinePlane(line, plane)\n% ans = \n% NaN NaN NaN\n%\n% See also \n% lines3d, planes3d, points3d, clipLine3d\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-02-17\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\n% extract tolerance if needed\ntol = 1e-14;\nif nargin > 2\n tol = varargin{1};\nend\n\n% unify sizes of data\nnLines = size(line, 1);\nnPlanes = size(plane, 1);\n\n% N planes and M lines not allowed \nif nLines ~= nPlanes && min(nLines, nPlanes) > 1\n error('MatGeom:geom3d:intersectLinePlane', ...\n 'Input must have same number of rows, or one must be 1');\nend\n\n% plane normal\nn = crossProduct3d(plane(:,4:6), plane(:,7:9));\n\n% difference between origins of plane and line\ndp = bsxfun(@minus, plane(:, 1:3), line(:, 1:3));\n\n% dot product of line direction with plane normal\ndenom = sum(bsxfun(@times, n, line(:,4:6)), 2);\n\n% relative position of intersection point on line (can be inf in case of a\n% line parallel to the plane)\nt = sum(bsxfun(@times, n, dp),2) ./ denom;\n\n% compute coord of intersection point\npoint = bsxfun(@plus, line(:,1:3), bsxfun(@times, [t t t], line(:,4:6)));\n\n% set indices of line and plane which are parallel to NaN\npar = abs(denom) < tol;\npoint(par,:) = NaN;\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/intersectLinePlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.7905349396810527}} {"text": "function W = compute_mesh_weight(vertex,face,type,options)\n\n% compute_mesh_weight - compute a weight matrix\n%\n% W = compute_mesh_weight(vertex,face,type,options);\n%\n% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not\n% connected in the mesh.\n%\n% type is either \n% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.\n% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex\n% i and j.\n% 'conformal': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j)\n%\n% If options.normalize=1, the the rows of W are normalize to sum to 1.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n[vertex,face] = check_face_vertex(vertex,face);\n\nnface = size(face,1);\nn = max(max(face));\n\nverb = getoptions(options, 'verb', n>5000);\n\nif nargin<3\n type = 'conformal';\nend\n\nswitch lower(type)\n case 'combinatorial'\n W = triangulation2adjacency(face);\n case 'distance'\n W = my_euclidean_distance(triangulation2adjacency(face),vertex);\n W(W>0) = 1./W(W>0);\n W = (W+W')/2; \n case 'conformal'\n % conformal laplacian\n W = sparse(n,n);\n ring = compute_vertex_face_ring(face);\n for i = 1:n\n if verb\n progressbar(i,n);\n end\n for b = ring{i}\n % b is a face adjacent to a\n bf = face(:,b);\n % compute complementary vertices\n if bf(1)==i\n v = bf(2:3);\n elseif bf(2)==i\n v = bf([1 3]);\n elseif bf(3)==i\n v = bf(1:2);\n else\n error('Problem in face ring.');\n end\n j = v(1); k = v(2);\n vi = vertex(:,i);\n vj = vertex(:,j);\n vk = vertex(:,k);\n % angles\n alpha = myangle(vk-vi,vk-vj);\n beta = myangle(vj-vi,vj-vk);\n % add weight\n W(i,j) = W(i,j) + cot( alpha );\n W(i,k) = W(i,k) + cot( beta );\n end\n end\n otherwise\n error('Unknown type.')\nend\n\nif isfield(options, 'normalize') && options.normalize==1\n W = diag(sum(W,2).^(-1)) * W;\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction beta = myangle(u,v);\n\ndu = sqrt( sum(u.^2) );\ndv = sqrt( sum(v.^2) );\ndu = max(du,eps); dv = max(dv,eps);\nbeta = acos( sum(u.*v) / (du*dv) );\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction W = my_euclidean_distance(A,vertex)\n\nif size(vertex,1) size(alpha,1)\n\talpha = alpha';\nend\n\nif nargin < 2 || isempty(sz)\n sz = circ_ang2rad(1);\nend\n\nif nargin < 3\n w = ones(size(alpha));\nelse\n if length(alpha)~=length(w)\n error('Input length does not match.')\n end\n w =w(:); \nend\n\nalpha = mod(alpha,2*pi);\nn = sum(w);\ndg = 0:sz:pi;\n\nm1 = zeros(size(dg));\nm2 = zeros(size(dg));\nfor i=1:length(dg)\n m1(i) = sum((alpha > dg(i) & alpha < pi + dg(i)).*w); \n m2(i) = n - m1(i);\nend\nm = min(min([m1;m2]));\n\nif n > 50\n % approximation by Ajne (1968)\n A = pi*sqrt(n) / 2 / (n-2*m);\n pval = sqrt(2*pi) / A * exp(-pi^2/8/A^2);\nelse\n % exact formula by Hodges (1955)\n pval = 2^(1-n) * (n-2*m) * nchoosek(n,m); \nend\n\n \n \n\n\n\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/external/CircStat2012a/circ_otest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7904445212091604}} {"text": "function y = gprctile(x,p)\n%GPRCTILE Percentile(s) of a grouped sample.\n% In some scientific works, once the data have been gathered from a \n% population of interest, it is often difficult to get a sense of what \n% the data indicate when they are presented in an unorganized fashion. \n% Assembling the raw data into a meaningful form, such as a frequency \n% distribution, makes the data easier to understand and interpret. It is\n% in the context of frequency distributions that the importance of \n% conveying in a succinct way numerical information contained in the data\n% is encountered.\n% So, grouped data is data that has been organized into groups known as\n% classes. The raw dataset can be organized by constructing a table \n% showing the frequency distribution of the variable (whose values are \n% given in the raw dataset). Such a frequency table is often referred to\n% as grouped data.\n% Here, we developed a m-code to calculate the percentile(s) of a grouped\n% data. One can input the returns or modified vectors n and xout \n% containing the frequency counts and the bin locations of the hist \n% m-function, in a column form matrix.\n%\n% Percentile calculation uses the straight forward formula,\n%\n% P = L + I*(N*P/100 - C)/F\n%\n% where:\n% L = lower limit of the interval containing the percentile \n% I = width of the interval containing the percentile \n% N = total number of data \n% P = interested percentile\n% C = cumulative frequency corresponding to the previous percentile class \n% F = number of cases in the interval containing the percentile\n% \n% Syntax: function y = gprctile(x,p) \n% \n% Inputs:\n% x - data matrix (Size of matrix must be n-by-2; absolut frequency=\n% column 1, class mark=column 2) \n% p - is a scalar or a vector of percent values\n% Outputs:\n% y - percentile(s) of the values in x\n%\n% Example: From the example given at\n% http://www.emathzone.com/tutorials/basic-statistics/frequency-distributi\n% on-of-discrete-data.html\n% We are interested to get the percentile values 15,30,60,80.\n%\n% Data: 2,4,6,1,3,5,3,7,8,6,4,7,4,4,2,1,3,6,4,2,5,7,9,1,2,10,1,8,9,2,3,1,\n% 2,3,4,4,4,6,6,5,5,4,5,8,5,4,3,3,2,5,0,5,9,9,8,10,0,4,10,10,1,1,2,2,1,8,\n% 6,9,10\n%\n% Using [A,B] = hist(x,11)\n%\n% x = [B' A']; p = [15,30,60,80];\n%\n% ----------------\n% MC F\n% ----------------\n% 0.4545 2\n% 1.3636 8\n% 2.2727 9\n% 3.1818 7\n% 4.0909 11\n% 5.0000 8\n% 5.9091 6\n% 6.8182 3\n% 7.7273 5\n% 8.6364 5\n% 9.5455 5\n% ----------------\n%\n% Calling on Matlab the function: \n% y = gprctile(x,p)\n%\n% Answer is:\n%\n% y = 1.8535 2.9481 5.0455 7.4909\n%\n% Created by A. Trujillo-Ortiz, R. Hernandez-Walls and R. Preciado-Perez\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.edu.mx\n%\n% Copyright (C) September 15, 2012.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls and R. Preciado-Perez. (2012). \n% gprctile:Percentile(s) of a grouped sample. [WWW document].\n% URL http://www.mathworks.com/matlabcentral/fileexchange/\n% 38228-gprctile\n%\n% Reference:\n% Cann, A. J. (2003), Maths from Scratch for Biologists. John Willey &\n% Sons Ltd. Chichester:England.\n%\n\nc = size(x,2);\n\nif c ~= 2\n error('stats:gprctile:BadData','X must have two colums.');\nend\n\nif ~isvector(p) || numel(p) == 0\n error('stats:gprctile:BadProbs', ...\n 'P must be a scalar or a non-empty vector.');\nelseif any(p < 0 | p > 100) || ~isreal(p)\n error('stats:gprctile:BadPercents', ...\n 'P must take real values between 0 and 100');\nend\n\nmc = x(:,1); %class mark\nf = x(:,2); %absolut frequency\na = mc(2) - mc(1); %class interval\nfa = cumsum(f); %cumulative absolut frequency\nn = fa(end); %sample size\n\ny = [];\nfor i = 1:length(p)\n r(i) = n*p(i)/100; %interested ordened data (iod)\n cl(i) = min(find(fa > r(i))); %class where the iod are\n l(i) = mc(cl(i));\n L(i) = l(i) - 0.5*a; %lower class boundary\n A(i) =(a/f(cl(i)));\n if (cl(i) - 1) == 0;\n B(i) = r(i);\n else\n B(i) = (r(i) - fa(cl(i) - 1));\n end\n \n yy = L(i) + A(i)*B(i); %calculation by a linear interpolation\n y = [y yy];\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/38228-gprctile/gprctile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7904445186564726}} {"text": "function [H,R] = myqr (A)\n%MYQR QR factorization using Householder reflections\n% uses function [v,beta,xnorm] = hmake1 (x)\n% and function hx = happly (v, beta, x)\n%\n% Example\n% [H,R] = myqr (A)\n% See also: testall\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n\n[m n] = size (A) ;\n\nH = zeros (m,n) ;\nR = zeros (m,n) ;\n\nfor k = 1:n\n\n % apply prior H's\n % fprintf ('\\n-----------------init %d\\n', k) ;\n x = A (:,k) ;\n for i = 1:k-1\n v = H(((i+1):m),i) ;\n v = [1 ; v] ; %#ok\n beta = H (i,i) ;\n % n1 = norm (x (i:m)) ;\n x (i:m) = happly (v, beta, x (i:m)) ;\n % n2 = norm (x (i:m)) ;\n % fprintf ('=============== i %d %g %g\\n', i, n1, n2) ;\n % beta\n % v'\n % X = x'\n % pause\n % i\n % x\n end\n % k\n % x\n\n % make Hk\n % fprintf ('x(k:m) = ') ; x (k:m)\n [v,beta,xnorm] = hmake1 (x (k:m)) ;\n\n H (k,k) = beta ;\n H (k+1:m, k) = v (2:end) ;\n\n R (1:(k-1),k) = x (1:(k-1)) ;\n R (k,k) = xnorm ;\n % full (R)\n % pause\nend\n\n% s2 = svd (full (R)) ;\n% [s1 s2 s1-s2]\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/myqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7902912885809091}} {"text": "function [col4row,row4col,gain]=linBottleneckAssign(C,solSel)\n%%LINBOTTLENECKASSIGN Solve the linear bottleneck assignment problem for a\n% square cost matrix. The problem being solved can be formulated\n% as\n% gain=minimize_phi max_i C_{i,phi(i)} where phi is a permutation\n% vector.\n% It can also be formulated as:\n% gain=minimize_{x} max_{i,j} C_{i,j}*x_{i,j}\n% subject to\n% \\sum_{j=1}^{n}x_{i,j}=1 for all i\n% \\sum_{i=1}^{n}x_{i,j}=1 for all j\n% x_{i,j}=0 or 1.\n%\n%INPUTS: C An nXn cost matrix that does not contain any NaNs.\n% solSel Multiple optimal solutions typically exist to this problem. This\n% parameter specifies which solution to choose. Possible values\n% are:\n% 0 (The default if omitted or an empty matrix is passed) Choose\n% a feasible solution without any particular property.\n% 1 Choose the optimal solution that also minimizes\n% sum_i C_{i,phi(i)}.\n% 2 Choose the optimal solution that also maximizes\n% sum_i C_{i,phi(i)}.\n%\n%OUTPUTS: col4row An nX1 vector where the entry in each element is an\n% assignment of the element in that row to a column. This\n% is equivalent to phi above.\n% row4col A nX1 vector where the entry in each element is an\n% assignment of the element in that column to a row.\n% gain The value of the cost function of the linear bottleneck\n% assignment problem at the optimal point.\n%\n%This function implements Algorithm 6.1 of Chapter 6.2 of [1]. This is an\n%algorithm based on thresholding. The choice of which solution is obtained\n%in the end depends on whether one uses maxCardBipartMatching in the final\n%step, or whether one modifies the cost matrix in the final step according\n%to G (forbidden assignments become either Inf or -Inf) and then uses\n%assign2D to solve the problem.\n%\n%EXAMPLE:\n%This is example 6.5 from Chapter 6.2 of [1].\n% C=[8,2,3,3;\n% 2,7,5,8;\n% 0,9,8,4;\n% 2,5,6,3];\n% [col4row,row4col,gain]=linBottleneckAssign(C)\n% %Verify the value of the cost function for the permutation.\n% n=size(C,1);\n% costVal=-Inf;\n% for curRow=1:n\n% cij=C(curRow,col4row(curRow));\n% if(cij>costVal)\n% costVal=cij;\n% end\n% end\n% costVal\n%One will see that gain=5 and costVal agrees with the gain. The cost value\n%is five even though the col4row assignment is not identical to the in the\n%book. Solution variations depend on variations to the algiruthm used for\n%the perfect matching. Here, maxCardBipartMatching is used.\n%\n%REFERENCES:\n%[1] R. Burkard, M. Dell'Amico, and S. Martello,Assignment Problems.\n% Philadelphia: Society for Industrial and Applied Mathematics, 2009.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(solSel))\n solSel=0;\nend\n\nn=size(C,1);\n\nc0=min(C(:));\nc1=max(C(:));\n\nif(c0==c1)\n col4row=(1:n).';\n row4col=(1:n).';\n gain=c0; \n return;\nend\n\nsel=Cc0;\nCSel=C(sel);\nif(isempty(CSel))\n %This instance can occur, for example, if the matrix contains only two\n %values, such as if C is the identity matrix.\n cStar=c1;\nelse\n while(~isempty(CSel))\n cStar=medianHi(CSel(:));\n [c0,c1]=feasCheck(C,cStar,c0,c1);\n\n sel=Cc0;\n CSel=C(sel);\n end\nend\n\nif(cStar~=c0)\n [~,c1]=feasCheck(C,c0,c0,c1);\nend\n\nG=(C<=c1);\nswitch(solSel)\n case 0\n [col4row,row4col]=maxCardBipartMatching(G);\n case 1\n CNew=Inf(n,n);\n CNew(G)=C(G);\n [col4row,row4col]=assign2D(CNew,false);\n if(isempty(col4row))%If the cost wouldn't have been finite.\n [col4row,row4col]=maxCardBipartMatching(G);\n end\n case 2\n CNew=-Inf(n,n);\n CNew(G)=C(G);\n [col4row,row4col]=assign2D(CNew,true);\n if(isempty(col4row))%If the cost wouldn't have been finite.\n [col4row,row4col]=maxCardBipartMatching(G);\n end\n otherwise\n error('Unknown solution selected.')\nend\ngain=c1;\n\nend\n\nfunction [c0,c1]=feasCheck(C,cStar,c0,c1)\n\nG=(C<=cStar);\ncol4row=maxCardBipartMatching(G);\n\nif(all(col4row~=0))\n %It is feasible.\n c1=cStar;\nelse\n %It is infeasible.\n c0=cStar;\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/Assignment_Algorithms/2D_Assignment/linBottleneckAssign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7902912866331786}} {"text": "function c = correlation_power ( n, rho, rho0, e )\n\n%*****************************************************************************80\n%\n%% CORRELATION_POWER evaluates the power correlation function.\n%\n% Discussion:\n%\n% The power correlation is\n%\n% C(rho) = ( 1 - |rho| )^e if 0 <= |rho| <= 1\n% = 0 otherwise\n%\n% The constraint on the exponent is 2 <= e.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of arguments.\n%\n% Input, real RHO(N,1), the arguments.\n% 0.0 <= RHO.\n%\n% Input, real RHO0, the correlation length.\n% 0.0 < RHO0.\n%\n% Input, real E, the exponent.\n% E has a default value of 2;\n% 2 <= E.\n%\n% Output, real C(N,1), the correlations.\n%\n if ( nargin < 4 )\n e = 2.0;\n end\n\n c = zeros ( n, 1 );\n\n rho1 = abs ( rho ( : ) ) / rho0;\n \n i = find ( rho1 <= 1 );\n \n c(i) = ( 1.0 - rho1(i) ) .^ e;\n\n return\nend\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/correlation/correlation_power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7902912811071556}} {"text": "% Black-Scholes implied vol\n%\n% sigma=impvol(C,S,K,r,t,T,q,tol)\n%\n% C: call price (scalar or vector)\n% S: Stock price (scalar or vector)\n% K: Strike price (scalar or vector)\n% r: Interest rate (scalar or vector)\n% t: Time now (scalar or vector)\n% T: Maturity date (scalar or vector)\n% [q]: Dividend yield (scalar or vector). Default=0;\n% [tol]: Tolerance. Default=1e-6\n\nfunction sigma=impvol(C,S,K,r,t,T,q,tol)\n\nT=T-t;\n\nif nargin<8\n tol=1e-6;\nend\n\nif nargin<7 || isempty(q)\n q=0;\nend\n\nF=S*exp((r-q).*T);\nG=C.*exp(r.*T);\n\nalpha=log(F./K)./sqrt(T);\nbeta=0.5*sqrt(T);\n\n% Now we need to solve G=F Phi(d1)- K Phi(d2) where\n% d1=alpha/sigma+beta and d2=alpha/sigma-beta\n\na=beta.*(F+K);\nb=sqrt(2*pi)*(0.5*(F-K)-G);\nc=alpha.*(F-K);\n\ndisc=max(0,b.^2-4*a.*c);\n\nsigma0=(-b+sqrt(disc))./(2*a);\n\nsigma=NewtonMethod(sigma0);\n\n function s1=NewtonMethod(s0)\n \n s1=s0;\n count=0;\n f=@(x) call(S,K,r,x,0,T,q)-C;\n fprime=@(x) call_vega(S,K,r,x,0,T,q);\n \n max_count=1e3;\n \n while max(abs(f(s1)))>tol && counttol\n disp('Newton method did not converge')\n end\n end\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28682-black-scholes-call-and-implied-vol-functions/impvol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7901204967221093}} {"text": "function out = planesBisector(plane1, plane2)\n% PLANESBISECTOR Bisector plane between two other planes\n% \n% BIS = planesBisector(PL1, PL2);\n% Returns the planes that contains the intersection line between PL1 and\n% PL2 and that bisect the dihedral angle of PL1 and PL2. \n% Note that computing the bisector of PL2 and PL1 (in that order) returns\n% the same plane but with opposite orientation.\n%\n% Example\n% % Draw two planes together with their bisector\n% pl1 = createPlane([3 4 5], [1 2 3]);\n% pl2 = createPlane([3 4 5], [2 -3 4]);\n% % compute bisector\n% bis = planesBisector(pl1, pl2);\n% % setup display\n% figure; hold on; axis([0 10 0 10 0 10]);\n% set(gcf, 'renderer', 'opengl')\n% view(3);\n% % draw the planes\n% drawPlane3d(pl1, 'g');\n% drawPlane3d(pl2, 'g');\n% drawPlane3d(bis, 'b');\n%\n% See also\n% planes3d, dihedralAngle, intersectPlanes\n%\n% Author: Ben X. Kang\n% Dept. Orthopaedics & Traumatology\n% Li Ka Shing Faculty of Medicine\n% The University of Hong Kong\n% Pok Fu Lam, Hong Kong\n%\n\n% Let the two planes be defined by equations\n% \n% a1*x + b1*y + c1*z + d1 = 0\n% \n% and\n% \n% a2*x + b2*y + c2*z + d2 = 0\n% \n% in which vectors [a1,b1,c1] and [a2,b2,c2] are normalized to be of unit\n% length (a^2+b^2+c^2 = 1). Then \n% \n% (a1+a2)*x + (b1+b2)*y + (c1+c2)*z + (d1+d2) = 0\n% \n% is the equation of the desired plane which bisects the dihedral angle\n% between the two planes. These coefficients cannot be all zero because\n% the two given planes are not parallel.\n% \n% Notice that there is a second solution to this problem\n% \n% (a1-a2)*x + (b1-b2)*y + (c1-c2)*z + (d1-d2) = 0\n% \n% which also is a valid plane and orthogonal to the first solution. One of\n% these planes bisects the acute dihedral angle, and the other the\n% supplementary obtuse dihedral angle, between the two given planes. \n\n\nP1 = plane1(1:3);\t\t\t% a point on the plane\nn1 = planeNormal(plane1);\t% the normal of the plane\n% d1 = -dot(n1, P1);\t\t% for line equation\n\nP2 = plane2(1:3);\nn2 = planeNormal(plane2);\n% d2 = -dot(n2, P2);\n\nif ~isequal(P1(1:3), P2(1:3))\n\tL = intersectPlanes(plane1, plane2);\t% intersection of the given two planes\n\tPt = L(1:3);\t\t\t\t\t\t\t% a point on the line intersection\n% \tv2 = cross(n1-n2, L(4:6));\t\t\t\t% another vector lie on the bisect plane\n% \tout = [v1, v2]';\nelse\n\tPt = P1(1:3);\nend\n\n% use column-wise vector\nout = createPlane(Pt, n1 - n2);\n\n\n%% EOF %%", "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/planesBisector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7901204942804545}} {"text": "function [Jacobian, Joint] = ARM_2DOF(L1, L2, theta1, theta2, draw, orgX, orgY)\n%% Function Configuration\nif (nargin == 5)\n orgX = 0;\n orgY = 0;\nend\n\n%% Modelling of the Manipulator\nX(1)= orgX+ L1*cosd(theta1);\nY(1)= orgY+ L1*sind(theta1);\nX(2)= X(1)+ L2*cosd(theta1 + theta2);\nY(2)= Y(1)+ L2*sind(theta1 + theta2);\n\n% Storing the Joint Locations of the Manipulator\nJoint = [orgX, orgY; X(1), Y(1); X(2), Y(2)];\n\n% Storing the Jacobian matrix for the current Manipulator configuration\nJacobian = [-L1*sind(theta1) - L2*sind(theta1+theta2), -L2*sind(theta1+theta2);\n L1*cosd(theta1)+ L2*cosd(theta1+theta2), L2*cosd(theta1+theta2)];\n\n% If it was mentioned in the parameter 'draw' then draw the manipulator.\nif draw == true\n plot([orgX,X(1)],[orgY,Y(1)]);\n hold on\n plot([X(1),X(2)],[Y(1),Y(2)]);\n axis([-(L1 + L2), (L1 + L2), -(L1 + L2), (L1 + L2)]);\n hold off;\n title('2 DOF Planar Manipulator');\n legend('1st Link of Arm', '2nd Link of Arm');\n drawnow;\nend\n\nend\n\n", "meta": {"author": "YashBansod", "repo": "Robotics-Planning-Dynamics-and-Control", "sha": "ee8984dd5f090b803c87ac9fdf4f9be625787b2b", "save_path": "github-repos/MATLAB/YashBansod-Robotics-Planning-Dynamics-and-Control", "path": "github-repos/MATLAB/YashBansod-Robotics-Planning-Dynamics-and-Control/Robotics-Planning-Dynamics-and-Control-ee8984dd5f090b803c87ac9fdf4f9be625787b2b/2_2DOF_Manipulator_Inverse_Kinematics/INV-functions/ARM_2DOF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7900131135651798}} {"text": "function [v,usediters] = projfunc( s, k1, k2, nn )\n\n% Solves the following problem:\n% Given a vector s, find the vector v having sum(abs(v))=k1 \n% and sum(v.^2)=k2 which is closest to s in the euclidian sense.\n% If the binary flag nn is set, the vector v is additionally\n% restricted to being non-negative (v>=0).\n% \n% Written 2.7.2004 by Patrik O. Hoyer\n%\n \n% Problem dimension\nN = length(s);\n\n% If non-negativity flag not set, record signs and take abs\nif ~nn,\n isneg = s<0;\n s = abs(s);\nend\n\n% Start by projecting the point to the sum constraint hyperplane\nv = s + (k1-sum(s))/N;\n\n% Initialize zerocoeff (initially, no elements are assumed zero)\nzerocoeff = [];\n\nj = 0;\nwhile 1,\n\n % This does the proposed projection operator\n midpoint = ones(N,1)*k1/(N-length(zerocoeff));\n midpoint(zerocoeff) = 0;\n w = v-midpoint;\n a = sum(w.^2);\n b = 2*w'*v;\n c = sum(v.^2)-k2;\n alphap = (-b+real(sqrt(b^2-4*a*c)))/(2*a);\n v = alphap*w + v;\n \n if all(v>=0),\n\t% We've found our solution\n\tusediters = j+1;\n\tbreak;\n end\n \n j = j+1;\n \n % Set negs to zero, subtract appropriate amount from rest\n zerocoeff = find(v<=0);\n v(zerocoeff) = 0;\n tempsum = sum(v);\n v = v + (k1-tempsum)/(N-length(zerocoeff));\n v(zerocoeff) = 0;\n \nend\n\n% If non-negativity flag not set, return signs to solution\nif ~nn,\n v = (-2*isneg + 1).*v;\nend\n\n% Check for problems\nif max(max(abs(imag(v))))>1e-10,\n error('Somehow got imaginary values!');\nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/nmfpack/code/projfunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.79001311167851}} {"text": "function inside = circle_sector_contains_point_2d ( r, center, theta1, theta2, p )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SECTOR_CONTAINS_POINT_2D : is a point inside a circular sector?\n%\n% Discussion:\n%\n% A circular sector is formed by a circular arc, and the two straight line \n% segments that join its ends to the center of the circle.\n%\n% A circular sector is defined by\n%\n% ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 = R**2\n%\n% and\n%\n% Theta1 <= Theta <= Theta2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2), the center of the circle.\n%\n% Input, real THETA1, THETA2, the angles defining the arc,\n% in radians. Normally, THETA1 < THETA2.\n%\n% Input, real P(2), the point to be checked.\n%\n% Output, logical INSIDE, is TRUE if the point is inside or on the\n% circular sector, FALSE otherwise.\n%\n inside = 0;\n%\n% Is the point inside the (full) circle?\n%\n if ( ( p(1) - center(1) ) * ( p(1) - center(1) ) ...\n + ( p(2) - center(2) ) * ( p(2) - center(2) ) <= r * r )\n%\n% Is the point's angle within the arc's range?\n% Try to force the angles to lie between 0 and 2 * PI.\n%\n theta = r8_atan ( p(2) - center(2), p(1) - center(1) );\n\n if ( r8_modp ( theta - theta1, 2.0 * pi ) <= ...\n r8_modp ( theta2 - theta1, 2.0 * pi ) )\n\n inside = 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/cvt_movie3/circle_sector_contains_point_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7899975529421039}} {"text": "function vs = sphere01_triangle_vertices_to_centroid ( v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% SPHERE01_TRIANGLE_VERTICES_TO_CENTROID gets a spherical triangle centroid.\n%\n% Discussion:\n%\n% A unit sphere centered at 0 in 3D satisfies the equation:\n%\n% X*X + Y*Y + Z*Z = 1\n%\n% A spherical triangle is specified by three points on the sphere.\n%\n% The (true) centroid of a spherical triangle is the point\n%\n% VT = (XT,YT,ZT) = Integral ( X, Y, Z ) dArea / Integral 1 dArea\n%\n% Note that the true centroid does NOT, in general, lie on the sphere. \n%\n% The \"flat\" centroid VF is the centroid of the planar triangle defined by\n% the vertices of the spherical triangle.\n%\n% The \"spherical\" centroid VS of a spherical triangle is computed by\n% the intersection of the geodesic bisectors of the triangle angles.\n% The spherical centroid lies on the sphere.\n%\n% VF, VT and VS lie on a line through the center of the sphere. We can\n% easily calculate VF by averaging the vertices, and from this determine\n% VS by normalizing.\n%\n% Of course, we still will not have actually computed VT, which lies\n% somewhere between VF and VS!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real V1(3), V2(3), V3(3), the vertices of the triangle.\n%\n% Output, real VS(3), the coordinates of the \"spherical\n% centroid\" of the spherical triangle.\n%\n vs(1:3) = ( v1(1:3) + v2(1:3) + v3(1:3) ) / 3.0;\n\n norm = sqrt ( sum ( vs(1:3).^2 ) );\n\n vs(1:3) = vs(1:3) / 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/sphere_quad/sphere01_triangle_vertices_to_centroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7899975509662164}} {"text": "function [ zfilt ] = gaussfilt( t,z,sigma )\n%Apply a Gaussian filter to a time series\n% Inputs: t = independent variable, z = data at points t, and \n% sigma = standard deviation of Gaussian filter to be applied.\n% Outputs: zfilt = filtered data.\n%\n% written by James Conder. Aug 22, 2013\n\nn = length(z); % number of data\nzfilt = 0*z; % initalize output vector\n\n%%% get distances between points for proper weighting\nw = 0*t;\nw(2:end-1) = 0.5*(t(3:end)-t(1:end-2));\nw(1) = t(2)-t(1);\nw(end) = t(end)-t(end-1);\n\n%%% check if sigma smaller than data spacing\niw = find(w > 2*sigma, 1);\nif ~isempty(iw)\n disp('WARNING: sigma smaller than half node spacing')\n disp('May lead to unstable result')\n iw = w > 2.5*sigma;\n w(iw) = 2.5*sigma;\n % this correction leaves some residual for spacing between 2-3sigma.\n % otherwise ok.\n % In general, using a Gaussian filter with sigma less than spacing is\n % a bad idea anyway...\nend\n\n%%% loop over points\na = 1/(sqrt(2*pi)*sigma);\nsigma2 = sigma*sigma;\nfor i = 1:n\n filter = a*exp(-0.5*((t - t(i)).^2)/(sigma2));\n zfilt(i) = sum(w.*z.*filter);\nend\n\n%%% clean-up edges - mirror data for correction\nss = 2.4*sigma; % distance from edge that needs correcting\n\n% left edge\ntedge = min(t);\niedge = find(t < tedge + ss);\nnedge = length(iedge);\nfor i = 1:nedge;\n dist = t(iedge(i)) - tedge;\n include = find( t > t(iedge(i)) + dist);\n filter = a*exp(-0.5*((t(include) - t(iedge(i))).^2)/(sigma2));\n zfilt(iedge(i)) = zfilt(iedge(i)) + sum(w(include).*filter.*z(include));\nend\n\n% right edge\ntedge = max(t);\niedge = find(t > tedge - ss);\nnedge = length(iedge);\nfor i = 1:nedge;\n dist = tedge - t(iedge(i));\n include = find( t < t(iedge(i)) - dist);\n filter = a*exp(-0.5*((t(include) - t(iedge(i))).^2)/(sigma2));\n zfilt(iedge(i)) = zfilt(iedge(i)) + sum(w(include).*filter.*z(include));\nend\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/43182-gaussian-smoothing-filter/gaussfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7899841309740477}} {"text": "function h=plotgauss2d(mu, Sigma)\n% PLOTGAUSS2D Plot a 2D Gaussian as an ellipse with optional cross hairs\n% h=plotgauss2(mu, Sigma)\n%\n\nh = plotcov2(mu, Sigma);\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n% PLOTCOV2 - Plots a covariance ellipse with major and minor axes\n% for a bivariate Gaussian distribution.\n%\n% Usage:\n% h = plotcov2(mu, Sigma[, OPTIONS]);\n% \n% Inputs:\n% mu - a 2 x 1 vector giving the mean of the distribution.\n% Sigma - a 2 x 2 symmetric positive semi-definite matrix giving\n% the covariance of the distribution (or the zero matrix).\n%\n% Options:\n% 'conf' - a scalar between 0 and 1 giving the confidence\n% interval (i.e., the fraction of probability mass to\n% be enclosed by the ellipse); default is 0.9.\n% 'num-pts' - the number of points to be used to plot the\n% ellipse; default is 100.\n%\n% This function also accepts options for PLOT.\n%\n% Outputs:\n% h - a vector of figure handles to the ellipse boundary and\n% its major and minor axes\n%\n% See also: PLOTCOV3\n\n% Copyright (C) 2002 Mark A. Paskin\n\nfunction h = plotcov2(mu, Sigma, varargin)\n\nif size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end\nif length(mu) ~= 2, error('mu must be a 2 by 1 vector'); end\n\n[p, ...\n n, ...\n plot_opts] = process_options(varargin, 'conf', 0.9, ...\n\t\t\t\t\t'num-pts', 100);\nh = [];\nholding = ishold;\nif (Sigma == zeros(2, 2))\n z = mu;\nelse\n % Compute the Mahalanobis radius of the ellipsoid that encloses\n % the desired probability mass.\n k = conf2mahal(p, 2);\n % The major and minor axes of the covariance ellipse are given by\n % the eigenvectors of the covariance matrix. Their lengths (for\n % the ellipse with unit Mahalanobis radius) are given by the\n % square roots of the corresponding eigenvalues.\n if (issparse(Sigma))\n [V, D] = eigs(Sigma);\n else\n [V, D] = eig(Sigma);\n end\n % Compute the points on the surface of the ellipse.\n t = linspace(0, 2*pi, n);\n u = [cos(t); sin(t)];\n w = (k * V * sqrt(D)) * u;\n z = repmat(mu, [1 n]) + w;\n % Plot the major and minor axes.\n L = k * sqrt(diag(D));\n h = plot([mu(1); mu(1) + L(1) * V(1, 1)], ...\n\t [mu(2); mu(2) + L(1) * V(2, 1)], plot_opts{:});\n hold on;\n h = [h; plot([mu(1); mu(1) + L(2) * V(1, 2)], ...\n\t [mu(2); mu(2) + L(2) * V(2, 2)], plot_opts{:})];\nend\n\nh = [h; plot(z(1, :), z(2, :), plot_opts{:})];\nif (~holding) hold off; end\n\n%%%%%%%%%%%%\n\n% CONF2MAHAL - Translates a confidence interval to a Mahalanobis\n% distance. Consider a multivariate Gaussian\n% distribution of the form\n%\n% p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C)))\n%\n% where MD(x, m, P) is the Mahalanobis distance from x\n% to m under P:\n%\n% MD(x, m, P) = (x - m) * P * (x - m)'\n%\n% A particular Mahalanobis distance k identifies an\n% ellipsoid centered at the mean of the distribution.\n% The confidence interval associated with this ellipsoid\n% is the probability mass enclosed by it. Similarly,\n% a particular confidence interval uniquely determines\n% an ellipsoid with a fixed Mahalanobis distance.\n%\n% If X is an d dimensional Gaussian-distributed vector,\n% then the Mahalanobis distance of X is distributed\n% according to the Chi-squared distribution with d\n% degrees of freedom. Thus, the Mahalanobis distance is\n% determined by evaluating the inverse cumulative\n% distribution function of the chi squared distribution\n% up to the confidence value.\n%\n% Usage:\n% \n% m = conf2mahal(c, d);\n%\n% Inputs:\n%\n% c - the confidence interval\n% d - the number of dimensions of the Gaussian distribution\n%\n% Outputs:\n%\n% m - the Mahalanobis radius of the ellipsoid enclosing the\n% fraction c of the distribution's probability mass\n%\n% See also: MAHAL2CONF\n\n% Copyright (C) 2002 Mark A. Paskin\n\nfunction m = conf2mahal(c, d)\n\nm = chi2inv(c, d); % matlab stats toolbox\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/KPMtools/plotgauss2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7899178092886862}} {"text": "function [ p, seed ] = triangle_reference_sample ( n, seed )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_REFERENCE_SAMPLE returns random points in the reference triangle.\n%\n% Diagram:\n%\n% 3\n% s |\\\n% i | \\\n% d | \\\n% e | \\ side 2\n% | \\\n% 3 | \\\n% | \\\n% 1-------2\n%\n% side 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points to generate.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real P(2,N), random points in the triangle.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n dim_num = 2;\n\n for j = 1 : n\n\n [ r, seed ] = r8_uniform_01 ( seed );\n%\n% Interpret R as a percentage of the triangle's area.\n%\n% Imagine a line L, parallel to side 1, so that the area between\n% vertex 1 and line L is R percent of the full triangle's area.\n%\n% The line L will intersect sides 2 and 3 at a fraction\n% ALPHA = SQRT ( R ) of the distance from vertex 1 to vertices 2 and 3.\n%\n alpha = sqrt ( r );\n%\n% Now choose, uniformly at random, a point on the line L.\n%\n [ beta, seed ] = r8_uniform_01 ( seed );\n\n p(1,j) = ( 1.0 - beta ) * alpha;\n p(2,j) = beta * 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/triangulation/triangle_reference_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7899178060992146}} {"text": "function z = r8vec_convolution ( m, x, n, y )\n\n%*****************************************************************************80\n%\n%% R8VEC_CONVOLUTION returns the convolution of two R8VEC's.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8's.\n%\n% The I-th entry of the convolution can be formed by summing the products\n% that lie along the I-th diagonal of the following table:\n%\n% Y3 : 3 4 5 6 7\n% Y2 : 2 3 4 5 6\n% Y1 : 1 2 3 4 5\n% +------------------\n% X1 X2 X3 X4 X5\n%\n% which will result in:\n%\n% Z = ( X1 * Y1,\n% X1 * Y2 + X2 * Y1,\n% X1 * Y3 + X2 * Y2 + X3 * Y1,\n% X2 * Y3 + X3 * Y2 + X4 * Y1,\n% X3 * Y3 + X4 * Y2 + X5 * Y1,\n% X4 * Y3 + X5 * Y2,\n% X5 * Y3 )\n%\n% Example:\n%\n% Input:\n%\n% X = (/ 1, 2, 3, 4 /)\n% Y = (/ -1, 5, 3 /)\n%\n% Output:\n%\n% Z = (/ -1, 3, 10, 17, 29, 12 /)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the dimension of X.\n%\n% Input, real X(M), the first vector to be convolved.\n%\n% Input, integer N, the dimension of Y.\n%\n% Input, real Y(N), the second vector to be convolved.\n%\n% Output, real Z(M+N-1), the convolution of X and Y.\n%\n z(1:m+n-1,1) = 0.0;\n\n for j = 1 : n\n z(j:j+m-1,1) = z(j:j+m-1,1) + x(1:m,1) * y(j,1);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_convolution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7899035425798643}} {"text": "function y = fcube ( x )\n\n%*****************************************************************************80\n%\n%% FCUBE sets the cubic data values.\n%\n% Discussion:\n%\n% Y(X) = ( ( X + 2 ) * X + 3 ) * X + 4\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, real X, the argument.\n%\n% Output, real Y, the value of the function.\n%\n y = ( ( ( 1.0E+00 ) ...\n * x + 2.0E+00 ) ...\n * x + 3.0E+00 ) ...\n * x + 4.0E+00;\n\n return\nend\n", "meta": {"author": "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/fcube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8705972734445508, "lm_q1q2_score": 0.7899035417155593}} {"text": "function [ x, w ] = gen_laguerre_ss_compute ( n, alpha )\n\n%*****************************************************************************80\n%\n%% GEN_LAGUERRE_SS_COMPUTE computes a generalized Gauss-Laguerre quadrature rule.\n%\n% Discussion:\n%\n% The integral:\n%\n% Integral ( 0 <= X < +oo ) EXP ( - X ) * X^ALPHA * F(X) dX\n%\n% The quadrature rule:\n%\n% Sum ( 1 <= I <= N ) W(I) * F ( X(I) )\n%\n% The integral:\n%\n% Integral ( 0 <= X < +oo ) X^ALPHA * F(X) dX\n%\n% The quadrature:\n%\n% Sum ( 1 <= I <= N ) W(I) * EXP ( X(I) ) * F ( X(I) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Arthur Stroud, Don Secrest.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n% N must be at least 1.\n%\n% Input, real ALPHA, the exponent of the X factor.\n% Set ALPHA = 0.0 for the simplest rule.\n% ALPHA must be nonnegative.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n x = zeros ( n, 1 );\n w = zeros ( n, 1 );\n%\n% Set the recursion coefficients.\n%\n for i = 1 : n\n b(i) = ( alpha + 2 * i - 1 );\n end\n\n for i = 1 : n\n c(i) = ( i - 1 ) * ( alpha + i - 1 );\n end\n\n cc = gamma ( alpha + 1.0 ) * prod ( c(2:n) );\n\n for i = 1 : n\n%\n% Compute an estimate for the root.\n%\n if ( i == 1 )\n\n xval = ( 1.0 + alpha ) * ( 3.0 + 0.92 * alpha ) ...\n / ( 1.0 + 2.4 * n + 1.8 * alpha );\n\n elseif ( i == 2 )\n\n xval = xval + ( 15.0 + 6.25 * alpha ) / ( 1.0 + 0.9 * alpha + 2.5 * n );\n\n else\n\n r1 = ( 1.0 + 2.55 * ( i - 2 ) ) / ( 1.9 * ( i - 2 ) );\n\n r2 = 1.26 * ( i - 2 ) * alpha / ( 1.0 + 3.5 * ( i - 2 ) );\n\n ratio = ( r1 + r2 ) / ( 1.0 + 0.3 * alpha );\n\n xval = xval + ratio * ( xval - x(i-2) );\n\n end\n%\n% Use iteration to find the root.\n%\n [ xval, dp2, p1 ] = gen_laguerre_ss_root ( xval, n, alpha, b, c );\n%\n% Set the abscissa and weight.\n%\n x(i) = xval;\n w(i) = ( cc / dp2 ) / p1;\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/quadrule/gen_laguerre_ss_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417881, "lm_q2_score": 0.8705972734445508, "lm_q1q2_score": 0.7899035395335999}} {"text": "function y = maxstar(x, w)\n% maxstar Log of a sum of exponentials.\n% For vectors, maxstar(x) is equivalent to log(sum(exp(x))).\n% For matrices, maxstar(x) is a row vector and maxstar operates on \n% each column of x. For N-D arrays, maxstar(x) operates along the\n% first non-singleton dimension.\n%\n% maxstar(x,w) is the log of a weighted sum of exponentials,\n% equivalent to log(sum(w.*exp(x))). Vectors w and x must be\n% the same length. For matrix x, the weights w can be input as\n% a matrix the same size as x, or as a vector of the same length \n% as columns of x. Weights may be zero or negative, but the result\n% sum(w.*exp(x)) must be greater than zero. \n%\n% Acts on first dimensions\n\nif nargin<2\n w = [];\nelse\n if ~isvector(w)\n error('maxstar: w must be a vector')\n end\n if length(w) ~= size(x,1)\n error('maxstar: weight does not match x')\n end\nend\n%%\nw = w(:);\nszx = size(x);\nif isempty(w)\n % no weight\n m = max(x);\n y = m + log(sum(exp(bsxfun(@minux,x,m))));\nelse\n % Move the weight into the exponent xw and find\n % m = max(xw) over terms with positive weights\n wpos = w>0;\n xw = bsxfun(@plus, x(wpos,:), log(w(wpos)));\n m = max(xw);\n exwp = exp( bsxfun(@minus, xw, m) );\n wneg = w<0;\n exwn = exp( x(wneg,:) + bsxfun(@minus,log(-w(wneg)), m) );\n y = m + log(sum(exwp,1) - sum(exwn,1));\nend\ny = reshape(y,[szx(2:end) 1]);\n\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/maxstar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7898501763641509}} {"text": "%% Data import\n%Copyright (c) 2011, The MathWorks, Inc.\n\n% Import tumor-weight profile for drugs A & B\nds = dataset('xlsfile', 'Data.xls') ;\n\n% Convert drug type column to nominal\nds.Drug = nominal(ds.Drug) ;\n\n%% Curve fitting \n\n% Initial estimates for [L0, L1, k1, k2_A and k2_B]\np0 = [0.11 , .149 , 1.836, 0.0154, 0.00732] ;\n\n% Estimate parameters\nfh = @(p , t ) objFcn(p , t , ds.Drug) ;% Function handle\ntic \npFit = lsqcurvefit(fh , p0 , ds.Time , ds.TumorWeight ) ;\ntoc\n%% Display results & plot\n\ndisp([' Drug-independent parameters: ' , ...\n num2str(pFit(1)), ' (L0), ' , ...\n num2str(pFit(2)), ' (L1) and ' , ...\n num2str(pFit(3)), ' (k1) ' ]) ;\n\ndisp([' Drug-dependent parameters: ' , ...\n num2str(pFit(4)), ' (k2 - Drug A) and ' , ...\n num2str(pFit(5)), ' (k2 - Drug B)' ]) ;\n\n% Plot observations\nfigure; hold on ;\nidx_A = ds.Drug == 'A' ;\nplot(ds.Time(idx_A) , ds.TumorWeight(idx_A) , 'ro') ;\nplot(ds.Time(~idx_A), ds.TumorWeight(~idx_A), 'bo') ;\n\n% Plot predictions\nyPred = fh(pFit, ds.Time) ;\nplot(ds.Time(idx_A) , yPred(idx_A) , 'r:') ;\nplot(ds.Time(~idx_A) , yPred(~idx_A), 'b:') ;\n\nxlabel('Time (days)')\nylabel('Tumor Weight (milligram)')\ntitle('Tumor growth profile')\nlegend({'Drug A', 'Drug B'})\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30869-fitting-with-matlab-statistics-optimization-and-curve-fitting/analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7898501753078979}} {"text": "function x = half_normal_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% HALF_NORMAL_CDF_INV inverts the Half Normal CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < B.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HALF_NORMAL_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'HALF_NORMAL_CDF_INV - Fatal error!' );\n end\n\n cdf2 = 0.5 * ( cdf + 1.0 );\n\n x = normal_cdf_inv ( cdf2, a, b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/half_normal_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7898240129473634}} {"text": "function [ xdp, ddp ] = dif_basis_derivk ( nd, xd, k )\n\n%*****************************************************************************80\n%\n%% DIF_BASIS_DERIVK: Lagrange basis K-th derivative difference tables.\n%\n% Discussion:\n%\n% Given ND points XD, a Lagrange basis polynomial L(J)(X) is associated\n% with each point XD(J).\n%\n% This function computes a table DDP(*,*) whose J-th column contains\n% the difference table for the K-th derivative of L(J)(X).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 June 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl deBoor,\n% A Practical Guide to Splines,\n% Springer, 2001,\n% ISBN: 0387953663,\n% LC: QA1.A647.v27.\n%\n% Parameters:\n%\n% Input, integer ND, the number of data points.\n%\n% Input, real XD(ND), the X values upon which the \n% Lagrange basis polynomials are to be based.\n%\n% Input, integer K, the index of the derivative.\n%\n% Output, real XDP(ND-K), the X values upon with\n% the derivative difference table is based. In fact, these are\n% all 0.\n%\n% Output, real DDP(ND-K,ND), the divided difference \n% tables for all the Lagrange basis polynomials. Column J of DDP\n% contains the table for basis polynomial associated with XD(J).\n%\n ddp = zeros ( nd - k, nd );\n%\n% Process the vectors one column at a time.\n%\n for j = 1 : nd\n%\n% Set the data.\n%\n yd(1:nd,1) = 0.0;\n yd(j,1) = 1.0;\n%\n% Compute the divided difference table.\n%\n dd = data_to_dif ( nd, xd, yd );\n%\n% Compute the divided difference table for the derivative.\n%\n [ xdp, ddp(1:nd-k,j) ] = dif_derivk_table ( nd, xd, dd, k );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/divdif/dif_basis_derivk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7898240081159866}} {"text": "function [ iters, endpt ] = hooke ( nvars, startpt, rho, eps, itermax, f )\n\n%*****************************************************************************80\n%\n%% HOOKE seeks a minimizer of a scalar function of several variables.\n%\n% Discussion:\n%\n% This routine find a point X where the nonlinear objective function\n% F(X) has a local minimum. X is an N-vector and F(X) is a scalar.\n% The objective function F(X) is not required to be differentiable\n% or even continuous. The program does not use or require derivatives\n% of the objective function.\n%\n% The user supplies three things:\n% 1) a subroutine that computes F(X),\n% 2) an initial \"starting guess\" of the minimum point X,\n% 3) values for the algorithm convergence parameters.\n%\n% The program searches for a local minimum, beginning from the\n% starting guess, using the Direct Search algorithm of Hooke and\n% Jeeves.\n%\n% This program is adapted from the Algol pseudocode found in the\n% paper by Kaupe, and includes improvements suggested by Bell and Pike,\n% and by Tomlin and Smith.\n%\n% The algorithm works by taking \"steps\" from one estimate of\n% a minimum, to another (hopefully better) estimate. Taking\n% big steps gets to the minimum more quickly, at the risk of\n% \"stepping right over\" an excellent point. The stepsize is\n% controlled by a user supplied parameter called RHO. At each\n% iteration, the stepsize is multiplied by RHO (0 < RHO < 1),\n% so the stepsize is successively reduced.\n%\n% Small values of rho correspond to big stepsize changes,\n% which make the algorithm run more quickly. However, there\n% is a chance (especially with highly nonlinear functions)\n% that these big changes will accidentally overlook a\n% promising search vector, leading to nonconvergence.\n%\n% Large values of RHO correspond to small stepsize changes,\n% which force the algorithm to carefully examine nearby points\n% instead of optimistically forging ahead. This improves the\n% probability of convergence.\n%\n% The stepsize is reduced until it is equal to (or smaller\n% than) EPS. So the number of iterations performed by\n% Hooke-Jeeves is determined by RHO and EPS:\n%\n% RHO^(number_of_iterations) = EPS\n%\n% In general it is a good idea to set RHO to an aggressively\n% small value like 0.5 (hoping for fast convergence). Then,\n% if the user suspects that the reported minimum is incorrect\n% (or perhaps not accurate enough), the program can be run\n% again with a larger value of RHO such as 0.85, using the\n% result of the first minimization as the starting guess to\n% begin the second minimization.\n%\n% Normal use:\n% (1) Code your function F() in the C language;\n% (2) Install your starting guess;\n% (3) Run the program.\n%\n% If there are doubts about the result, the computed minimizer\n% can be used as the starting point for a second minimization attempt.\n%\n% To apply this method to data fitting, code your function F() to be\n% the sum of the squares of the errors (differences) between the\n% computed values and the measured values. Then minimize F()\n% using Hooke-Jeeves.\n%\n% For example, you have 20 datapoints (T(i), Y(i)) and you want to\n% find A, B and C so that:\n%\n% A*t*t + B*exp(t) + C*tan(t)\n%\n% fits the data as closely as possible. Then the objective function\n% F() to be minimized is just\n%\n% F(A,B,C) = sum ( 1 <= i <= 20 )\n% ( y(i) - A*t(i)*t(i) - B*exp(t(i)) - C*tan(t(i)) )^2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2008\n%\n% Author:\n%\n% ALGOL original by Arthur Kaupe.\n% C version by Mark Johnson.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% M Bell, Malcolm Pike,\n% Remark on Algorithm 178: Direct Search,\n% Communications of the ACM,\n% Volume 9, Number 9, September 1966, page 684.\n%\n% Robert Hooke, Terry Jeeves,\n% Direct Search Solution of Numerical and Statistical Problems,\n% Journal of the ACM,\n% Volume 8, Number 2, April 1961, pages 212-229.\n%\n% Arthur Kaupe,\n% Algorithm 178:\n% Direct Search,\n% Communications of the ACM,\n% Volume 6, Number 6, June 1963, page 313.\n%\n% FK Tomlin, LB Smith,\n% Remark on Algorithm 178: Direct Search,\n% Communications of the ACM,\n% Volume 12, Number 11, November 1969, page 637-638.\n%\n% Parameters:\n%\n% Input, integer NVARS, the number of spatial dimensions.\n%\n% Input, real STARTPT(NVARS), the user-supplied\n% initial estimate for the minimizer.\n%\n% Input, real RHO, a user-supplied convergence parameter\n% which should be set to a value between 0.0 and 1.0. Larger values\n% of RHO give greater probability of convergence on highly nonlinear\n% functions, at a cost of more function evaluations. Smaller\n% values of RHO reduce the number of evaluations and the program\n% running time, but increases the risk of nonconvergence.\n%\n% Input, real EPS, the criterion for halting\n% the search for a minimum. When the algorithm\n% begins to make less and less progress on each\n% iteration, it checks the halting criterion: if\n% the stepsize is below EPS, terminate the\n% iteration and return the current best estimate\n% of the minimum. Larger values of EPS (such\n% as 1.0e-4) give quicker running time, but a\n% less accurate estimate of the minimum. Smaller\n% values of EPS (such as 1.0e-7) give longer\n% running time, but a more accurate estimate of\n% the minimum.\n%\n% Input, integer ITERMAX, a limit on the number of iterations.\n%\n% Input, function handle F, the name of the function routine,\n% which should have the form:\n% function value = f ( x, n )\n%\n% Output, integer ITERS, the number of iterations taken.\n%\n% Output, real ENDPT(NVARS), the estimate for the\n% minimizer, as calculated by the program.\n%\n verbose = 0;\n\n for i = 1 : nvars\n newx(i) = startpt(i);\n end\n\n for i = 1 : nvars\n xbefore(i) = startpt(i);\n end\n\n for i = 1 : nvars\n if ( startpt(i) == 0.0 )\n delta(i) = rho;\n else\n delta(i) = rho * abs ( startpt(i) );\n end\n end\n\n funevals = 0;\n steplength = rho;\n iters = 0;\n fbefore = f ( newx, nvars );\n funevals = funevals + 1;\n newf = fbefore;\n\n while ( iters < itermax & eps < steplength )\n\n iters = iters + 1;\n\n if ( verbose )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FUNEVALS = %d, F(X) = %e\\n', funevals, fbefore );\n for i = 1 : nvars\n fprintf ( 1, ' %8d %e\\n', i, xbefore(i) );\n end\n\n end\n%\n% Find best new point, one coordinate at a time.\n%\n for i = 1 : nvars\n newx(i) = xbefore(i);\n end\n\n [ newf, newx, funevals ] = best_nearby ( delta, newx, fbefore, nvars, ...\n f, funevals );\n%\n% If we made some improvements, pursue that direction.\n%\n keep = 1;\n\n while ( newf < fbefore & keep == 1 )\n\n for i = 1 : nvars\n%\n% Arrange the sign of DELTA.\n%\n if ( newx(i) <= xbefore(i) )\n delta(i) = - abs ( delta(i) );\n else\n delta(i) = abs ( delta(i) );\n end\n%\n% Now, move further in this direction.\n%\n tmp = xbefore(i);\n xbefore(i) = newx(i);\n newx(i) = newx(i) + newx(i) - tmp;\n end\n\n fbefore = newf;\n [ newf, newx, funevals ] = best_nearby ( delta, newx, fbefore, nvars, ...\n f, funevals );\n%\n% If the further (optimistic) move was bad...\n%\n if ( fbefore <= newf )\n break;\n end\n%\n% Make sure that the differences between the new and the old points\n% are due to actual displacements; beware of roundoff errors that\n% might cause NEWF < FBEFORE.\n%\n keep = 0;\n\n for i = 1 : nvars\n if ( 0.5 * abs ( delta(i) ) < abs ( newx(i) - xbefore(i) ) )\n keep = 1;\n break\n end\n end\n\n end\n\n if ( eps <= steplength & fbefore <= newf )\n steplength = steplength * rho;\n for i = 1 : nvars\n delta(i) = delta(i) * rho;\n end\n end\n\n end\n\n for i = 1 : nvars\n endpt(i) = xbefore(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/toms178/hooke.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.7898159305385323}} {"text": "function varargout = modschaffer4(X)\n% modified Schaffer function, #4\n%\n% MODSCHAFFER4([x1, x2]) returns the value of the 4th Schaffer\n% function at the specified points. [x1] and [x2] may be vectors.\n% The search domain is\n%\n% -100 < x_i < 100\n%\n% The global minimum is \n%\n% f(x1, x2) = f(0, 1.25313) = 0.292579.\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-100, -100]; % LB\n varargout{3} = [+100, +100]; % UB\n varargout{4} = [0, 1.253131828927371e+000]; % solution\n varargout{5} = 2.925786320359805e-001; % function value at solution\n \n % otherwise, output function value\n else \n\n % keep values within the search interval\n X(X < -100) = inf; X(X > 100) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = 0.5 + (cos(sin(abs(x1.^2 - x2.^2))).^2 - 0.5) ./ (1+0.001*(x1.^2 + x2.^2)).^2;\n \n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23147-many-testfunctions-for-global-optimizers/single-objective/modschaffer4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7897621970578652}} {"text": "function value = j_double_product_integral ( i, j, a, b )\n\n%*****************************************************************************80\n%\n%% J_DOUBLE_PRODUCT_INTEGRAL: integral of J(i,x)*J(j,x)*(1-x)^a*(1+x)^b.\n%\n% Discussion:\n%\n% VALUE = integral ( -1 <= x <= +1 ) J(i,x)*J(j,x)*(1-x)^a*(1+x)^b dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, J, the polynomial indices.\n%\n% Input, real A, B, the parameters.\n% -1 < A, B.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( i ~= j )\n value = 0.0;\n else\n value = 2^( a + b + 1.0 ) / ( 2 * i + a + b + 1 ) ...\n * gamma ( i + a + 1 ) * gamma ( i + b + 1 ) ...\n / r8_factorial ( i ) / gamma ( i + a + b + 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/jacobi_polynomial/j_double_product_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7897368632070797}} {"text": "function [mappedX, mapping] = em_pca(X, no_dims, max_iter)\n%EMPCA Run an EM-based implementation of (probabilistic) PCA\n%\n% [mappedX, mapping] = em_pca(X, no_dims)\n%\n% Performs probabilistic PCA on dataset X in order to reduce its\n% dimensionality to no_dims. The dimensionality reduction is performed by\n% means of an EM algorithm. The resulting low-dimensional counterpart of X\n% is returned in mappedX. Information on the applied mapping (allowing for,\n% e.g., out-of-sample extension) is returned in mapping.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if ~exist('max_iter', 'var')\n max_iter = 200;\n end\n\n % Initialize some variables\n [n D] = size(X); % data dimensions\n Ez = zeros(no_dims, n); % expectation of latent vars\n Ezz = zeros(no_dims, no_dims, n); % expectation of cov(z)\n Q = Inf; % log-likelihood\n mapping = struct;\n\n % Randomly initialize W and sigma\n W = rand(D, no_dims) * 2; % factor loadings\n sigma2 = rand(1) * 2; % variance ^ 2\n % The covariance of the Gaussian is: C = W * W' + sigma2 * eye(D);\n \n % Make data zero-mean (possible because data mean is ML estimate for mu)\n mapping.mean = mean(X, 1);\n X = bsxfun(@minus, X, mapping.mean);\n \n % Compute data covariance and transpose data\n S = cov(X);\n X = X';\n \n % Perform EM iterations\n converged = 0;\n iter = 0;\n inW = W' * W;\n while ~converged && iter <= max_iter\n \n % Update iteration number\n iter = iter + 1;\n if rem(iter, 5) == 0\n fprintf('.');\n end\n \n % Perform E-step\n invM = inv(inW + sigma2 * eye(no_dims));\n for i=1:n\n Ez(:,i) = invM * W' * X(:,i); \n Ezz(:,:,i) = sigma2 * invM + Ez(:,i) * Ez(:,i)';\n end\n \n % Perform M-step (maximize mapping W)\n Wp1 = zeros(D, no_dims);\n Wp2 = zeros(no_dims, no_dims);\n for i=1:n\n Wp1 = Wp1 + X(:,i) * Ez(:,i)';\n Wp2 = Wp2 + Ezz(:,:,i);\n end\n W = Wp1 / Wp2;\n inW = W' * W;\n \n % Perform M-step (maximize discarded variance sigma)\n normX = sum(X .^ 2, 1);\n sigma2 = 0;\n for i=1:n\n sigma2 = sigma2 + (normX(i) - 2 * Ez(:,i)' * W' * X(:,i) + trace(Ezz(:,:,i) * inW));\n end\n sigma2 = (1 / (n * D)) * sigma2;\n \n % Compute likelihood of new model\n oldQ = Q;\n if iter > 1\n invC = ((1 / sigma2) * eye(D)) - ((1 / sigma2) * W * invM * W');\n detC = det(sigma2 * eye(D)) * det(eye(no_dims) + W' * ((sigma2 .^ -1) * eye(D)) * W);\n Q = (-n / 2) * (D * log(2 * pi) + log(detC) + trace(invC * S));\n end\n \n % Stop condition to detect convergence\n if abs(oldQ - Q) < 1e-3\n converged = 1;\n end\n end\n \n % Compute mapped data\n disp(' ');\n mapping.M = (inW \\ W')';\n mapping.sigma2 = sigma2;\n mappedX = X' * mapping.M; \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/em_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7897368602944547}} {"text": "function t = tvec_even3 ( nt )\n\n%*****************************************************************************80\n%\n%% TVEC_EVEN3 computes an evenly spaced set of angles between 0 and 2*PI.\n%\n% Discussion:\n%\n% The angles begin with 0 and end with 2*PI.\n%\n% Example:\n%\n% NT = 4\n%\n% T = ( 0, 2*PI/3, 4*PI/3 2*PI )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NT, the number of values to compute.\n%\n% Output, real TVEC(NT), the evenly spaced angles, in radians.\n%\n if ( nt == 1 )\n t(1) = pi;\n else\n t(1:nt) = ( 0:2:(2*nt-1) ) * pi / ( nt - 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/stroud/tvec_even3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8840392909114835, "lm_q1q2_score": 0.789720613892845}} {"text": "function [VIn, MIn] = partition_distance(Cx, Cy)\n%PARTITION_DISTANCE Distance or similarity between community partitions\n%\n% This function quantifies information-theoretic distance (normalized\n% variation of information) or similarity (normalized mutual information)\n% between community partitions.\n%\n% VIn = partition_distance(Cx);\n% VIn = partition_distance(Cx, Cy);\n% [VIn, MIn] = partition_distance(Cx, Cy);\n%\n% Inputs:\n% Cx,\n% Community partition vector or matrix of n rows and p columns,\n% n is the number of network nodes, and p is the number of input\n% community partitions (in the case of vector input p=1).\n%\n% Cy (optional argument),\n% Community partition vector or matrix of n rows and q columns. n\n% is the number of nodes (must be equal to the number of nodes in\n% Cq) and q is the number of input community partitions (may be\n% different to the number of nodes in Cq). This argument may be\n% omitted, in which case, the partition distance is computed\n% between all pairwise partitions of Cx.\n%\n% Outputs:\n% VIn,\n% Normalized variation of information ([p, q] matrix)\n%\n% MIn,\n% Normalized mutual information ([p, q] matrix)\n%\n% Notes:\n% Mathematical definitions.\n%\n% VIn = [H(X) + H(Y) - 2MI(X, Y)]/log(n)\n% MIn = 2MI(X, Y) / [H(X) + H(Y)]\n%\n% where H is the entropy and MI is the mutual information\n%\n%\n% Reference: Meila M (2007) J Multivar Anal 98, 873-895.\n%\n%\n% 2011-2017, Mika Rubinov, UNSW, Janelia HHMI\n\n% Modification History:\n% Mar 2011: Original\n% Jan 2017: Added computation between input matrices.\n\ns = (nargin==1);\nif s\n Cy = Cx;\n d = 10.^ceil(log10(double(1 + max( Cx(:)) )));\nelse\n d = 10.^ceil(log10(double(1 + max([Cx(:);Cy(:)]) )));\nend\n\nif ~isequal([Cx(:);Cy(:)], int64([Cx(:);Cy(:)])) || min([Cx(:);Cy(:)])<=0\n error('Input partitions must contain only positive integers.')\nend\n\n[n, p] = size(Cx);\nHX = zeros(p, 1);\nfor i = 1:p\n Px = nonzeros(accumarray(Cx(:, i), 1)) / n; % P(x)\n HX(i) = - sum(Px .* log(Px)); % H(x)\nend\n\nif s\n q = p;\n HY = HX;\nelse\n [n_, q] = size(Cy);\n assert(n == n_);\n HY = zeros(q, 1);\n for j = 1:q\n Py = nonzeros(accumarray(Cy(:, j), 1)) / n; % P(y)\n HY(j) = - sum(Py .* log(Py)); % H(y)\n end\nend\n\nVIn = zeros(p, q);\nMIn = zeros(p, q);\nfor i = 1:p\n j_idx = (s * (i - 1) + 1):q;\n for j = j_idx\n Pxy = nonzeros(accumarray(d*Cx(:, i) + Cy(:, j), 1)) / n; \t% P(x,y)\n Hxy = -sum(Pxy .* log(Pxy)); % H(x,y)\n VIn(i, j) = (2 * Hxy - HX(i) - HY(j)) / log(n); % VIn\n MIn(i, j) = 2 * (HX(i) + HY(j) - Hxy) / (HX(i) + HY(j)); % MIn\n end\n if s\n VIn(j_idx, i) = VIn(i, j_idx);\n MIn(j_idx, i) = MIn(i, j_idx);\n 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/External/2019_03_03_BCT/partition_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7896287343565841}} {"text": "function x = log_normal_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% LOG_NORMAL_CDF_INV inverts the Lognormal CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < B.\n%\n% Input, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LOG_NORMAL_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'LOG_NORMAL_CDF_INV - Fatal error!' );\n end\n\n logx = normal_cdf_inv ( cdf, a, b );\n\n x = exp ( logx );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/log_normal_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7896287327003283}} {"text": "function [ pn, dist, t ] = segment_point_near ( p1, p2, p )\n\n%*****************************************************************************80\n%\n%% SEGMENT_POINT_NEAR finds the line segment point nearest a point.\n%\n% Discussion:\n%\n% A line segment is the finite portion of a line that lies between\n% two points.\n%\n% The nearest point will satisfy the condition\n%\n% PN = (1-T) * P1 + T * P2.\n%\n% T will always be between 0 and 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), the endpoints of the line segment.\n%\n% Input, real P(2,1), the point whose nearest neighbor\n% on the line segment is to be determined.\n%\n% Output, real PN(2,1), the point on the line segment which is\n% nearest the point (X,Y).\n%\n% Output, real DIST, the distance from the point to the\n% nearest point on the line segment.\n%\n% Output, real T, the relative position of the point (XN,YN)\n% to the points (X1,Y1) and (X2,Y2).\n%\n\n%\n% If the line segment is actually a point, then the answer is easy.\n%\n if ( p1(1:2,1) == p2(1:2,1) )\n\n t = 0.0;\n\n else\n\n bot = sum ( ( p2(1:2,1) - p1(1:2,1) ).^2 );\n\n t = ( p(1:2,1) - p1(1:2,1) )' * ( p2(1:2,1) - p1(1:2,1) ) / bot;\n\n t = max ( t, 0.0 );\n t = min ( t, 1.0 );\n\n end\n\n pn(1:2,1) = p1(1:2,1) + t * ( p2(1:2,1) - p1(1:2,1) );\n\n dist = sqrt ( sum ( ( pn(1:2,1) - p(1:2,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polygon_properties/segment_point_near.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.7895871669261144}} {"text": "function [env] = env_secant(x_data, y_data, view, side) \n% Function call: env_secant(x_data, y_data, view, side) \n% Calculates the top envelope of data over .\n% Method used: 'secant-method'\n% env_secant() observates the max. slope of about points,\n% and joints them to the resulting envelope.\n% An interpolation over original x-values is done finally.\n% ('top' or 'bottom') defines which side to evolve.\n% Author: Andreas Martin, Volkswagen AG, Germany\n\n\nside = strcmpi( {'top','bottom'}, side ) * [ 1 ; -1 ];\n\nassert( view > 1, ...\n 'Parameter too small!' );\nassert( ndims (x_data) == 2, ...\n 'Parameter has to be vector type!' );\nassert( size (x_data, 1) == 1 || size (x_data, 2) == 1, ...\n 'Parameter has to be vector type (Nx1)!' );\nassert( ndims (y_data) == 2, ...\n 'Parameter has to be vector type (Nx1)!' );\nassert( size (y_data, 1) == 1 || size (y_data, 2) == 1, ...\n 'Parameter has to be vector type (Nx1)!' );\nassert( length (x_data) == length (y_data), ...\n 'Parameters and must have same length!' );\nassert( side ~= 0, ...\n 'Parameter must be ''top'' or ''bottom''' );\n\ny_data = y_data(:);\ndata_len = length( y_data );\nx_new = [];\ny_new = [];\n\ni = 1;\nwhile i < data_len;\n ii = i+1:min( i + view, data_len );\n [ m, idx ] = max( ( y_data(ii) - y_data(i) ) ./ (ii-i)' .* side );\n\n % Equidistant x_data assumed! Use next row instead, if not:\n %[ m, idx ] = max( ( y_data(ii) - y_data(i) ) ./ ( x_data(ii) - x_data(i) ) * side );\n \n % New max. slope: store new \"observation point\"\n i = i + idx;\n x_new = [ x_new x_data(i) ];\n y_new = [ y_new y_data(i) ];\nend;\n\nenv = interp1( x_new, y_new, x_data, 'linear', 'extrap' );\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27662-evolve-top-and-bottom-envelopes-for-time-signals-i-e/env_secant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7895841771028688}} {"text": "function program_07 ( )\n\n%*****************************************************************************80\n%\n%% PROGRAM_07: Monte Carlo integral estimate for arbitrary triangle.\n%\n% Discussion:\n%\n% The program\n% * reads a triangle T (defined by three points),\n% * reads a random number seed;\n% * reads integer exponents P and Q;\n% * reads N, the number of random values to generate;\n% * it then computes N random points in the triangle;\n% * evaluates X^P * Y^Q at each point, and averages \n% to estimate the integral over the triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 February 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROGRAM_07 - Monte Carlo estimate of\\n' );\n fprintf ( 1, ' Integral x^p y^q\\n' );\n fprintf ( 1, ' over an arbitrary triangle.\\n' );\n%\n% Get the triangle vertices.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Define a triangle T:\\n' );\n\n t_v1 = input ( ' Enter [ T.v1.x, T.v1.y]: ' ); \n t_v2 = input ( ' Enter [ T.v2.x, T.v2.y]: ' ); \n t_v3 = input ( ' Enter [ T.v3.x, T.v3.y]: ' ); \n%\n% Get the random number seed.\n%\n seed = input ( 'Enter a random number seed: ' );\n rand ( 'state', seed );\n%\n% Get the powers P and Q.\n%\n p = input ( 'Enter the power P for X^P: ' );\n q = input ( 'Enter the power Q for Y^Q: ' );\n%\n% Get the number of values to generate.\n%\n n = input ( 'Enter the number of samples to generate: ' );\n%\n% Compute the area.\n%\n t_area = 0.5 * ( t_v1(1) * ( t_v2(2) - t_v3(2) ) ...\n + t_v2(1) * ( t_v3(2) - t_v1(2) ) ...\n + t_v3(1) * ( t_v1(2) - t_v2(2) ) );\n%\n% Generate sample points in the unit triangle, \n% map them to points in the given triangle,\n% evaluate the integrand, add to QUAD.\n%\n quad = 0.0;\n\n for i = 1 : n\n\n r = rand;\n s = rand;\n\n xi1 = 1.0 - sqrt ( s );\n xi2 = ( 1.0 - r ) * sqrt ( s );\n xi3 = r * sqrt ( s );\n\n x = xi1 * t_v1(1) + xi2 * t_v2(1) + xi3 * t_v3(1);\n y = xi1 * t_v1(2) + xi2 * t_v2(2) + xi3 * t_v3(2);\n\n quad = quad + x^p * y^q;\n\n end\n%\n% Normalize QUAD by the area and the number of points.\n%\n quad = quad * t_area / n;\n%\n% We didn't work out the exact integral, so all we have is\n% this estimate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Estimated integral = %12.6f\\n', quad );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROGRAM_07\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cg_lab_triangles/program_07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7895275262161435}} {"text": "function y = logGauss(X, mu, sigma)\n% Compute log pdf of a Gaussian distribution.\n% Input:\n% X: d x n data matrix\n% mu: d x 1 mean vector of Gaussian\n% sigma: d x d covariance matrix of Gaussian\n% Output:\n% y: 1 x n probability density in logrithm scale y=log p(x)\n% Written by Mo Chen (sth4nth@gmail.com).\nd = size(X,1);\nX = X-mu;\n[U,p]= chol(sigma);\nif p ~= 0\n error('ERROR: sigma is not PD.');\nend\nQ = U'\\X;\nq = dot(Q,Q,1); % quadratic term (M distance)\nc = d*log(2*pi)+2*sum(log(diag(U))); % normalization constant\ny = -(c+q)/2;\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter02/logGauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7895275210508506}} {"text": "%% Mean-Shift Algorithm\n% by Sylvain Bernhardt\n% July 2008\n%% Description\n% Computes the mask of a Parzen window\n% and its gradient in respect of the x-axis\n% and the y-axis.\n% The different types of kernel are:\n% {Uniform,Triangular,Epanechnikov,Gaussian}\n%\n% [k,gx,gy] = Parzen_window(H,W,R,type,graph)\n% with:\n% k - the mask\n% gx,gy - its gradients\n% (H,W) - size of the mask\n% type - its type\n% graph - plot the masks if graph=1\n\nfunction [k,gx,gy] = Parzen_window(H,W,R,type,graph)\nk = zeros(H,W);\n\n%% ----Uniform----\nif strcmp(type,'Uniform')==1\n for i=1:H\n for j=1:W\n if (((2*i)/H-1)/R)^2+(((2*j)/W-1)/R)^2 <= 1\n k(i,j) = 1;\n end\n end\n end\nend\n\n%% ----Triangular----\nif strcmp(type,'Triangular')==1\n Max = max(H,W);\n for z=1:round(R*Max/2)-1\n h = zeros(H,W);\n for i=1:H\n for j=1:W\n if ((i-(H/2))/(R*H/2-z*H/Max))^2+...\n ((j-(W/2))/(R*W/2-z*W/Max))^2 <= 1\n h(i,j) = 2/(Max*R);\n end\n end\n end\n k = k+h;\n end\nend\n\n%% ----Epanechnikov\nif strcmp(type,'Epanechnikov')==1\n for i=1:H\n for j=1:W\n k(i,j) = (1-(2*i/(R*H)-1/R)^2-...\n (2*j/(R*W)-1/R)^2);\n if k(i,j) < 0\n k(i,j) = 0;\n end\n end\n end\nend\n\n%% ----Gaussian----\nif strcmp(type,'Gaussian')==1\n sigmaH = (R*H/2)/3;\n sigmaW = (R*W/2)/3;\n % sigma = x/3 as a gaussian is almost equal to 0\n % from 3*sigma.\n for i=1:H\n for j=1:W\n k(i,j) = exp(-.5*((i-.5*H)^2/sigmaH^2+...\n (j-.5*W)^2/sigmaW^2));\n end\n end\nend\n\n%% Gradient of kernel\n[gx,gy] = gradient(-k);\n\n%% Plotting the window\nif graph==1\n figure (4)\n scrsz = get(0,'ScreenSize');\n set(4,'Position',[scrsz(3)/4 scrsz(4)/4 ...\n scrsz(3)/1.5 scrsz(4)/1.5])\n subplot(2,2,1)\n mesh(k);\n surf(k);\n shading interp\n subplot(2,2,2)\n mesh(gx);\n surf(gx);\n shading interp\n subplot(2,2,3)\n mesh(gy);\n surf(gy);\n shading interp\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/Parzen_window.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7894624400794608}} {"text": "function c=dsti(f,L,dim)\n%DSTI Discrete Sine Transform type I\n% Usage: c=dsti(f);\n% c=dsti(f,L);\n% c=dsti(f,[],dim);\n% c=dsti(f,L,dim);\n%\n% `dsti(f)` computes the discrete sine transform of type I of the\n% input signal *f*. If *f* is multi-dimensional, the transformation is\n% applied along the first non-singleton dimension.\n%\n% `dsti(f,L)` zero-pads or truncates *f* to length *L* before doing the\n% transformation.\n%\n% `dsti(f,[],dim)` or `dsti(f,L,dim)` applies the transformation along\n% dimension *dim*.\n%\n% The transform is real (output is real if input is real) and orthonormal.\n%\n% This transform is its own inverse.\n%\n% Let f be a signal of length *L* and let `c=dsti(f)`. Then \n%\n% .. L-1\n% c(n+1) = sqrt(2/(L+1)) * sum sin(pi*(n+1)*(m+1)/(L+1)) \n% m=0 \n% .. math:: c\\left(n+1\\right)=\\sqrt{\\frac{2}{L+1}}\\sum_{m=0}^{L-1}f\\left(m+1\\right)\\sin\\left(\\frac{\\pi \\left(n+1\\right)\\left(m+1\\right)}{L+1}\\right)\n%\n% The implementation of this functions uses a simple algorithm that requires\n% an FFT of length $2N+2$, which might potentially be the product of a large\n% prime number. This may cause the function to sometimes execute slowly.\n% If guaranteed high speed is a concern, please consider using one of the\n% other DST transforms.\n%\n% Examples:\n% ---------\n%\n% The following figures show the first 4 basis functions of the DSTI of\n% length 20:::\n%\n% % The dsti is its own adjoint.\n% F=dsti(eye(20));\n%\n% for ii=1:4\n% subplot(4,1,ii);\n% stem(F(:,ii));\n% end;\n%\n% See also: dcti, dstiii, dstiv\n%\n% References: rayi90 wi94\n\n% AUTHOR: Peter L. Søndergaard\n% TESTING: TEST_PUREFREQ\n% REFERENCE: REF_DSTI\n\ncomplainif_argnonotinrange(nargin,1,3,mfilename);\n\nif nargin<3\n dim=[];\nend;\n\nif nargin<2\n L=[];\nend;\n\n[f,L,Ls,W,dim,permutedsize,order]=assert_sigreshape_pre(f,L,dim,'DSTI');\n\nif ~isempty(L)\n f=postpad(f,L);\nend;\n\nif L==1\n c=f;\n \nelse\n\n c = comp_dst(f,1);\n\nend;\n\nc=assert_sigreshape_post(c,dim,permutedsize,order);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/fourier/dsti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.789461746200741}} {"text": "%% NUMERICAL LINEAR ALGEBRA WITH MATLAB\n% This document looks at some important concepts in linear and shows how to\n% solve some basic problems using MATLAB.\n\n%% Matrix-Vector products\n% Let's think about what a matrix-vector product actually does. It's more\n% interesting that you think! Lets take a simple example. Consider the\n% vector [1;0] multiplied by a matrix [1,1;1,1]\n%%\nfigure('color',[1 1 1])\nA=ones(2)\nx=[1;0]\nAx=A*x\nline([0 x(1)],[0 x(2)]), hold on, grid on\nline([0,Ax(1)],[0,Ax(2)],'color',[1 0 0])\ntext(1.1,0,'x','fontweight','bold'), text(1.1,1.1,'A*x','fontweight','bold')\naxis([-0.5 1.5 -0.5 1.5])\ntitle('Action of a matrix A on a vector x')\n%%\n% We can see that the matrix multiplication resulted in a vector that was\n% rotated by a certain angle and also stretched by a certain factor. This\n% action (stretching and rotating) is extremely useful for switching from\n% one co-ordinate system [x,y] to another [x', y']. Something that you will\n% come across in special relativity and a number of other areas. To\n% visualise what we mean by a co-ordinate transformation, consider the\n% basis vectors x:=[1,0] and y:=[0,1], and a point p:=[0.2,0.1].\nfigure('color',[1 1 1])\nxy=[1,0;0,1]\np=[0.5,0.3,0.1;0.4,0.2,0.0]\nA=[-1 1;1 1]\nxyp=A*xy; % Co-ordinate rotation step\nAp=A*p;\nline([0 xy(1,1)],[0 xy(2,1)]), grid on, hold on\nline([0,xy(1,2)],[0,xy(2,2)])\nplot(p(1,:),p(2,:),'*','markersize',6,'color','b')\nline([0, xyp(1,1)],[0 xyp(2,1)],'color',[1 0 0])\nline([0, xyp(2,1)],[0,xyp(2,2)],'color',[1 0 0])\nplot(Ap(1,:),Ap(2,:),'*','markersize',6,'color','r')\naxis([-1.5 1.5 -1.5 1.5]), axis square\ntitle('Changing the co-ordinate basis with matrix multiplication')\n\n%% A rogue's gallery of useful matrices\n% Matrices can be thought of as a 2-D array of data, or a collection of\n% vectors. There are a number of important matrices that are extremely\n% useful, and worth knowing about. We will use several of these later on in \n% this lecture. Here are a few:\n%%\n% * Identity\n% * Ones/Zeros\n% * Upper/Lower Triangular\n% * Symmetric\n% * Vandermonde\n% * Finite Difference\n% * Rotation\n%%\n% The *Identity Matrix* or *I*\n%%\nI = eye(4)\n%%\n% A *matrix of ones or zeros*:\n%% \nO = ones(4)\nZ = zeros(4)\n%%\n% *Upper and lower triangular matrices*. These are particularly important,\n% as we shall see below, and consist of matrices that have zeros below, or\n% above the _main diagonal_\n%%\nUT = triu(randn(4))\nLT = tril(randn(4))\n%%\n% *Symmetric matrices* are matrices that have the same\n% elements above he main diagonal as below the main diagonal:\n%%\nA = randn(4);\nSYM = A*A'\n%%\n% The *Vandermonde matrix* is a matrix whose columns are polynomials in\n% $$x$. This is useful in curve fitting and interpolation, for example, if \n% I wanted to find the $$3^{rd}$ order interpolating polynomial for some \n% data [x,y], then I would use the following matrix:\nfigure('color',[1 1 1])\nx=linspace(0,1,5)';\nIM = [x.^0, x.^1, x.^2, x.^3, x.^4]\nplot(x,IM), axis([0 1 0 1.2]), grid on\ntitle('First five powers of x')\n%%\n% Generally for interpolation, it's better to use a matrix whose columns\n% are *orthogonal* polynomials, such as Legendre or Chebyshev, but this is\n% beyond the remit of this course.\n%%\n% *Finite difference matrices* are extremely useful. They are matrices that\n% approximate the derivative of a function on a grid. One way to calculate\n% them is to fit an interpolating polynomial through the function, and then\n% differentiate the polynomial to get what is called a finite difference\n% stencil, while the other is to use a Taylor expansion to approximate\n% the derivatives.\n%%\n% As an illustration, we will use the Taylor expansion.\n%%\n% {\\Large\n% $ f(x+\\Delta x) = f(x) + \\Delta x f'(x) + \\frac{{\\Delta x}^2f''(x)}{2!} +\n% $}{\\emph higher order terms} \n%%\n% Here the dash represents a derivative with respect to x. If we ignore\n% terms above the first derivative, we see we can say that\n%%\n% {\\Large\n% $ f'(x) \\approx \\frac{f(x+ \\Delta x) - f(x)}{\\Delta x}$} \n%%\n% This is called the *forward difference* approximation. If we apply this\n% formula to itself, we come up with an approximation for the second\n% derivative of a function:\n%%\n% {\\Large\n% $ f''(x) \\approx \\frac{1}{\\Delta x}\\left(\\frac{f(x+\\Delta x+\\Delta\n% x)-f(x+\\Delta x)-f(x+\\Delta x)+f(x)}{\\Delta x}\\right)$}\n%%\n% or that, finally:\n%%\n% {\\Large\n% $ f''(x) \\approx \\frac{1}{\\Delta x^2}\\left(f(x+2\\Delta x\n% )-2f(x+\\Delta x)+f(x)\\right)$}\n%%\n% How to turn this into a matrix, however? If we imagine a function\n% expressed on a grid of points $${x_1,x_2,\\cdots,x_N}$ and replace the\n% function evaluation $$f(x+\\Delta x)$ with function evaluations at the\n% grid points, then the second derivative can be expressed as the following\n% matrix:\n%%\nN=5;\nI=ones(N,1);\nD2 = spdiags([I, -2*I, I],[-1:1],N,N);\nfull(D2)\n%%\n% Here we use the construct \n% spdiags\n% to tell MATLAB that the matrix is sparse, i.e. is composed of mainly zero\n% elements. In fact, this particular type of sparsity pattern is called\n% *tridiagonal*. Consider the second row of this matrix multiplied by a\n% vector which is the function evaluated on the grid of points $$x_i$,\n% $$\\left[f(x_0), f(x_1), f(x_2),\\cdots,f(x_N)\\right]^T$. We have the following \n% result:\n%%\n% \n% $ \\left(\\begin{array}{cccccc} 1&-2&1&0&\\cdots&0 \\end{array}\\right)\\times\n% \\left(\\begin{array}{c} f(x_0) \\\\ f(x_1) \\\\ f(x_2) \\\\ \\vdots \\\\\n% f(x_N)\\end{array}\\right) = f(x_0)-2\\times f(x_1)+f(x_2)$\n% \n%%\n% That is, the result of multiplying the second row of the differentiation\n% matrix by a vector representing our function on the grid, gives an\n% approximation to the derivative of our function on the grid. As an\n% example, let's calculate the second derivative of $$ f(x)=\\exp^{\\sin(x)}$ \n% on a grid of 21 points:\nN=21; x=linspace(0,2*pi,N)'; % set up the grid\nI=ones(N,1); dx=x(2)-x(1);\nD2 = spdiags([I, -2*I, I],[-1:1],N,N)/dx^2; %2nd derivative matrix\nf=@(x)(exp(sin(x))) % function\nd2 = D2*f(x); % numerical derivative\nd2(1)=1; d2(N)=1; % fix boundary points\nfigure('color',[1 1 1])\nplot(x,f(x),x,d2), grid on, hold on\nd2f=@(x)(cos(x).^2.*exp(sin(x))-sin(x).*exp(sin(x))) % actual second derivative\nplot(x,d2f(x),'r-.')\ntitle('Approximating a second derivative using a differentiation matrix');\nlegend('f(x)=exp^{sin(x)}','Approximate 2^{nd} deriv','Actual 2^{nd} deriv');\nhold off\n%% Systems of linear equations\n% At its heart, the subject of linear algebra is concerned with how to\n% solve the seemingly simple equation:\n%\n% $${\\bf{A}}x=b$,\n% where $${\\bf{A}}$ is a matrix and $$x$ and $$b$ are vectors.\n%%\n%\n% This might seem surprising, but this problem is right at the heart of\n% almost all problems in scientific computing, from differential equations\n% to eigenvalue problems to interpolation and curve fitting. \n\n%%\n% Of course, for a single scalar variable, x, we know what that means:\n% $$ a\\times x = y$\n% from which we can deduce that \n% $$ x = y/a$, for non-zero $$a$.\n%%\n% The question is how do we solve such a problem when we have more than one\n% unknown variable, or, equivalently, when x is a vector? To investigate this\n% question, let's consider the following electrical circuit:\n%\n[c,m]=imread('circuit2.gif','gif');\n\nfigure('color',[1 1 1]),\nimage(c), colormap(m), axis equal, axis off\n\n%%\n% We want to calculate the currents $$I_1,I_2,I_3$ \n%%\n% Using Kirchoff's voltage laws we get the following three equations for\n% the three unknown currents:\n%%\n% \n% $\\left\\{\\begin{array}{ccc}\n% I_1 + 25(I_1-I_2)+50(I_1-I_3) & = & 10 \\\\\n% 25(I_2-I_1) + 30I_2 + I_2 -I_3 & = & 0 \\\\\n% 50(I_3-I_1)+I_3-I_2+55I_3 & = & 0 \\end{array}\\right . $\n% \n%%\n% which, with a little re-arranging becomes:\n%%\n% \n% $\\left\\{\\begin{array}{ccc}\n% 76I_1 - 25I_2-50I_3 & = & 10 \\\\\n% -25I_1 +56I_2 -I_3 & = & 0 \\\\\n% -50I_1-I_2+106I_3 & = & 0 \\end{array}\\right .$\n% \n%%\n% Finally, we can gather all the coefficients into a matrix, and the\n% unknowns into a vector, to write the single matrix linear equation:\n%%\n% \n% $\\left( {\\begin{array}{ccc}\n% 76 & -25 & -50 \\\\\n% -25 & 56 & -1 \\\\\n% -50& -1 & 106 \\end{array}} \\right)\n% \\times \\left(\\begin{array}{c}\n% I_1\\\\\n% I_2\\\\\n% I_3 \\end{array}\\right) = \\left( \\begin{array}{c}\n% 10 \\\\\n% 0\\\\\n% 0 \\end{array}\\right)$\n% \n%%\n% In this way we have got the system of equations into the form that we\n% described above, namely:\n% $${\\bf{A}}x=b$\n%%\n% Of course, for a small system (3 by 3 in this case) we can solve this by\n% hand. For a larger system, however, we need a computer. The basic\n% approach to solving such a system is an extension of that used by hand,\n% namely we add and subtract multiples of one row to one another until we\n% finally end up with an upper triangular matrix. This action\n% of adding and subtrating multiples of one row to another is known as a\n% basic row operation. Let us illustrate the process with MATLAB. Before we\n% begin, we augment the right hand side vector to be an extra column in our\n% matrix $$\\bf A$, so it is now three rows by four columns.\nA=[76 -25 -50 10;-25 56 -1 0; -50 -1 106 0]\nrrefexample(A)\n%%\n% What is the advantage of reducing $${\\bf A}$ to be upper triangular?\n% Starting from the last row, we see that we now have an equation that\n% depends only on $$I_3$, that is $$I_3 = 0.117$. The row above depends on\n% $$I_3$ and $$I_2$ only, and we now know what $$I_3$ is! In this way, we\n% work our way up through the rows substituting as we go, and in each row\n% there is only a single unknown variable. This process is called _back\n% substitution_. This entire process - that of reducing the matrix to a\n% triangular form and solving via back substitution - is the way most\n% computer packages solve these linear systems. In MATLAB, the shorthand\n% way of solving such systems is with the backslash character ``\\''\nA=[76 -25 -50;-25 56 -1; -50 -1 106]\nb =[10;0;0]\nI= A\\b\n%%\n% In the example above, we have performed a special case of what is a more \n% general idea - that of transforming a matrix into a special form, so that \n% the equations can be solved more easily. In general, the idea of\n% transforming a matrix through a series of elementary row operations is a\n% powerful one. May special types of _matrix factorisations_ exist, and two\n% of the most important examples are:\n%%\n% *QR decomposition*\n% In this case, a general matrix is written as the product of two matrices,\n% one orthogonal and one upper triangular:\n% $${\\bf A = QR}$\n% As the inverse of an orthogonal matrix is equal to its transpose, we find\n% the solution to the general system $${\\bf A}x=b$ can be calculated as:\n%%\n% \n% $\\begin{array}{l}\n% {\\bf A}x = b \\\\\n% {\\bf QR}x = b \\\\\n% {\\bf Q}({\\bf R}x)=b \\\\\n% {\\bf R}x = {\\bf Q^T} \\times b \\\\\n% x = {\\bf R}\\setminus{\\bf Q^T} \\times b \\end{array}$\n% \n%%\n% *LU Decomposition*\n% In this case the matrix is decomposed into two, a lower and an upper\n% triangular matrix. As both the matrices are triangular, the back (and\n% forward) substitution process is very quick:\n%%\n% \n% $\\begin{array}{l}\n% {\\bf A}x = b \\\\\n% {\\bf LU}x = b \\\\\n% {\\bf L}({\\bf U}x)=b \\\\\n% {\\bf L}x = {\\bf U}\\setminus b \\\\\n% x = {\\bf L}\\setminus({\\bf U}\\setminus b) \\end{array}$\n% \n%%\n% As another example of using MATLAB to solve linear systems, let us\n% perform a least squares fit on some experimental data. We have run an\n% experiment to measure the distance fallen by an object in a given time.\n% We know from the laws of motion that the distance is related to the\n% initial velocity and position, and the acceleration through a quadratic\n% relationship:\n%%\n% $$x(t) = x(0) + v(0)t + \\frac{1}{2}gt^2$\n%%\n% We want to fit a quadratic line of best fit through the data, and hence\n% work out a rough estimate for $$g$ the acceleration due to gravity.\nload fall_data\nt=data(:,1);\ndist=data(:,2);\nI=ones(size(t));\nR=[I,t,t.^2]; % This is a VANDERMONDE matrix (see above)\ncoeffs = R\\dist\ng=2*coeffs(3) % approximation for g (coeff is g/2)\nplot(t,dist,'o',t,R*coeffs,'r'), grid on\ntitle('Fitting a quadratic curve to experimental data')\n\n\n\n\n%% Eigenvectors and Eigenvalues of a matrix\n% As we have seen, the action of a mtrix on a vector is one of rotation and\n% scaling. There are certain vectors, however, which in some sense\n% _resonate_ with some fundamental property of the matrix, and do not get\n% rotated. These special vectors (or directions in N-Dimensional space) are\n% called *eigenvectors* and the scaling factor by which they are stretched\n% are called the *eigenvalues*. Mathematically what we are saying is:\n% $$\\bf{A}x = \\lambda x$\n% Or visually we are saying:\nevecPlot\n%%\n% Essentially, what we are saying is that (square) matrices have certain \n% ``resonant modes'' or ``preferred'' co-ordinate directions, which we call\n% _eigenvectors_ of the matrix. The eigenvectors are orthogonal to one\n% another, and together form an orthogonal basis. If an $$N\\times N$ matrix\n% has N distinct eigenvalues, and correspondingly N orthogonal\n% eigenvectors, then it is said to have *Rank* N, or to be *full rank*.\n\n%%\n% To make all this more concrete, let's consider an example from the\n% mathematical theory of waves and vibration. In one dimension, the wave\n% equation can be written as the following _partial differential equation_\n% (don't worry about what this means, exactly, you'll learn more about all\n% this later). \n%%\n% {\\Large $\\frac{\\partial ^2 \\Psi}{\\partial t^2} = c\\frac{\\partial ^2\n% \\Psi}{\\partial x^2}$}\n%%\n% We solve such a system by a process known as _separation of the\n% variables_, and this involves writing the solution to the above equation\n% as a product of two parts, one purely dependent on space and the other on \n% time:\n%%\n% $${\\Large\\Psi\\left(x,t\\right) = \\Theta\\left(x\\right)\\Phi\\left(t\\right)}$\n%%\n% By substituting this form of the solution back into the differential\n% equation, we get:\n%%\n% $$\\ddot{\\Phi}(t)\\Theta(x)=c\\Phi(t)\\Theta''(x)$\n%%\n% or that\n%%\n% {\\Large$\\frac{\\ddot{\\Phi}(t)}{\\Phi(t)} =\n% c\\frac{\\Theta''(x)}{\\Theta(x)} = -k^2 $}\n%%\n% The only way that the left hand side, which is completely independent of \n% $$x$, can be equal to the right hand side, which is completely \n% independent of $$t$, is if both sides are equal to a constant, $$-k^2$.\n% We are interested in time independent solutions (standing waves) for this\n% problem, so we can consider only the spatial parts of the equation, which\n% can be written as:\n%%\n% \n% {\\Large$\\frac{\\partial ^2 \\Theta(x)}{\\partial x^2} = -k^2\\Theta(x)\n% $ }\n%%\n% This is an eigenvalue equation, exactly as we had above, and the\n% solutions we are looking for are called *eigenfunctions*. This particular\n% equation is important in physics and is known as the _Helmholtz\n% equation_.\n%%\n% Using the second derivative differentiation matrix we described above\n% (actually a more accurate version of it) and extending the notion to two\n% dimensions, we transform a differential equation into a matrix eigenvalue\n% equation. We can then use MATLAB to compute the eigenvalues and\n% eigenvectors numerically to investigate the standing wave patterns, for\n% example:\nchladni\n\n% Copyright 2008-2009 The MathWorks, Inc.\n% $Revision: 35 $ $Date: 2009-05-29 15:27:34 +0100 (Fri, 29 May 2009) $\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23039-matlab-in-physics-matrices/Lecture3/lecture3_Matrices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8807970764133561, "lm_q1q2_score": 0.7894155867467152}} {"text": "function a = lehmer ( m, n )\n\n%*****************************************************************************80\n%\n%% LEHMER returns the LEHMER matrix.\n%\n% Discussion:\n%\n% This matrix is also known as the \"Westlake\" matrix.\n%\n% Formula:\n%\n% A(I,J) = min ( I, J ) / max ( I, J )\n%\n% Example:\n%\n% N = 5\n%\n% 1/1 1/2 1/3 1/4 1/5\n% 1/2 2/2 2/3 2/4 2/5\n% 1/3 2/3 3/3 3/4 3/5\n% 1/4 2/4 3/4 4/4 4/5\n% 1/5 2/5 3/5 4/5 5/5\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is positive definite.\n%\n% A is totally nonnegative.\n%\n% The inverse of A is tridiagonal.\n%\n% The condition number of A lies between N and 4*N*N.\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Morris Newman, John Todd,\n% The evaluation of matrix inversion programs,\n% Journal of the Society for Industrial and Applied Mathematics,\n% Volume 6, Number 4, 1958, pages 466-476.\n%\n% Solutions to problem E710, proposed by DH Lehmer: The inverse of\n% a matrix.\n% American Mathematical Monthly,\n% Volume 53, Number 9, November 1946, pages 534-535.\n%\n% John Todd,\n% Basic Numerical Mathematics, Volume 2: Numerical Algebra,\n% Academic Press, 1977, page 154.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of A.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n a(i,j) = ( min ( i, j ) ) / ( max ( i, j ) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/lehmer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7894155710109605}} {"text": "function mortrage()\nclc;clear all; close all;\n% definitions\n% P = principle amount\n% J = Monthly intrest rate\n% R = Total monthly payment\n% R = J*P+ amount applied to principle\n% new principle amount\n% P+j*P-R => P(1+J)-R => P*m-R: m=1+J\n\n\n% inputs\npri=input('Principle amount ');\nYr=input(' No of Year ' );\nrate=input('Annual percentage rate ' );\nperyear=1/12;\npercent=1/100;\nttl_mnt=Yr*12;\nsyms m J P R A N;\n\n% the principal after n payments can be written as\n% P = A?mn ? R? (mn ? 1)/(m? 1).\nsolve(A*m^N - R*(m^N - 1)/(m - 1), R);\nR = subs(ans, m, J + 1);\nformat bank; \n disp( ' Interest Rate Payment')\n%for rate= 6:0.2:12 \n disp([rate, double(subs(R, [A, N, J], [pri, ttl_mnt, rate*percent*peryear]))])\n%end\nttl_payment=subs(R, [A, N, J], [pri, ttl_mnt, rate*percent*peryear])*ttl_mnt;\ndisp('total amunt paid =')\ndisp(ttl_payment)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18783-emi-calculator-for-fix-rate/mortrage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7893110948484982}} {"text": "%DEMO_PGAUSS How to use PGAUSS\n%\n% This script illustrates various properties of the Gaussian function.\n%\n% .. figure::\n%\n% Window+Dual+Tight\n%\n% This figure shows an optimally centered Gaussian for a \n% given Gabor system, its canonical dual and tight windows\n% and the DFTs of these windows.\n%\n% See also: pgauss\n\ndisp('Type \"help demo_pgauss\" to see a description of how this demo works.');\n\n% A quick test: If the second input parameter to\n% pgauss is not specified, the output will be\n% invariant under an unitary DFT. Matlabs FFT is does not\n% preserve the norm, so it must be scaled a bit.\n\nL=128;\ng=pgauss(L);\n\ndisp('');\ndisp('Test of DFT invariance: Should be close to zero.');\nnorm(g-dft(g))\n\n% Setup parameters and length of signal.\n% Note that it must hold that L=M*b=N*a for some integers\n% b and N, and that a <= M\nL=72; % Length of signal.\na=6; % Time shift.\nM=9; % Number of modulations.\n\n% Calculate the frequency shift.\nb=L/M;\n\n% For this Gabor system, the optimally concentrated Gaussian\n% is given by\ng=pgauss(L,a/b);\n\n% This is not invarient with respect to a DFT, but it is still\n% real and whole point even\ndisp('');\ndisp('The function is WP even. The following should be 1.');\nisevenfunction(g)\n\ndisp('Therefore, its DFT is real.');\ndisp('The norm of the imaginary part should be close to zero.');\nnorm(imag(dft(g)))\n\n% Calculate the canonical dual.\ngdual=gabdual(g,a,M);\n\n% Calculate the canonical tight window.\ngtight=gabtight(g,a,M);\n\n% Plot them:\n\n% Standard note on plotting:\n%\n% - All windows have real DFTs, but Matlab does not\n% always recoqnize this, so we have to filter away\n% the small imaginary part by calling REAL(...)\n%\n% - The windows are all centered around zero, but this\n% is not visually pleasing, so the window must be\n% shifted to the middle by an FFTSHIFT\n%\n\ngf_plot = fftshift(real(dft(g)));\ngdual_plot = fftshift(gdual);\ngdualf_plot = fftshift(real(dft(gdual)));\ngtight_plot = fftshift(gtight);\ngtightf_plot = fftshift(real(dft(gtight)));\nfigure(1);\n\nsubplot(3,2,1);\nx=(1:L).';\nplot(x,fftshift(g),'-',...\n x,circshift(fftshift(g),a),'-',...\n x,circshift(fftshift(g),-a),'-');\ntitle('g=pgauss(72,6/8)');\n\nsubplot(3,2,2);\nplot(gf_plot);\ntitle('g, frequency domain');\n\nsubplot(3,2,3);\nplot(gdual_plot);\ntitle('Dual window of g');\n\nsubplot(3,2,4);\nplot(gdualf_plot);\ntitle('dual window, frequency domain');\n\nsubplot(3,2,5);\nplot(gtight_plot);\ntitle('Tight window generated from g');\n\nsubplot(3,2,6);\nplot(gtightf_plot);\ntitle('tight window, frequency domain');\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_pgauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7892634413645289}} {"text": "function copl = isCoplanar(x,y,z,tol)\n%ISCOPLANAR Tests input points for coplanarity in 3-space.\n%\n% COPL = isCoplanar(PTS)\n% Tests the coplanarity of the input points in array PTS. Input array must\n% be 4-by-3, each row containing coordinate of one point.\n%\n% COPL = isCoplanar(PTS, TOLERANCE)\n% Specifies the tolerance value used for checking coplanarity. Default is\n% zero.\n% \n% \n% Example: \n% iscoplanar([1 2 -2; -3 1 -14; -1 2 -6; 1 -2 -8], eps)\n\n%\n% Adapted from a function originally written by Brett Shoelson, Ph.D.\n% brett.shoelson@joslin.harvard.edu\n% https://fr.mathworks.com/matlabcentral/fileexchange/46-iscoplanar-m\n%\n\nif nargin == 0\n\terror('Requires at least one input argument.'); \n \nelseif nargin == 1\n if size(x,2) == 3\n % Matrix of all x,y,z is input\n pts = x;\n tol = 0;\n else\n error('Invalid input.')\n end\n \nelseif nargin == 2\n\tif size(x,2) == 3\n\t\t% Matrix of all x,y,z is input\n\t\tpts = x;\n\t\ttol = y;\n\telse\n\t\terror('Invalid input.')\n\tend\nelseif nargin == 3\n\t% Compile a matrix of all x,y,z\n\tpts = [x y z];\n\ttol = 0;\nelse\n\tpts = [x y z];\nend\n\nif size(x, 1) < 4\n error('Requires at least four points to compute coplanarity');\nend\n\n% replace first point at the origin and compute SVD of the matrix\nsv = svd(bsxfun(@minus, pts(2:end,:), pts(1,:)));\ncopl = sv(3) <= tol * sv(1);\n\n% % Alterantive version that computes the rank of the matrix\n% rnk = rank(bsxfun(@minus, pts(2:end,:), pts(1,:)), tol);\n% copl = rnk <= size(pts, 2) - 1;\n\n% % Old version:\n% %Compare all 4-tuples of point combinations; {P1:P4} are coplanar iff\n% %det([x1 y1 z1 1;x2 y2 z2 1;x3 y3 z3 1;x4 y4 z4 1])==0\n% tmp = nchoosek(1:size(pts,1),4);\n% for ii = 1:size(tmp,1)\n% \tcopl = abs(det([pts(tmp(ii, :), :) ones(4,1)])) <= tolerance;\n% \tif ~copl\n% \t\tbreak\n% \tend\n% 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/z_geom3d/geom3d/isCoplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7892634312490636}} {"text": "function sig = signature(b,x0,y0)\n%SIGNATURE Computes the signature of a boundary.\n% SIG = SIGNATURE(B,X0,Y0) computes the signature of boundary. B. A\n% signature is defined as the distance (DIST) from (X0,Y0) to the\n% boundary, as a function of angle. B is an np-by-2 matrix, with np >=\n% 360, whose rows contain the (x,y) = (row,col) coordinates of the\n% boundary ordered in a clockwise or counterclockwise direction. If\n% (X0,Y0) is not included in the input argument, the centroid of the\n% boundary is used by default. SIG is a vector of size size 360-by-1,\n% indicating a signature resolution of one degree. The input must be a\n% one-pixel-thick boundary obtained, for example, by using function\n% bwboundaries.\n%\n% If (X0,Y0) or the default centroid is outside the boundary, the\n% signature is not defined and an error is issued.\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 dimensions of b.\n[np,nc] = size(b);\nif (np < 360 || nc ~= 2)\n error('b must be of size (>=360)-by-2.');\nend\n\n% Some boundary tracing programs, such as bwboundaries.m, result in a\n% sequence in which the coordinates of the first and last points are the\n% same. If this is the case, in b, eliminate the last point.\nif isequal(b(1,:),b(np,:))\n b = b(1:np - 1,:);\n np = np - 1;\nend\n\n% If (x0,y0) is not specified, set the origin from which the signature\n% is computed as the centroid.\nif nargin == 1\n % Coordinates of the centroid.\n x0 = sum(b(:,1))/np;\n y0 = sum(b(:,2))/np;\nend\n\n% Check to see that (x0,y0) is inside the boundary.\nIN = inpolygon(x0,y0,b(:,1),b(:,2));\nif ~IN\n error('(x0,y0) or centroid is not inside the boundary.')\nend\n\n% Shift origin of coordinate system to (x0,y0).\nb(:,1) = b(:,1) - x0;\nb(:,2) = b(:,2) - y0;\n\n% Convert the coordinates to polar. But first have to convert the given\n% image coordinates, (x,y), to the coordinate system used by MATLAB for\n% conversion between Cartesian and polar cordinates. Designate these\n% coordinates by (xcart,ycart). The two coordinate systems are related\n% as follows: xcart = y and ycart = -x, where (x,y) = (row,col).\nxcart = b(:,2);\nycart = -b(:,1);\n[theta,rho] = cart2pol(xcart,ycart);\n\n% Convert angles to degrees.\ntheta = theta.*(180/pi);\n\n% Convert to all nonnegative angles.\nj = theta == min(theta(:));\nk = theta == max(theta(:));\ntheta = theta.*(0.5*abs(1 + sign(theta)))...\n - 0.5*(-1 + sign(theta)).*(360 + theta);\n\n% Set the smallest angle to 0 and the largest angle to 359.\ntheta(j) = 0;\ntheta(k) = 359;\n\n% Sort angles in ascending order and pair them with the corresponding\n% rho\n[theta,idx] = sort(theta);\nrho(idx) = rho;\nn = size(theta,1);\n\n% Subsample the signature into 360 angle increments.\nn = size(rho,1);\nidx = round(linspace(1,n,360));\nrho = rho(idx);\nsig = rho;\n\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/signature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.7892058980822944}} {"text": "% This is a small script to compute the Bethe approximation of a small\n% factor graph. The factor graph is generated by taking the Bayes net of\n% Lauritzen and Spiegelhalter (1988) and setting the following random\n% variables as evidence\n%\n% visit to Asia = false\n% positive X-ray = true\n% smoking = true\n%\n% For this particular set of evidence, the Bethe approximation is exact\n% because the corresponding factor graph does not have any cycles.\n%\n% For more information, see: Lauritzen and Speigelhalter (1988). \"Local\n% computations with probabilities on graphical structures and their\n% application to expert systems.\" Journal of the Royal Statistical\n% Society, Series B, Vol. 50, No. 2, pp. 157-194.\n%\n% 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\nverbose = true;\n\n% The remaining random variables can either be true or false. They are:\n% 1. tuberculosis\n% 2. lung cancer\n% 3. bronchitis\n% 4. tuberculosis or lung cancer\n% 5. dysponoea\nnv = 5; % The number of random variables.\nnf = 6; % The number of factors.\nK = 2*ones(nv,1); % The number of possible discrete assignments to the \n % random variable at each site. \nC = cell(nf,1); % The factor neighbourhoods.\nf = cell(nf,1); % The factors.\n\n% Set up the factors.\n% ------------------\n% This is p(tuberculosis | visit to Asia = false).\nC{1} = 1;\nf{1} = [ 0.01 0.99 ]';\n\n% This is p(lung cancer | smoking = true).\nC{2} = 2;\nf{2} = [ 0.1 0.9 ]';\n\n% This is p(bronchitis | smoking = true).\nC{3} = 3;\nf{3} = [ 0.6 0.4 ]';\n\n% This is p(tuberculosis or lung cancer | tuberculosis, lung cancer).\nC{4} = [4 1 2];\np = zeros(2,2,2);\np(:,1,1) = [ 0.99 0.01 ]';\np(:,1,2) = [ 0.99 0.01 ]';\np(:,2,1) = [ 0.99 0.01 ]';\np(:,2,2) = [ 0.99 0.01 ]';\nf{4} = p;\n\n% This is p(positive X-ray = true | tuberculosis or lung cancer).\nC{5} = 4;\nf{5} = [ 0.98 0.5 ]';\n\n% This is p(dyspnoea | tuberculosis or lung cancer, bronchitis).\nC{6} = [5 4 3];\np = zeros(2,2,2);\np(:,1,1) = [ 0.9 0.1 ]';\np(:,1,2) = [ 0.7 0.3 ]';\np(:,2,1) = [ 0.8 0.2 ]';\np(:,2,2) = [ 0.1 0.9 ]';\nf{6} = p;\nclear p\n\n% Set up the junction graph.\n% -------------------------\n% These are the large regions of the junction graph.\nRv{1} = [1 2 4];\nRf{1} = [1 2 4];\nNR{1} = [1];\n\nRv{2} = [3 4 5];\nRf{2} = [3 5 6];\nNR{2} = [1];\n\n% These are the small regions of the junction graph.\nSv{1} = [4];\nSf{1} = [];\nNS{1} = [1 2];\n\nnr = length(Rv); % The number of large regions.\nns = length(Sv); % The number of small regions.\n\n% Infer the region marginals.\n% --------------------------\n% Compute the junction graph approximation to the variational free\n% energy. Since the junction graph is a tree in this case (trivially,\n% because there are only two large regions), the junction graph\n% approximation is exact.\nqR = bopt(K,C,f,Rv,Rf,Sv,Sf,NS,verbose);\n\n% Output the marginal probabilities.\n% ---------------------------------\np = ndsum(qR{1},[2 3]);\nfprintf('Pr(tuberculosis | evidence) = %0.2f \\n', p(1));\n\np = ndsum(qR{1},[1 3]);\nfprintf('Pr(lung cancer | evidence) = %0.2f \\n', p(1));\n\np = ndsum(qR{2},[2 3]);\nfprintf('Pr(bronchitis | evidence) = %0.2f \\n', p(1));\n\np = ndsum(qR{2},[1 2]);\nfprintf('Pr(dysponoea | evidence) = %0.2f \\n', p(1));\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/ipopt/distribution/examples/bayesnet/examplelauritzen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7891695110310757}} {"text": "function [ fea, out ] = ex_convdiff3( varargin )\n%EX_CONVDIFF3 1D Time dependent convection and diffusion equation example.\n%\n% [ FEA, OUT ] = EX_CONVDIFF3( VARARGIN ) 1D time dependendt convection and diffusion equation on\n% a line with an infinately oscillating exact solution. Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% w scalar {1.5*pi} Simulation parameter\n% U scalar {2} Simulation parameter\n% a scalar {1} Convection velocity\n% nu scalar {0.1} Diffusion coefficient\n% hmax scalar {1/25} Max grid cell size\n% dt scalar {0.02} Time step size\n% ischeme scalar {3} Time stepping scheme\n% sfun string {sflag2} Shape function\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'w', 1.5*pi; ...\n 'U', 2; ...\n 'a', 1; ...\n 'nu', 0.1; ...\n 'hmax', 1/25; ...\n 'dt' 0.02; ...\n 'ischeme' 3; ...\n 'sfun', 'sflag1'; ...\n 'iplot', 1; ...\n 'tol', 3e-2; ...\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\nw = opt.w;\nU = opt.U;\na = opt.a;\nnu = opt.nu;\nl1 = ['(',num2str(a),'+sqrt(',num2str(a^2),'+',num2str(4*nu*w),'*i))/',num2str(2*nu)];\nl2 = ['(',num2str(a),'-sqrt(',num2str(a^2),'+',num2str(4*nu*w),'*i))/',num2str(2*nu)];\nrefsol = ['(exp(',l1,'*x)-exp(',l2,'*x))/(exp(',l1,')-exp(',l2,'))*',num2str(U),'*exp(i*',num2str(w),'*t)'];\nrefsol0 = ['(exp(',l1,'*x)-exp(',l2,'*x))/(exp(',l1,')-exp(',l2,'))*',num2str(U)];\n\n\n% Grid generation.\nfea.grid = linegrid( 1/opt.hmax, 0, 1 );\n\n\n% Problem definition.\nfea.sdim = { 'x' };\nfea = addphys( fea, @convectiondiffusion );\nfea.phys.cd.sfun = { opt.sfun };\nfea.phys.cd.eqn.coef{2,4} = { opt.nu };\nfea.phys.cd.eqn.coef{3,4} = { opt.a };\nfea = parsephys(fea);\n\n\n% Parse and solve problem.\nfea = parseprob( fea );\nfea.bdr.d{1} = 0;\nfea.bdr.d{2} = [num2str(U),'*cos(',num2str(w),'*t)'];\nfea.bdr.n = cell(1,2);\nx = fea.grid.p';\nif( strcmp( opt.sfun,'sflag2' ) )\n x = [ x; (x(2:end)+x(1:end-1))/2 ];\nend\ninit = real( eval( refsol0 ) );\n[fea.sol.u,tlist] = solvetime( fea, 'fid', fid, 'init', init, 'ischeme', opt.ischeme, 'tstep', opt.dt, 'tmax', 1 );\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n figure;\n if( opt.iplot>1 )\n i_sol_list = 1:numel(tlist);\n else\n i_sol_list = numel(tlist);\n end\n [~,ix] = sort( x );\n for i_sol=i_sol_list\n t = tlist(i_sol);\n clf\n postplot( fea, 'surfexpr', 'c', 'solnum', i_sol );\n hold on\n u_r = real( eval( refsol ) );\n plot( sort(x), u_r(ix), 'r--' );\n title( ['Solution at time ',num2str(t)])\n xlabel( 'x' )\n drawnow\n end\nend\n\n\n% Error checking.\nfor i_sol=1:numel(tlist)\n u_i = fea.sol.u(:,i_sol);\n t = tlist(i_sol);\n u_r = real( eval( refsol ) );\n errnm(i_sol) = norm( u_i - u_r )/norm( u_r );\nend\nout.err = errnm;\nout.pass = all( errnm= 0\n%\n% NOTE: WE ONLY HANDLE PROBLEMS WITH BOUNDED SUBPROBLEM LPs.\n% IF WE ENCOUNTER AN UNBOUNDED SUBPROBLEM, THEN WE QUIT.\n\n% generate a random example\nn = 50; % number of variables\nm1 = 15; % number of equations to relax\nm2 = 10; % number of equations to keep\n\nrng('default');\nrng(1); % set seed\nE = rand(m1,n); % random m1-by-n matrix\nA = rand(m2,n); % random m2-by-n matrix\n\nw = rand(n,1); % generate rhs's so problem is feasible\nh = E*w;\nb = A*w;\n\nc = rand(n,1); % generate random objective\n% first we will calculate the optimal value z of the original LP, just to\n% compare later\ndisp('Optimizing the original LP without Lagrangian relaxation');\n[x,z,exitflag] = linprog(c,[],[],[E; A],[h; b],zeros(n,1),[]);\nif (exitflag < 1)\n disp('fail 1: original LP (without using LR) did not solve correctly');\n return;\nend;\n\ndisp('Optimal value of the original LP:');\nz\n\ndisp('Starting Subgradient Optimization');\n\nMAXIT = 100; % number of iterations\n\nresults1 = zeros(MAXIT,1);\nresults2 = zeros(MAXIT,1);\n\nk = 0; % iteration counter\ny = zeros(m1,1); % initialize y as you like\ng = zeros(m1,1); % initialize g arbitrarily --- it will essentially be ignored\nstepsize = 0; % just to have us really start at the initialized y\nbestlb = -Inf;\nwhile k < MAXIT \n k = k + 1; % increment the iteration counter\n y = y + stepsize*g; % take a step in the direction of the subgradient\n % solve the Lagrangian\n [x,subval,exitflag,output,dualsol] = linprog((c'-y'*E)',[],[],A,b,zeros(n,1),[]); \n v = h'*y + (c'-y'*E)*x; % calculate the value of the Lagrangian\n disp(v);\n bestlb = max(bestlb,v);\n results1(k)=k;\n results2(k)=v;\n g = h - E*x; % calculate the subgradient \n stepsize = 1/k; % calculate the step size\nend\n\nbestlb\n\nz\n\nclf; % clear figure\n% plot the sequence of MAXIT lower bounds\nplot(results1,results2,'k--.','MarkerSize',15); \nhold on;\n% plot a horizontal line at height z\nplot([1,MAXIT],[ z z ], 'r-','LineWidth',2.5) \naxis tight;\nxlabel('Iteration');\nylabel('Lagrangian lower bound');\nlegend('Lagrangian LB','z','Location','SouthEast');\n\nprint -djpeg SubgradientOpt.jpeg;\n\n% Next, if y really solves the Lagrangian dual, and pi is the \n% optimal solution to the Lagrangian subproblem corresponding to y,\n% then y and pi should be an optimal dual solution to the given problem.\n% \n% Let's see if y and pi are nearly dual feasible.\n\npi = - dualsol.eqlin;\nTotal_Dual_Infeasibility = norm(min(c' - y'*E - pi'*A,zeros(1,n)))\n\n\n\n\n\n", "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/SubgradientOpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7891364856158583}} {"text": "function [H,info] = freqwavelet(name,L, varargin)\n%FREQWAVELET Wavelet in the freq. domain\n% Usage: H=freqwavelet(name,L)\n% H=freqwavelet(name,L,scale)\n% [H,info]=freqwavelet(...)\n%\n% Input parameters:\n% name : Name of the wavelet\n% L : System length\n% Output parameters:\n% H : Frequency domain wavelet\n% info : Struct with additional outputs\n%\n% `freqwavelet(name,L)` returns peak-normalized \"mother\" frequency-domain\n% wavelet `name` for system length *L*. The basic scale is selected such\n% that the peak is positioned at the frequency 0.1 relative to the Nyquist\n% rate (fs/2).\n%\n% The supported wavelets that can be used in place of `name` (the actual\n% equations can be found at the end of this help):\n%\n% 'cauchy' Cauchy wavelet with alpha=100. Custom order=(alpha-1)/2\n% (with alpha>1) can be set by `{'cauchy',alpha}`. The\n% higher the order, the narrower and more symmetric the\n% wavelet. A numericaly stable formula is used in order\n% to allow support even for very high `alpha` e.g.\n% 10^6.\n%\n% 'morse' Morse wavelet with alpha=100 and gamma=3. Both parameters\n% can be set directly by `{'morse',alpha,gamma}`. `alpha`\n% has the same role as for 'cauchy', `gamma` is the\n% 'skewness' parameter. 'morse' becomes 'cauchy' for\n% gamma=1.\n%\n% 'morlet' Morlet wavelet with sigma=4. The parameter `sigma` \n% is the center frequency to standard deviation ratio of\n% the main generating Gaussian distribution. Note that the \n% true peak and standard deviation of the Morlet wavelet \n% differ, in particular for low values of `sigma` (<5). \n% This is a consequence of the correction factor. The \n% parameter can be set directly by `{'morlet',sigma}`.\n% \n% 'fbsp' Frequency B-spline wavelet of order m=3, center frequency\n% to bandwidth ratio fb = 2. The parameters can be set\n% by `{'fbsp',m,fb}`. Note that `m` must be integer and\n% greater than or equal to 1, and `fb` must be greater than \n% or equal to 2. \n%\n% 'analyticsp' Positive frequency part of cosine-modulated B-spline \n% wavelet of order order=3, with center frequency to main \n% lobe width ratio fb = 1. The parameters can be set by \n% `{'analyticsp',order,fb}`. Note that `order` and `fb` \n% must be integer and greater than or equal to 1.\n%\n% 'cplxsp' Complex-modulated B-spline of order order=3, with center\n% frequency to main lobe width ratio fb = 1. The parameters \n% can be set by `{'cplxsp',order,fb}`. Note that `order` \n% and `fb` must be integer and greater than or equal to 1.\n%\n% `freqwavelet(name,L,scale)` returns a \"dilated\" version of the wavelet.\n% The nonzero scalar `scale` controls both the bandwidth and the center\n% frequency. Values greater than 1 make the wavelet wider (and narrower \n% in the frequency domain), values lower than 1 make the wavelet narrower.\n% The center frequency is moved to`0.1/scale`. The center frequency is \n% limited to the range of \"positive\" frequencies ]0,1] (up to Nyquist rate).\n% If `scale` is a vector, the output is a `L x numel(scale)` matrix with \n% the individual wavelets as columns.\n%\n% The following additional flags and key-value parameters are available:\n%\n% 'scale' Wavelet scale (relative to basic scale)\n%\n% 'waveletParams' a vector containing the respective wavelet parameters\n% [alpha, beta, gamma] for cauchy and morse wavelets\n% [sigma] for morlet wavelets\n% [order, fb] for splines \n%\n% 'basefc',fc Normalized center frequency of the mother wavelet\n% (scale=1). The default is 0.1.\n%\n% 'bwthr',bwthr The height at which the bandwidth is computed.\n% The default value is 10^(-3/10) (~0.5).\n%\n% 'efsuppthr',thr The threshold determining the effective support of\n% the wavelet. The default value is 10^(-5).\n%\n% 'scal',s Scale the filter by the constant *s*. This can be\n% useful to equalize channels in a filter bank.\n%\n% 'delay',d Set the delay of the filter. Can be either a scalar or\n% a vector of the same length as *scale*. Default value is zero.\n%\n% The admissible range of scales can be adjusted to handle different \n% scenarios:\n%\n% 'positive' Enables the construction of wavelets at postive\n% center frequencies ]0,1]. If `basefc=0.1`, this \n% corresponds to scales larger than or equal to 0.1.\n% This is the default.\n%\n% 'negative' Enables the construction of wavelets at negative \n% center frequencies [-1,0[. If `basefc=0.1`, this \n% corresponds to scales smaller than or equal to -0.1.\n%\n% 'analytic' Enables the construction of wavelets with center \n% frequencies in ]0,2] for analysis of analytic signals. \n% [! This feature is currently experimental and may not\n% always work as intended. !]\n%\n% The format of the output is controlled by the following flags:\n% 'full' (default),'econ','asfreqfilter':\n%\n% 'full' The output is a `L x numel(scale)` matrix.\n%\n% 'econ' The output is a `numel(scale)` cell array with\n% individual freq. domain wavelets truncated to the\n% length of the effective support given by parameter 'efsuppthr'.\n% Does not run stably for system lengths > 2000\n%\n% 'asfreqfilter' As 'econ', but the elements of the cell-array are\n% filter structs with fields .H and .foff as in \n% |blfilter| to be used in |filterbank| and related. \n%\n% `[H,info]=freqwavelet(...)` additionally returns a struct with the\n% following fields:\n%\n% .fc Normalized center frequency.\n%\n% .foff Index of the first sample above the effective\n% support threshold (minus one). \n% It can be directly used to convert the 'econ'\n% output to 'full' by `circshift(postpad(H,L),foff)`.\n%\n% .fsupp Length of the effective support (with values above \n% efsuppthr).\n%\n% .basefc Center frequency of the implied mother wavelet.\n%\n% .scale The scale used.\n%\n% .dilation The actual dilation used in the formula.\n%\n% .bw Relative bandwidth at -3 dB (half of the height).\n%\n% .tfr Time-frequency ratio of a Gaussian with the same\n% bandwidth as the wavelet.\n%\n% .aprecise Exact natural subsampling factors (not rounded). \n%\n% .a_natural Fractional natural subsampling factors in the\n% format acceptable by |filterbank| and related.\n%\n% .cauchyAlpha Alpha value of closest Cauchy wavelet [NOTE: Not \n% implemented for non-Morse wavelets.]\n%\n% Additionally, the function accepts flags to normalize the output.\n% Please see the help of |setnorm|. By default, no normaliazation is\n% applied.\n%\n% Wavelet definitions\n% -------------------\n%\n% `C` is a normalization constant.\n%\n% Cauchy wavelet\n%\n% H = C \\xi^{\\frac{\\alpha-1}{2}} exp( -2\\pi\\xi )\n%\n% .. math:: H = C \\xi^{\\frac{\\alpha-1}{2}} exp( -2\\pi\\xi )\n%\n% Morse wavelet\n%\n% H = C \\xi^{\\frac{\\alpha-1}{2\\gamma}} exp( -2\\pi\\xi^{\\gamma} )\n%\n% .. math:: H = C \\xi^{\\frac{\\alpha-1}{2\\gamma}} exp( -2\\pi\\xi^{\\gamma} )\n%\n% Morlet wavelet\n%\n% H = C \\xi^{\\frac{\\alpha-1}{2\\gamma}} exp( -2\\pi\\xi^{\\gamma} )\n%\n% .. math:: H = C \\xi^{\\frac{\\alpha-1}{2\\gamma}} exp( -2\\pi\\xi^{\\gamma} )\n%\n% Frequency bandlimited spline wavelet\n%\n% H = C B (\\xi - m \\frac{\\xi}{4})\n%\n% .. math:: H = C B (\\xi - m \\frac{\\xi}{4})\n%\n% Analytic spline wavelet\n%\n% H = C exp(-j \\omega x) A(-exp(j \\omega)) H(exp(-j \\omega)\n%\n% .. math:: H = C exp(-j \\omega x) A(-exp(j \\omega)) H(exp(-j \\omega))\n%\n% Complex spline wavelet\n%\n% H = C exp(-j \\omega x + \\xi )\n%\n% .. math:: H = C exp(-j \\omega x + \\xi )\n%\n%\n% References: rioul92 unalsc94\n%\n% See also: setnorm, filterbank, blfilter\n\n\n\ncomplainif_notenoughargs(nargin,2,upper(mfilename));\n\n%set default input parameters\nif ~isscalar(L)\n error('%s: L must be a scalar',upper(mfilename));\nend\n\nif ~iscell(name), name = {name}; end\n\nfreqwavelettypes = getfield(arg_freqwavelet(),'flags','wavelettype');\n\nif ~ischar(name{1}) || ~any(strcmpi(name{1},freqwavelettypes))\n error('%s: First input argument must be the name of a supported window.',...\n upper(mfilename));\nend\n\n\ndefinput.import={'setnorm', 'freqwavelet'};\ndefinput.importdefaults={'null'};\ndefinput.keyvals.scale = 1;\ndefinput.keyvals.scal = [];\ndefinput.keyvals.basefc = 0.1;\ndefinput.keyvals.delay=0;\ndefinput.keyvals.fc = [];\ndefinput.keyvals.bwthr = 10^(-3/10);\ndefinput.keyvals.efsuppthr = 10^(-5);\ndefinput.flags.freqrange = {'positive','negative','analytic'};\ndefinput.flags.outformat = {'full','econ','asfreqfilter'};\ndefinput.keyvals.fs = 2;\ndefinput.keyvals.alphaStep = definput.keyvals.fs/L;\n\nif ~iscell(name)\n name = {name};\nend\n\n\n[flags,kv,scale]=ltfatarghelper({'scale'},definput,varargin,'freqwavelet');\n\n%check L\nif ~isscalar(L)\n error('%s: L must be a scalar',upper(mfilename));\nend\n\n%check basefc\nif ~isscalar(kv.basefc)\n error('%s: basefc must be a positive scalar',upper(mfilename));\nend\n\nscale = scale(:).'; % Scale should always be a row vector\nif ~isnumeric(scale), error('%s: scale must be numeric',upper(mfilename)); end\n\nif isempty(kv.scal)\n kv.scal = scale;\nelseif ~isnumeric(kv.scal)\n error('%s: scal must be numeric',upper(mfilename)); \nelseif numel(kv.scal) ~= numel(scale)\n error('%s: scal must have exactly as many entries as scale',upper(mfilename)); \nend\n\nif kv.alphaStep > 0.02\n error('%s: wavelet sampling too small. increase system length.',upper(mfilename));\nend\n\n%if L/scale > 10\n% error('%s: scale too large.',upper(mfilename));\n%end\n\n% Check range of scales\nif flags.do_positive && (any(scale <= 0) || any(kv.basefc./scale > 1))\n error('%s: Frequency range flag is set to positive. scale must be positive and not smaller than basefc.', upper(mfilename)); \nend\nif flags.do_negative && (any(scale >= 0) || any(kv.basefc./scale < -1))\n error('%s: Frequency range flag is set to negative. scale must be negative and not larger than -basefc.', upper(mfilename)); \nend\nif flags.do_analytic && (any(scale <= 0) || any(kv.basefc./scale > 2))\n error('%s: Frequency range flag is set to analytic. scale must be positive and not smaller than 2*basefc.', upper(mfilename)); \nend\n\n% Check delay vector\nif numel(kv.delay) == 1\n kv.delay = repmat(kv.delay, 1, numel(scale));\nend\nif numel(kv.delay) ~= numel(scale)\n error('%s: delay must have exactly as many entries as scale',upper(mfilename));\nend\n% Check other parameters\nif kv.efsuppthr < 0, error('%s: efsuppthr must be nonnegative',upper(mfilename)); end\nif kv.bwthr < 0, error('%s: bwthr must be nonnegative',upper(mfilename)); end\nif kv.bwthr < kv.efsuppthr, error('%s: efsuppthr must be lower than bwthr.',upper(mfilename)); end\n\nM = numel(scale);\n\n\nif flags.do_full\n H = zeros(L,M);\nelse\n H = cell(1,M);\nend\n\nif flags.do_negative\n wltype = 'negative';\nelse\n wltype = 'positive';\nend\n\n%% generate the wavelet prototype\n[fun, fsupp_, peakpos, cauchyAlpha] = helper_waveletgeneratorfunc(name, wltype);\n\n%% calculate the support as f(scale)\nfsupp = zeros(5,M);\nfsupp(5,:) = kv.fs;\nbasedil = peakpos/(kv.basefc);\n\nif kv.efsuppthr > 0\n fsupp(1,:) = max(0,(fsupp_(1)/basedil)./scale);\n fsupp(5,:) = min(kv.fs,(fsupp_(5)/basedil)./scale);\nend\nfsupp(2,:) = max(0,(fsupp_(2)/basedil)./scale);\nfsupp(3,:) = (fsupp_(3)/basedil)./scale;\nfsupp(4,:) = min(kv.fs,(fsupp_(4)/basedil)./scale);\n\n\nif flags.do_negative\n fsupp = flip(fsupp);\nend\n\nfsuppL = fsuppL_inner(fsupp,kv.fs,L,1:5);\n\n\n%% calculate H\nif flags.do_full\n if ~flags.do_negative\n y = ((0:L-1)').*basedil*kv.alphaStep*scale;\n else\n y = ([0;(L-1:-1:1)']).*basedil*kv.alphaStep*scale;\n end\n H = abs(kv.scal).*setnorm(fun(y), flags.norm); \nelseif flags.do_econ\n for ii = 1:numel(scale)\n y = ((fsuppL(1,ii):fsuppL(end,ii)-1)').*basedil*kv.alphaStep*abs(scale(ii));\n H{ii} = abs(kv.scal(ii)).*setnorm(fun(y), flags.norm);%TODO: check output format: should be cell\n end\nelseif flags.do_asfreqfilter\n for m = 1:numel(scale)\n y = @(L) ((fsuppL_inner(fsupp(:,m),kv.fs,L,1):fsuppL_inner(fsupp(:,m),kv.fs,L,5)-1)').*basedil*abs(scale(m))*kv.fs/L;\n H{m} = struct('H',@(L) abs(kv.scal(m))*setnorm(fun(y(L)),flags.norm),'foff',@(L)fsuppL_inner(fsupp(:,m),kv.fs,L,1),'realonly',0, 'delay', kv.delay(m));\n end\nend\n\n%% write info struct\ninfo.basefc = kv.basefc; \ninfo.fc = fsupp(3,:);\ninfo.scale = scale;%';\ninfo.dilation = basedil.*scale;%';\ninfo.fsupp = fsuppL(end,:) - fsuppL(1,:) + ones(1,numel(scale));\nif info.fsupp <= 0, info.fsupp = 0; end\ninfo.bw = (fsupp(4,:) - fsupp(2,:));\nbwinsamples = info.bw./kv.alphaStep;\ninfo.aprecise = L./bwinsamples;\ninfo.a_natural(:,2) = ceil(bwinsamples);\ninfo.a_natural = info.a_natural';\ninfo.tfr = (cauchyAlpha - 1)./(pi*info.fc.^2*L);\ninfo.cauchyAlpha = cauchyAlpha;\ninfo.foff = fsuppL(1,:);\n\n\n%if M==1 && iscell(H)\n% H = H{1};\n%end\n\nend\n\nfunction fsuppL = fsuppL_inner(fsupp,fs,L,idx)\n fsuppL_all = [ ceil(fsupp(1:2,:)/fs*L); round(fsupp(3,:)/fs*L); floor(fsupp(4:5,:)/fs*L) ];\n fsuppL = fsuppL_all(idx,:);\nend \n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/freqwavelet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7891364819815846}} {"text": "function varargout = euclideanMST(points)\n%EUCLIDEANMST Build euclidean minimal spanning tree of a set of points.\n%\n% EDGES = euclideanMST(POINTS)\n% POINTS is a [NxP] array, N being the number of points and P being the\n% dimension.\n% Result EDGES is a [Mx2] array, containing indices of each vertex for\n% each edges.\n%\n% [EDGES DISTS] = euclideanMST(POINTS)\n% Also returns the lengths of edges computed by MST algorithm.\n%\n% Algorithm first computes Delaunay triangulation of the set of points,\n% then computes euclidean length of each edge of triangulation, and\n% finally uses prim algorithm to simplify the graph.\n%\n% Example\n% % choose random points in the plane and display their Euclidean MST\n% pts = rand(50, 2)*100;\n% edges = euclideanMST(pts);\n% drawGraph(pts, edges)\n%\n% See also \n% prim_mst, distancePoints, delaunayn\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2007-07-27, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2007-2022 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas\n\n% dimension\nD = size(points, 2);\nDf = factorial(D);\n\n% compute all couples of vertices in unit triangle, tetrahedron, or n-dim\n% simplex\nsubs = zeros(Df, 2);\nk = 1;\nfor i = 1:D\n for j = i+1:D+1\n subs(k, 1) = i;\n subs(k, 2) = j;\n k = k + 1;\n end\nend\n\n% compute delaunay triangulation in D dimensions\ntri = delaunayn(points);\nNt = size(tri, 1);\n\n% compute all possible edges\nedges = zeros(Nt*Df, 2);\nfor t = 1:Nt\n for i = 1:Df\n edges((t-1)*Df+i, 1) = tri(t, subs(i, 1));\n edges((t-1)*Df+i, 2) = tri(t, subs(i, 2));\n end\nend\n\n% simplify edges\nedges = unique(sort(edges, 2), 'rows');\n\n% compute euclidean length of each edge\nval = zeros(size(edges, 1), 1);\nfor i = 1:size(edges,1)\n val(i) = distancePoints(points(edges(i,1), :), points(edges(i,2), :));\nend\n\n% compute MST of created graph\n[edges2, vals2] = prim_mst(edges, val);\n\n% process output arguments\nif nargout == 1\n varargout{1} = edges2;\nelseif nargout==2\n varargout{1} = edges2;\n varargout{2} = vals2;\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/graphs/euclideanMST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7891207195379408}} {"text": "function [x]=grandn(a,b)\n\n\n\n% function [x]=grandn(a,b)\n% random number generator from the Gamma (a,b) distribution\n\n\n% part 1: obtain a random number from Gamma(a,1)\n\nif a>=1\nx=gammadrawover1(a);\nelse\nxtilde=gammadrawover1(a+1);\nu=rand;\nx=xtilde*u^(1/a);\nend\n\n% part 2: transform into a draw from G(a,b)\nx=x*b;\n\n\n% auxiliary nested function to draw a Gamma random number when argument 'a' is greater than or equal to 1\nfunction x=gammadrawover1(a)\nd=a-1/3;\nc=1/((9*d)^0.5);\ncheck=0;\n while check==0\n z=randn;\n u=rand;\n v=(1+c*z)^3;\n if (v>0 && log(u)<0.5*z^2+d-d*v+d*log(v))\n x=d*v;\n check=1;\n else\n check=0;\n end\n end\nend\n\n\n% declare end of general function\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/grandn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782469, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7891059312640081}} {"text": "function [ intersect, p ] = plane_imp_line_par_int_3d ( a, b, c, d, x0, y0, z0, ...\n f, g, h )\n\n%*****************************************************************************80\n%\n%% PLANE_IMP_LINE_PAR_INT_3D: intersection ( implicit plane, parametric line ) in 3D.\n%\n% Discussion:\n%\n% The implicit form of a plane in 3D is:\n%\n% A * X + B * Y + C * Z + D = 0\n%\n% The parametric form of a line in 3D is:\n%\n% X = X0 + F * T\n% Y = Y0 + G * T\n% Z = Z0 + H * T\n%\n% We normalize by choosing F*F+G*G+H*H=1 and 0 <= F.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983, page 111.\n%\n% Parameters:\n%\n% Input, real A, B, C, D, the implicit plane parameters.\n%\n% Input, real X0, Y0, Z0, F, G, H, parameters that define the\n% parametric line.\n%\n% Output, logical INTERSECT, is TRUE if the line and the plane\n% intersect.\n%\n% Output, real P(3), is a point of intersection of the line\n% and the plane, if INTERSECT is TRUE.\n%\n dim_num = 3;\n tol = 0.00001;\n%\n% Check.\n%\n norm1 = sqrt ( a * a + b * b + c * c );\n\n if ( norm1 == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_IMP_LINE_PAR_INT_3D - Fatal error!\\n' );\n fprintf ( 1, ' The plane normal vector is null.\\n' );\n error ( 'PLANE_IMP_LINE_PAR_INT_3D - Fatal error!' )\n end\n\n norm2 = sqrt ( f * f + g * g + h * h );\n\n if ( norm2 == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_IMP_LINE_PAR_INT_3D - Fatal error!\\n' );\n fprintf ( 1, ' The line direction vector is null.\\n' );\n error ( 'PLANE_IMP_LINE_PAR_INT_3D - Fatal error!' )\n end\n\n denom = a * f + b * g + c * h;\n%\n% The line and the plane may be parallel.\n%\n if ( abs ( denom ) < tol * norm1 * norm2 )\n\n if ( a * x0 + b * y0 + c * z0 + d == 0.0 )\n intersect = 1;\n p(1) = x0;\n p(2) = y0;\n p(3) = z0;\n else\n intersect = 0;\n p(1:dim_num) = 0.0;\n end\n%\n% If they are not parallel, they must intersect.\n%\n else\n\n intersect = 1;\n t = - ( a * x0 + b * y0 + c * z0 + d ) / denom;\n p(1) = x0 + t * f;\n p(2) = y0 + t * g;\n p(3) = z0 + t * h;\n\n end\n\n return\nend\n", "meta": {"author": "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_line_par_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7889581352247977}} {"text": "function p = chebyshev(n,var)\n%CHEBYSHEV Chebyshev polynomial (exactly representable up to degree n<=81)\n%\n% p = chebyshev(n,var)\n%\n%Computed by recursion\n% p(0,x) = 1\n% p(1,x) = x\n% p(n,x) = 2*x*p(n-1,x) - p(n-2,x) for n>1\n%\n%Parameter var for dependent variable optional (default 'x')\n%\n\n% written 07/30/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%\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 var = 'x';\n else\n if ~ischar(var)\n error('variable must be string')\n end\n end\n \n if n==0\n p = polynom(1,var);\n elseif n==1\n p = polynom([1 0],var);\n else\n t1 = [1 zeros(1,n)];\n t2 = [0 1 zeros(1,n-1)];\n for i=3:n+1\n t3 = [0 2*t2(1:n)] - t1; \n t1 = t2; \n t2 = t3; \n end\n p = polynom(fliplr(t3),var);\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/chebyshev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7888400331258227}} {"text": "function pdf = gompertz_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% GOMPERTZ_PDF evaluates the Gompertz PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B) = B * A**X / exp ( B * ( A**X - 1 ) / log ( A ) )\n%\n% for\n%\n% 0.0 <= X\n% 1.0 < A\n% 0.0 < B\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 X, the argument of the PDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 1 < A, 0 < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0.0 )\n\n pdf = 0.0;\n\n elseif ( 1.0 < a )\n\n pdf = exp ( log ( b ) + x * log ( a ) - ( b / log ( a ) ) * ( a^x - 1.0 ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/gompertz_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7888222799853332}} {"text": "function ASK_FSK_PSK(msglen)\n%msglen= number of bits to be transmitted\n%take msglen=10000, or 20000 for more accuracy\n%If you have any problem or feedback please contact me @\n%%===============================================\n% NIKESH BAJAJ\n% Asst. Prof., Lovely Professional University, India\n% Almameter: Aligarh Muslim University, India\n% +919915522564, bajaj.nikkey@gmail.com\n%%===============================================\nn=msglen;\nb=randint(1,n);\nf1=1;f2=2;\nt=0:1/30:1-1/30;\n%ASK\nsa1=sin(2*pi*f1*t);\nE1=sum(sa1.^2);\nsa1=sa1/sqrt(E1); %unit energy \nsa0=0*sin(2*pi*f1*t);\n%FSK\nsf0=sin(2*pi*f1*t);\nE=sum(sf0.^2);\nsf0=sf0/sqrt(E);\nsf1=sin(2*pi*f2*t);\nE=sum(sf1.^2);\nsf1=sf1/sqrt(E);\n%PSK\nsp0=-sin(2*pi*f1*t)/sqrt(E1);\nsp1=sin(2*pi*f1*t)/sqrt(E1);\n\n%MODULATION\nask=[];psk=[];fsk=[];\nfor i=1:n\n if b(i)==1\n ask=[ask sa1];\n psk=[psk sp1];\n fsk=[fsk sf1];\n else\n ask=[ask sa0];\n psk=[psk sp0];\n fsk=[fsk sf0];\n end\nend\nfigure(1)\nsubplot(411)\nstairs(0:10,[b(1:10) b(10)],'linewidth',1.5)\naxis([0 10 -0.5 1.5])\ntitle('Message Bits');grid on\nsubplot(412)\ntb=0:1/30:10-1/30;\nplot(tb, ask(1:10*30),'b','linewidth',1.5)\ntitle('ASK Modulation');grid on\nsubplot(413)\nplot(tb, fsk(1:10*30),'r','linewidth',1.5)\ntitle('FSK Modulation');grid on\nsubplot(414)\nplot(tb, psk(1:10*30),'k','linewidth',1.5)\ntitle('PSK Modulation');grid on\nxlabel('Time');ylabel('Amplitude')\n%AWGN\nfor snr=0:20\n askn=awgn(ask,snr);\n pskn=awgn(psk,snr);\n fskn=awgn(fsk,snr);\n\n %DETECTION\n A=[];F=[];P=[];\n for i=1:n\n %ASK Detection\n if sum(sa1.*askn(1+30*(i-1):30*i))>0.5\n A=[A 1];\n else\n A=[A 0];\n end\n %FSK Detection\n if sum(sf1.*fskn(1+30*(i-1):30*i))>0.5\n F=[F 1];\n else\n F=[F 0];\n end\n %PSK Detection\n if sum(sp1.*pskn(1+30*(i-1):30*i))>0\n P=[P 1];\n else\n P=[P 0];\n end\n end\n\n %BER\n errA=0;errF=0; errP=0;\n for i=1:n\n if A(i)==b(i)\n errA=errA;\n else\n errA=errA+1;\n end\n if F(i)==b(i)\n errF=errF;\n else\n errF=errF+1;\n end\n if P(i)==b(i)\n errP=errP;\n else\n errP=errP+1;\n end\n end\n BER_A(snr+1)=errA/n;\n BER_F(snr+1)=errF/n;\n BER_P(snr+1)=errP/n;\nend\n\nfigure(2)\nsubplot(411)\nstairs(0:10,[b(1:10) b(10)],'linewidth',1.5)\naxis([0 10 -0.5 1.5]);grid on\ntitle('Received signal after AWGN Channel')\nsubplot(412)\ntb=0:1/30:10-1/30;\nplot(tb, askn(1:10*30),'b','linewidth',1.5)\ntitle('Received ASK signal');grid on\nsubplot(413)\nplot(tb, fskn(1:10*30),'r','linewidth',1.5)\ntitle('Received FSK signal');grid on\nsubplot(414)\nplot(tb, pskn(1:10*30),'k','linewidth',1.5)\ntitle('Received PSK signal');grid on\nfigure(3)\nsemilogy(0:20,BER_A, 'b','linewidth',2)\ntitle('BER Vs SNR')\ngrid on;\nhold on\nsemilogy(0:20,BER_F,'r','linewidth',2)\nsemilogy(0:20,BER_P, 'k','linewidth',2)\nxlabel('Eo/No(dB)')\nylabel('BER')\nhold off\nlegend('ASK','FSK','PSK');\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30995-digital-modulationask-psk-fsk/ASK_FSK_PSK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7887483317625076}} {"text": "% Optimal doping profile optimization with current gain constraint.\n% Boyd, Kim, Vandenberghe, and Hassibi, \"A tutorial on geometric programming\"\n% Joshi, Boyd, and Dutton, \"Optimal doping profiles via geometric programming\"\n% Written for CVX by Almir Mutapcic 02/08/06\n% (a figure is generated)\n%\n% Determines the optimal doping profile that minimizes base transit\n% time subject to a lower bound constraint on the current gain (beta).\n% This problem can be posed as a GP:\n%\n% minimize tau_B\n% s.t. Nmin <= v <= Nmax\n% y_(i+1) + v_i^const1 <= y_i\n% w_(i+1) + v_i^const2 <= w_i, etc...\n% beta => beta_min\n%\n% where variables are v_i, y_i, and w_i.\n\n% problem size\nM = 20;\n\n% problem constants\ng1 = 0.42;\ng2 = 0.69;\nNmax = 5*10^18;\nNmin = 5*10^16;\nNref = 10^17;\nDn0 = 20.72;\nni0 = 1.4*(10^10);\nWB = 10^(-5);\nC = WB^2/((M^2)*(Nref^g1)*Dn0);\n\n% minimum current gain values\nbeta_min_GE = [1 1.4 1.8 2.2 2.6 3.0 3.4 3.43]*(1e-11);\n\n% exponent powers\npwi = g2 -1;\npwj = 1+g1-g2;\n\nv_array = [];\nfor k = 1:length(beta_min_GE)\n fprintf( 'beta_min_GE = %g: ', beta_min_GE(k) );\n cvx_begin gp quiet\n % optimization variables\n variables v(M) y(M) w(M)\n\n % objective function is the base transmit time\n tau_B = C*w(1);\n\n minimize( tau_B )\n subject to\n % fixed problem constraints\n Nmin <= v <= Nmax;\n\n for i=1:M-1\n y(i+1) + v(i)^pwj <= y(i);\n w(i+1) + y(i)*v(i)^pwi <= w(i);\n end\n\n % equalities\n y(M) == v(M)^pwj;\n w(M) == y(M)*v(M)^pwi;\n\n % changing constraint\n (WB*beta_min_GE(k)/(M*Nref^(g1-g2)*Dn0))*y(1) <= 1;\n cvx_end\n fprintf( '%s\\n', cvx_status );\n % keep the optimal solution\n v_array = [v_array v];\nend\n\n% plot the basic optimal doping profile\nfigure, clf\nnbw = 0:1/M:1-1/M;\nfor k = 1:length(beta_min_GE)\n semilogy(nbw,v_array(:,k),'LineWidth',2); hold on;\nend\naxis([0 1 1e16 1e19]);\nxlabel('base');\nylabel('doping');\ntext(0,Nmin,'Nmin ', 'HorizontalAlignment','right');\ntext(0,Nmax,'Nmax ', 'HorizontalAlignment','right');\nhold off;\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/gp_tutorial/beta_min_odp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7887483210879745}} {"text": "% CXCORR Circular Cross Correlation function estimates. \n% CXCORR(a,b), where a and b represent samples taken over time interval T\n% which is assumed to be a common period of two corresponded periodic signals. \n% a and b are supposed to be length M row vectors, either real or complex.\n% \n% [x,c]=CXCORR(a,b) returns the length M-1 circular cross correlation sequence c\n% with corresponded lags x.\n% \n% The circular cross correlation is:\n% c(k) = sum[a(n)*conj(b(n+k))]/[norm(a)*norm(b)]; \n% where vector b is shifted CIRCULARLY by k samples.\n%\n% The function doesn't check the format of input vectors a and b!\n%\n% For circular covariance between a and b look for CXCOV(a,b) in\n% http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objectType=author&objectId=1093734\n%\n% Reference:\n% A. V. Oppenheim, R. W. Schafer and J. R. Buck, Discrete-Time Signal Processing, \n% Upper Saddler River, NJ : Prentice Hall, 1999.\n%\n% Author: G. Levin, Apr. 26, 2004.\n\nfunction [x,c]=CXCORR(a,b)\nna=norm(a);\nnb=norm(b);\na=a/na; %normalization\nb=b/nb;\nfor k=1:length(b)\n c(k)=a*b';\n b=[b(end),b(1:end-1)]; %circular shift\nend\nx=[0:length(b)-1]; %lags", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4810-circular-cross-correlation/cxcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7887483197164662}} {"text": "% CONVERT ROTATION ANGLES INTO A QUATERNION\nfunction [q] = GetQuaternionFromEulers(eulers)\n% THis function converts euler angle rotations into a\n% quaternion via its components. Associated block:\n% \"Rotation Angles to Quaternions\".\neulers = 0.5*eulers;\n% Build vector of trigonometric arguements\ntrigArgs = [sin(eulers);cos(eulers)];\n% Assemble Quaternion components\nq = zeros(4,1);\nq(1) = trigArgs(4)*trigArgs(5)*trigArgs(6) + trigArgs(1)*trigArgs(2)*trigArgs(3);\nq(2) = trigArgs(4)*trigArgs(5)*trigArgs(3) - trigArgs(1)*trigArgs(2)*trigArgs(6);\nq(3) = trigArgs(4)*trigArgs(2)*trigArgs(6) + trigArgs(1)*trigArgs(5)*trigArgs(3);\nq(4) = trigArgs(1)*trigArgs(5)*trigArgs(6) - trigArgs(4)*trigArgs(2)*trigArgs(3);\n% Renormalise\nq = unit(q);\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/GetQuaternionFromEulers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7887084681610408}} {"text": "function [tfr,t,f] = tfrppage(x,t,N,h,trace);\n%TFRPPAGE Pseudo Page time-frequency distribution.\n%\t[TFR,T,F]=TFRPPAGE(X,T,N,H,TRACE) computes the Pseudo Page \n%\tdistribution of a discrete-time signal X, or the\n%\tcross Pseudo Page representation between two signals. \n% \n%\tX : signal if auto-PPage, or [X1,X2] if cross-PPage.\n%\tT : time instant(s) (default : 1:length(X)).\n%\tN : number of frequency bins (default : length(X)).\n%\tH : frequency smoothing window, H(0) being forced to 1.\n%\t (default : Hamming(N/4)). \n%\tTRACE : if nonzero, the progression of the algorithm is shown\n%\t (default : 0).\n%\tTFR : time-frequency representation. When called without \n%\t output arguments, TFRPPAGE runs TFRQVIEW.\n%\tF : vector of normalized frequencies.\n%\n%\tExample :\n%\t sig=fmlin(128,0.1,0.4); tfrppage(sig);\n% \n%\tSee also all the time-frequency representations listed in\n%\t the file CONTENTS (TFR*)\n\n%\tF. Auger, May-August 1994, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n[xrow,xcol] = size(x);\nif (nargin < 1),\n error('At least 1 parameter is required');\nelseif nargin<=2,\n N=xrow;\nend;\n\nhlength=floor(N/4);\nif (rem(hlength,2)==0),\n hlength=hlength+1;\nend;\n\nif (nargin == 1),\n t=1:xrow; h = tftb_window(hlength); trace=0;\nelseif (nargin == 2 | nargin == 3),\n h = tftb_window(hlength); trace = 0;\nelseif (nargin == 4),\n trace = 0;\nend;\n\nif (N<0),\n error('N must be greater than zero');\nend;\n[trow,tcol] = size(t);\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nelseif (trow~=1),\n error('T must only have one row'); \nelseif (2^nextpow2(N)~=N),\n fprintf('For a faster computation, N should be a power of two\\n');\nend; \n\n[hrow,hcol]=size(h); Lh=(hrow-1)/2; h=h/h(Lh+1);\nif (hcol~=1)|(rem(hrow,2)==0),\n error('H must be a smoothing window with odd length');\nend;\n\ntfr= zeros (N,tcol) ; \nif trace, disp('Pseudo Page distribution'); end;\nfor icol=1:tcol,\n ti= t(icol); tau=0:min([N-1,Lh,ti-1]);\n indices= rem(N+tau,N)+1;\n if trace, disprog(icol,tcol,10); end;\n tfr(indices,icol)=h(Lh+1+tau).*x(ti,1).*conj(x(ti-tau,xcol));\nend; \nif trace, fprintf('\\n'); end;\ntfr= real(fft(tfr)); \n\nif (nargout==0),\n tfrqview(tfr,x,t,'tfrppage',h);\nelseif (nargout==3),\n if rem(N,2)==0, \n f=[0:N/2-1 -N/2:-1]'/N;\n else\n f=[0:(N-1)/2 -(N-1)/2:-1]'/N; \n end;\nend;\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrppage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7885718499337548}} {"text": "function value = r8_choose ( n, k )\n\n%*****************************************************************************80\n%\n%% R8_CHOOSE computes the binomial coefficient C(N,K).\n%\n% Discussion:\n%\n% The value is calculated in such a way as to avoid overflow and\n% roundoff. The calculation is done in integer arithmetic.\n%\n% The formula used is:\n%\n% C(N,K) = N! / ( K! * (N-K)! )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 March\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% ML Wolfson, HV Wright,\n% Algorithm 160:\n% Combinatorial of M Things Taken N at a Time,\n% Communications of the ACM,\n% Volume 6, Number 4, April 1963, page 161.\n%\n% Parameters:\n%\n% Input, integer N, K, are the values of N and K.\n%\n% Output, real VALUE, the number of combinations of N\n% things taken K at a time.\n%\n mn = min ( k, n - k );\n\n if ( mn < 0 )\n\n value = 0;\n\n elseif ( mn == 0 )\n\n value = 1;\n\n else\n\n mx = max ( k, n - k );\n value = mx + 1;\n\n for i = 2 : mn\n value = ( value * ( mx + i ) ) / i;\n end\n\n end\n\n return\nend\n", "meta": {"author": "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/r8_choose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7885718427486891}} {"text": "function y = loggausspdf2(X, sigma)\n% log pdf of Gaussian with zero mena\n% Based on code written by Mo Chen (mochen@ie.cuhk.edu.hk). March 2009.\nd = size(X,1);\n\n[R,p]= chol(sigma);\nif p ~= 0\n error('ERROR: sigma is not SPD.');\nend\nq = sum((R'\\X).^2,1); % quadratic term (M distance)\nc = d*log(2*pi)+2*sum(log(diag(R))); % normalization constant\ny = -(c+q)/2;\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/loggausspdf2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248123094438, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7885310332664195}} {"text": "function result = polygon_1_2d ( n, v )\n\n%*****************************************************************************80\n%\n%% POLYGON_1_2D integrates the function 1 over a polygon in 2D.\n%\n% Discussion\n%\n% The polygon is bounded by the points (X(1:N), Y(1:N)).\n%\n% INTEGRAL = 0.5 * SUM ( 1 <= I <= N )\n% ( X(I) + X(I-1) ) * ( Y(I) - Y(I-1) )\n%\n% where X(0) and Y(0) should be replaced by X(N) and Y(N).\n%\n% Note that the integral of 1 over a polygon is the area of the polygon.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% S F Bockman,\n% Generalizing the Formula for Areas of Polygons to Moments,\n% American Mathematical Society Monthly,\n% 1989, pages 131-132.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n% N should be at least 3 for a nonzero result.\n%\n% Input, real V(2,N), the coordinates of the vertices\n% of the polygon. These vertices should be given in counter-clockwise order.\n%\n% Output, real RESULT, the value of the integral.\n%\n result = 0.0;\n\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_1_2D - Warning!\\n' );\n fprintf ( 1, ' The number of vertices must be at least 3.\\n' );\n fprintf ( 1, ' The input value of N = %d\\n', n );\n error ( 'POLYGON_1_2D - Fatal error!' );\n end\n\n for i = 1 : n\n\n if ( i == 1 )\n im1 = n;\n else\n im1 = i - 1;\n end\n\n result = result + 0.5 * ( v(1,i) + v(1,im1) ) * ( v(2,i) - v(2,im1) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_1_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.788374630313724}} {"text": "function [V,F]=platonic_solid(varargin)\n\n% function [V,F]=platonic_solid(n,r)\n% ------------------------------------------------------------------------\n% PLATONIC_SOLID Creates the PATCH data, the vertices (V) and faces (F) for\n% a given platonic solid (according to \"n\" see below) with radius (r)\n%\n% n=1 -> Tetrahedron\n% n=2 -> Cube\n% n=3 -> Octahedron\n% n=4 -> Icosahedron\n% n=5 -> Dodecahedron\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 12/08/2014 Updated for GIBBON\n%------------------------------------------------------------------------\n%% Parse input\n\nswitch nargin\n case 1\n n=varargin{1};\n r=1;\n case 2\n n=varargin{1};\n r=varargin{2};\nend\n\nif isempty(r)\n r=1; \nend\n\n%%\nswitch n\n case 1 % Tetrahedron\n X=[-0.5;0.5;0;0;];\n Y=[-sqrt(3)/6; -sqrt(3)/6; sqrt(3)/3; 0];\n Z=[-0.25.*sqrt(2/3); -0.25.*sqrt(2/3); -0.25.*sqrt(2/3); 0.75.*sqrt(2/3)];\n X=X([1 2 4 3]);\n Y=Y([1 2 4 3]);\n Z=Z([1 2 4 3]); \n F=[3,2,1;1,2,4;2,3,4;4,3,1;];\n F=fliplr(F);\n case 2 % Cube\n X=[-1; 1; 1; -1; -1; 1; 1; -1;];\n Y=[-1; -1; 1; 1; -1; -1; 1; 1;];\n Z=[-1; -1;-1; -1; 1; 1; 1; 1;];\n F=[4,3,2,1;\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;];\n case 3 % Octahedron\n X=[-1; 1; 1; -1; 0; 0;];\n Y=[-1; -1; 1; 1; 0; 0;];\n Z=[ 0; 0; 0; 0; -1; 1;];\n F=[5,2,1;5,3,2;5,4,3;5,1,4;1,2,6;2,3,6;3,4,6;4,1,6;]; \n case 4 % Icosahedron\n phi=(1+sqrt(5))/2;\n X=[0;0;0;0;-1;-1;1;1;-phi;phi;phi;-phi;];\n Y=[-1;-1;1;1;-phi;phi;phi;-phi;0;0;0;0;];\n Z=[-phi;phi;phi;-phi;0;0;0;0;-1;-1;1;1;];\n F=[9,4,1;1,5,9;1,8,5;10,8,1;4,10,1;5,2,12;12,2,3;12,3,6;12,6,9;12,9,5;10,7,11;8,10,11;2,8,11;3,2,11;7,3,11;2,5,8;10,4,7;7,6,3;6,7,4;6,4,9;];\n case 5 % Dodecahedron\n phi=(1+sqrt(5))/2;\n X=[1;(1/phi);-phi;phi;-1;0;-phi;1;-1;-1;1;(1/phi);-1;0;0;-(1/phi);phi;-(1/phi);1;0;];\n Y=[1;0;-(1/phi);(1/phi);1;-phi;(1/phi);-1;1;-1;-1;0;-1;-phi;phi;0;-(1/phi);0;1;phi;];\n Z=[1;phi;0;0;-1;-(1/phi);0;1;1;1;-1;-phi;-1;(1/phi);-(1/phi);phi;0;-phi;-1;(1/phi);];\n F=[20,9,16,2,1;2,16,10,14,8;16,9,7,3,10;7,9,20,15,5;18,13,3,7,5;3,13,6,14,10;6,13,18,12,11;6,11,17,8,14;11,12,19,4,17;1,2,8,17,4;1,4,19,15,20;12,18,5,15,19;];\n otherwise\n warning('False input for n')\nend\n\n%Altering radius\n[THETA,PHI,~]=cart2sph(X,Y,Z);\n[X,Y,Z]=sph2cart(THETA,PHI,r.*ones(size(X)));\nV=[X(:) Y(:) Z(:)];\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/platonic_solid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7883746270744878}} {"text": "function krn = spm_smoothkern(fwhm,x,t)\n% Generate a Gaussian smoothing kernel\n% FORMAT krn = spm_smoothkern(fwhm,x,t)\n% fwhm - full width at half maximum\n% x - position\n% t - either 0 (nearest neighbour) or 1 (linear).\n% [Default: 1]\n%\n% krn - value of kernel at position x\n%__________________________________________________________________________\n%\n% For smoothing images, one should really convolve a Gaussian with a sinc\n% function. For smoothing histograms, the kernel should be a Gaussian\n% convolved with the histogram basis function used. This function returns\n% a Gaussian convolved with a triangular (1st degree B-spline) basis \n% function (by default). A Gaussian convolved with a hat function (0th \n% degree B-spline) can also be returned.\n%__________________________________________________________________________\n% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_smoothkern.m 4419 2011-08-03 18:42:35Z guillaume $\n\n\nif nargin<3, t = 1; end\n\n% Variance from FWHM\ns = (fwhm/sqrt(8*log(2)))^2+eps;\n\n% The simple way to do it. Not good for small FWHM\n% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));\n\nif t==0\n % Gaussian convolved with 0th degree B-spline\n % int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)\n w1 = 1/sqrt(2*s);\n krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));\n krn(krn<0) = 0;\n\nelseif t==1\n % Gaussian convolved with 1st degree B-spline\n % int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)\n % +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)\n w1 = 0.5*sqrt(2/s);\n w2 = -0.5/s;\n w3 = sqrt(s/2/pi);\n krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...\n +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));\n krn(krn<0) = 0;\n\nelse\n error('Only defined for nearest neighbour and linear interpolation.');\n % If anyone knows a nice formula for a sinc function convolved with a\n % a Gaussian, then that could be quite useful.\nend\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_smoothkern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7883746264983028}} {"text": "function variance = logistic_variance ( a, b )\n\n%*****************************************************************************80\n%\n%% LOGISTIC_VARIANCE returns the variance of the Logistic PDF.\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, real VARIANCE, the variance of the PDF.\n%\n variance = ( pi * b )^2 / 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/prob/logistic_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7883746134009115}} {"text": "function [ lambda, x ] = jacobi_iterate ( n, a )\n\n%*****************************************************************************80\n%\n%% JACOBI_ITERATE applies the Jacobi eigenvalue iteration to a symmetric matrix.\n%\n% Discussion:\n%\n% I had to modify the code, in order to avoid cases where the\n% off-diagonal element was not exactly zero, but very very close.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real A(N,N), a symmetric matrix.\n% On output, the matrix has been overwritten by an approximately\n% diagonal matrix, with the eigenvalues on the diagonal.\n%\n% Output, real LAMBDA(N), the computed eigenvalues.\n%\n% Output, real X(N,N), the computed eigenvector matrix.\n%\n eps = 0.00001;\n maxit = 100;\n\n error_frobenius = r8mat_is_symmetric ( n, n, a );\n\n if ( eps < error_frobenius )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_ITERATE - Fatal error!\\n' );\n fprintf ( 1, ' The input matrix is not symmetric.\\n' );\n error ( 'JACOBI_ITERATE - Fatal error!' );\n end\n\n b(1:n,1:n) = a(1:n,1:n);\n\n norm_fro = r8mat_norm_fro ( n, n, b );\n\n x = identity ( n, n );\n\n for it = 1 : maxit\n\n for i = 1 : n\n for j = 1 : i - 1\n\n if ( eps * norm_fro < abs ( b(i,j) ) + abs ( b(j,i) ) )\n\n u = ( b(j,j) - b(i,i) ) / ( b(i,j) + b(j,i) );\n\n t = r8_sign ( u ) / ( abs ( u ) + sqrt ( u * u + 1.0 ) );\n c = 1.0 / sqrt ( t * t + 1.0 );\n s = t * c;\n%\n% A -> A * Q.\n%\n for k = 1 : n\n t1 = b(i,k);\n t2 = b(j,k);\n b(i,k) = t1 * c - t2 * s;\n b(j,k) = t1 * s + t2 * c;\n end\n%\n% A -> Q' * A\n%\n for k = 1 : n\n t1 = b(k,i);\n t2 = b(k,j);\n b(k,i) = c * t1 - s * t2;\n b(k,j) = s * t1 + c * t2;\n end\n%\n% X -> Q' * X\n%\n for k = 1 : n\n t1 = x(k,i);\n t2 = x(k,j);\n x(k,i) = c * t1 - s * t2;\n x(k,j) = s * t1 + c * t2;\n end\n\n end\n\n end\n end\n%\n% Test the size of the off-diagonal elements.\n%\n sum2 = 0.0;\n for i = 1 : n\n sum2 = sum2 + sum ( abs ( b(i,1:i-1) ) );\n end\n\n if ( sum2 <= eps * ( norm_fro + 1.0 ) )\n break\n end\n\n end\n\n lambda = diag ( b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/jacobi_iterate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.7883483321040496}} {"text": "function [EC,ec,degij] = edge_nei_overlap_bu(CIJ)\n% EDGE_NEI_OVERLAP_BU Overlap amongst neighbors of two adjacent nodes\n%\n% [EC,ec,degij] = edge_nei_bu(CIJ);\n%\n% This function determines the neighbors of two nodes that are linked by \n% an edge, and then computes their overlap. Connection matrix must be\n% binary and directed. Entries of 'EC' that are 'inf' indicate that no\n% edge is present. Entries of 'EC' that are 0 denote \"local bridges\", i.e.\n% edges that link completely non-overlapping neighborhoods. Low values\n% of EC indicate edges that are \"weak ties\".\n%\n% If CIJ is weighted, the weights are ignored.\n%\n% Inputs: CIJ, undirected (binary/weighted) connection matrix\n% \n% Outputs: EC, edge neighborhood overlap matrix\n% ec, edge neighborhood overlap per edge, in vector format\n% degij, degrees of node pairs connected by each edge\n%\n% Reference: Easley and Kleinberg (2010) Networks, Crowds, and Markets. \n% Cambridge University Press, Chapter 3.\n%\n% Olaf Sporns, Indiana University, 2012\n\n[ik,jk,ck] = find(CIJ);\nlel = length(ck);\nN = size(CIJ,1);\n\n[deg] = degrees_und(CIJ);\n\nec = zeros(1,lel);\ndegij = zeros(2,lel);\nfor e=1:lel\n neiik = setdiff(union(find(CIJ(ik(e),:)),find(CIJ(:,ik(e))')),[ik(e) jk(e)]);\n neijk = setdiff(union(find(CIJ(jk(e),:)),find(CIJ(:,jk(e))')),[ik(e) jk(e)]);\n ec(e) = length(intersect(neiik,neijk))/length(union(neiik,neijk));\n degij(:,e) = [deg(ik(e)) deg(jk(e))];\nend;\n\nff = find(CIJ);\nEC = 1./zeros(N);\nEC(ff) = ec; %#ok\n\n\n", "meta": {"author": "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/edge_nei_overlap_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8688267643505194, "lm_q1q2_score": 0.7882971328303451}} {"text": "function quadmom_test08 ( )\n\n%*****************************************************************************80\n%\n%% QUADMOM_TEST08 integrates sin(x) against a lower truncated normal weight.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub, John Welsch,\n% Calculation of Gaussian Quadrature Rules,\n% Mathematics of Computation,\n% Volume 23, Number 106, April 1969, pages 221-230.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUADMOM_TEST08:\\n' );\n fprintf ( 1, ' Integrate sin(x) against a lower truncated normal weight.\\n' );\n\n mu = 0.0;\n sigma = 1.0;\n a = -3.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' MU = %g\\n', mu );\n fprintf ( 1, ' SIGMA = %g\\n', sigma );\n fprintf ( 1, ' A = %g\\n', a );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Estimate\\n' );\n fprintf ( 1, '\\n' );\n%\n% N is the order of the quadrature rule.\n%\n for n = 1 : 9\n%\n% Compute the M = 2 * N + 1 moments.\n%\n m = 2 * n + 1;\n\n moment = moments_truncated_normal_a ( m, mu, sigma, a );\n%\n% Compute the N points and weights by the method of moments.\n%\n [ x, w ] = moment_method ( n, moment );\n%\n% Evaluate the quadrature rule when f(x) = sin(x).\n%\n q = w' * sin ( x );\n\n fprintf ( 1, ' %2d %14.6g\\n', n, q );\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/quadmom/quadmom_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7882320760049008}} {"text": "function p = legendre(n,var)\n%LEGENDRE Legendre polynomial\n%\n% p = legendre(n,var)\n%\n%Computed by recursion\n% p(0,x) = 1\n% p(1,x) = x\n% p(n,x) = (2*n-1)/n * x * p(n-1,x) - (n-1)/n * p(n-2,x) for n>1\n%\n%Parameter var for dependent variable optional (default 'x')\n%\n\n% written 07/30/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%\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 var = 'x';\n else\n if ~ischar(var)\n error('variable must be string')\n end\n end\n \n if n==0\n p = polynom(1,var);\n elseif n==1\n p = polynom([1 0],var);\n else\n t1 = [1 zeros(1,n)];\n t2 = [0 1 zeros(1,n-1)];\n for i=3:n+1\n t3 = (2*i-3)/(i-1)*[0 t2(1:n)] - (i-2)/(i-1)*t1;\n t1 = t2; \n t2 = t3; \n end\n p = polynom(fliplr(t3),var);\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/legendre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7882320724805518}} {"text": "function [A, B] = zeroKronApprox( K, m, n )\n%\n% [A, B] = zeroKronApprox( K, m, n );\n%\n% computes a kronecker sum approximation to the blurring matrix K\n% that arises from the input PSF under zero boundary conditions.\n% This approximation is done a-la Kamm-Nagy (see paper for details). \n%\n% Input:\n% K - psfMatrix object\n% m - size of matrix A (assumed square)\n% n - size of matrix B (assumed square)\n%\n% Output:\n% Matrices A and B such that K \\aprrox A \\otimes B.\n%\n\n% J. Nagy 2/11/02\n\n% Modifications: This used to be zeroSepMatrix, which did not compute\n% A and B. \n% 5/25/02, J. Nagy \n% This now computes A and B. \n%\n% 11/17/02, J. Nagy\n% This was designed for image processing problems, where\n% it is common to use lexicographical (row) ordering.\n% But @kronMatrix functions where designed using vec (column)\n% ordering. This inconsistency has been fixed.\n \nP1 = K.psf;\nP2 = P1.image;\nPSF = P2{1};\nc1 = P1.center;\ncenter = c1{1};\n\n[mp, np] = size(PSF);\n\nif ( mp ~= np )\n error('For now, we expect PSF to be square')\nend\n\n%\n% Compute weighted PSF.\n%\nfor i = 1:center(1)\n Aweights(i,1) = sqrt( i+mp-center(1) );\nend;\nfor i = center(1)+1:mp\n Aweights(i,1) = sqrt( mp+center(1)-i);\nend;\nfor i = 1:center(2)\n Bweights(i,1) = sqrt( i+np-center(2) );\nend;\nfor i = center(2)+1:np\n Bweights(i,1) = sqrt( np+center(2)-i );\nend;\n\nPhat = (Aweights*Bweights').*PSF;\n%\n% Compute SVD of weighted PSF, which is then used to construct\n% the separable approximation.\n%\n[U,S,V] = svd( Phat );\n\n%\n% check to make sure first column looks like\n% a Gaussian, and is not inverted.\n%\nminU = abs(min(min(U(:,1))));\nmaxU = max(max(abs(U(:,1))));\nif minU == maxU\n U = -U;\n V = -V;\nend\n\n%\n% Construct approximation.\n%\na = ( U(:,1) * sqrt(S(1,1)) ) ./ Aweights;\nb = ( V(:,1) * sqrt(S(1,1)) ) ./ Bweights;\n\n%\n% This construction corresponds to lexicographical ordering,\n% but kronMatrix does everything corresponding to vec ordering.\n% Thus, these two do not work together.\n%%\n%%A = build_toep(a, center(1), n);\n%%B = build_toep(b, center(2), m);\n\n% To fix this, we just need to switch A and B. Then kronMatrix\n% can continue to be used corresponding to a vec ordering.\n%\nA = build_toep(b, center(2), m);\nB = build_toep(a, center(1), 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/oldZeroKronApprox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7882221349422501}} {"text": "function [ v1, v2, v3, v4 ] = tetrahedron_ref ( )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_REF returns the vertices of the reference tetrahedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 July 2014\n%\n% Author:\n%\n% John Burkardt.\n%\n% Reference:\n%\n% 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% Output, real V1(3), V2(3), V3(3), V4(3), the vertices.\n%\n v1(1) = - 1.0;\n v1(2) = - 1.0 / sqrt ( 3.0 );\n v1(3) = - 1.0 / sqrt ( 6.0 );\n\n v2(1) = 0.0;\n v2(2) = 2.0 / sqrt ( 3.0 );\n v2(3) = - 1.0 / sqrt ( 6.0 );\n\n v3(1) = 1.0;\n v3(2) = - 1.0 / sqrt ( 3.0 );\n v3(3) = - 1.0 / sqrt ( 6.0 );\n\n v4(1) = 0.0;\n v4(2) = 0.0;\n v4(3) = 3.0 / sqrt ( 6.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/tetrahedron_arbq_rule/tetrahedron_ref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7881949155888445}} {"text": "function pdf = beta_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% BETA_PDF evaluates the Beta PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B) = X**(A-1) * (1-X)**(B-1) / BETA(A,B).\n%\n% A = B = 1 yields the Uniform distribution on [0,1].\n% A = B = 1/2 yields the Arcsin distribution.\n% B = 1 yields the power function distribution.\n% A = B -> Infinity tends to the Normal distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n% 0.0 <= X <= 1.0.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < A,\n% 0.0 < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0.0 | 1.0 < x )\n pdf = 0.0;\n else\n pdf = x^( a - 1.0 ) * ( 1.0 - x )^( b - 1.0 ) / beta ( a, b );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/beta_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7881949140570776}} {"text": "%% A script to generate copy'able functions for quad-curl problem\n% used in \"Error analysis of a decoupled finite element method for quad-curl problems\"\n% https://arxiv.org/abs/2102.03396\n% \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear; clc;\nsyms x y z\n% U = [sin(y), -sin(z), sin(x)];\n% U = [0, 0, (sin(x))^2*(sin(y))^2*sin(z)];\nU = [0, 0, (sin(x)).^3.*(sin(y)).^3.*(sin(z)).^2];\n% U = [0, 0, x^2*(1-x)^2*y^2*(1-y)^2*z^2*(1-z)^2];\n\nX = [x y z];\n\n%%\ncurlu = curl(U,X);\ncurlcurlu = curl(curlu,X);\ntricurlu = curl(curlcurlu,X);\nquadcurlu = curl(tricurlu,X);\npentacurlu = curl(quadcurlu,X);\nhexacurlu = curl(pentacurlu,X);\n\nvectorsStr = {'curlu', 'curlcurlu', 'tricurlu', ...\n 'quadcurlu', 'pentacurlu', 'hexacurlu'};\n\n%%\nfor idx = 1:length(vectorsStr)\n vector = eval(vectorsStr{idx});\n fprintf(\"function s = %s(p)\\n\",vectorsStr{idx})\n fprintf(\"x = p(:,1); y = p(:,2); z = p(:,3);\\n\")\n for j = 1:3\n vStr = char(vector(j));\n vStr = strrep(vStr, '*', '.*');\n vStr = strrep(vStr, '^', '.^');\n fprintf(\"s(:,%d) = %s;\\n\", j, vStr)\n end\n fprintf('end\\n\\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/quadCurl/quadCurlexactu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7881887306146873}} {"text": "function [costs,paths] = dijkstra(AorV,xyCorE,SID,FID,iswaitbar)\n%DIJKSTRA Calculate Minimum Costs and Paths using Dijkstra's Algorithm\n%\n% Inputs:\n% [AorV] Either A or V where\n% A is a NxN adjacency matrix, where A(I,J) is nonzero (=1)\n% if and only if an edge connects point I to point J\n% NOTE: Works for both symmetric and asymmetric A\n% V is a Nx2 (or Nx3) matrix of x,y,(z) coordinates\n% [xyCorE] Either xy or C or E (or E3) where\n% xy is a Nx2 (or Nx3) matrix of x,y,(z) coordinates (equivalent to V)\n% NOTE: only valid with A as the first input\n% C is a NxN cost (perhaps distance) matrix, where C(I,J) contains\n% the value of the cost to move from point I to point J\n% NOTE: only valid with A as the first input\n% E is a Px2 matrix containing a list of edge connections\n% NOTE: only valid with V as the first input\n% E3 is a Px3 matrix containing a list of edge connections in the\n% first two columns and edge weights in the third column\n% NOTE: only valid with V as the first input\n% [SID] (optional) 1xL vector of starting points\n% if unspecified, the algorithm will calculate the minimal path from\n% all N points to the finish point(s) (automatically sets SID = 1:N)\n% [FID] (optional) 1xM vector of finish points\n% if unspecified, the algorithm will calculate the minimal path from\n% the starting point(s) to all N points (automatically sets FID = 1:N)\n% [iswaitbar] (optional) a scalar logical that initializes a waitbar if nonzero \n%\n% Outputs:\n% [costs] is an LxM matrix of minimum cost values for the minimal paths\n% [paths] is an LxM cell array containing the shortest path arrays\n%\n% Revision Notes:\n% (4/29/09) Previously, this code ignored edges that have a cost of zero,\n% potentially producing an incorrect result when such a condition exists.\n% I have solved this issue by using NaNs in the table rather than a\n% sparse matrix of zeros. However, storing all of the NaNs requires more\n% memory than a sparse matrix. This may be an issue for massive data\n% sets, but only if there are one or more 0-cost edges, because a sparse\n% matrix is still used if all of the costs are positive.\n%\n% Note:\n% If the inputs are [A,xy] or [V,E], the cost is assumed to be (and is\n% calculated as) the point-to-point Euclidean distance\n% If the inputs are [A,C] or [V,E3], the cost is obtained from either\n% the C matrix or from the edge weights in the 3rd column of E3\n%\n% Example:\n% % Calculate the (all pairs) shortest distances and paths using [A,xy] inputs\n% n = 7; A = zeros(n); xy = 10*rand(n,2)\n% tri = delaunay(xy(:,1),xy(:,2));\n% I = tri(:); J = tri(:,[2 3 1]); J = J(:);\n% IJ = I + n*(J-1); A(IJ) = 1\n% [costs,paths] = dijkstra(A,xy)\n%\n% Example:\n% % Calculate the (all pairs) shortest distances and paths using [A,C] inputs\n% n = 7; A = zeros(n); xy = 10*rand(n,2)\n% tri = delaunay(xy(:,1),xy(:,2));\n% I = tri(:); J = tri(:,[2 3 1]); J = J(:);\n% IJ = I + n*(J-1); A(IJ) = 1\n% a = (1:n); b = a(ones(n,1),:);\n% C = round(reshape(sqrt(sum((xy(b,:) - xy(b',:)).^2,2)),n,n))\n% [costs,paths] = dijkstra(A,C)\n%\n% Example:\n% % Calculate the (all pairs) shortest distances and paths using [V,E] inputs\n% n = 7; V = 10*rand(n,2)\n% I = delaunay(V(:,1),V(:,2));\n% J = I(:,[2 3 1]); E = [I(:) J(:)]\n% [costs,paths] = dijkstra(V,E)\n%\n% Example:\n% % Calculate the (all pairs) shortest distances and paths using [V,E3] inputs\n% n = 7; V = 10*rand(n,2)\n% I = delaunay(V(:,1),V(:,2));\n% J = I(:,[2 3 1]);\n% D = sqrt(sum((V(I(:),:) - V(J(:),:)).^2,2));\n% E3 = [I(:) J(:) D]\n% [costs,paths] = dijkstra(V,E3)\n%\n% Example:\n% % Calculate the shortest distances and paths from the 3rd point to all the rest\n% n = 7; V = 10*rand(n,2)\n% I = delaunay(V(:,1),V(:,2));\n% J = I(:,[2 3 1]); E = [I(:) J(:)]\n% [costs,paths] = dijkstra(V,E,3)\n%\n% Example:\n% % Calculate the shortest distances and paths from all points to the 2nd\n% n = 7; A = zeros(n); xy = 10*rand(n,2)\n% tri = delaunay(xy(:,1),xy(:,2));\n% I = tri(:); J = tri(:,[2 3 1]); J = J(:);\n% IJ = I + n*(J-1); A(IJ) = 1\n% [costs,paths] = dijkstra(A,xy,1:n,2)\n%\n% Example:\n% % Calculate the shortest distance and path from points [1 3 4] to [2 3 5 7]\n% n = 7; V = 10*rand(n,2)\n% I = delaunay(V(:,1),V(:,2));\n% J = I(:,[2 3 1]); E = [I(:) J(:)]\n% [costs,paths] = dijkstra(V,E,[1 3 4],[2 3 5 7])\n%\n% Example:\n% % Calculate the shortest distance and path between two points\n% n = 1000; A = zeros(n); xy = 10*rand(n,2);\n% tri = delaunay(xy(:,1),xy(:,2));\n% I = tri(:); J = tri(:,[2 3 1]); J = J(:);\n% D = sqrt(sum((xy(I,:)-xy(J,:)).^2,2));\n% I(D > 0.75,:) = []; J(D > 0.75,:) = [];\n% IJ = I + n*(J-1); A(IJ) = 1;\n% [cost,path] = dijkstra(A,xy,1,n)\n% gplot(A,xy,'k.:'); hold on;\n% plot(xy(path,1),xy(path,2),'ro-','LineWidth',2); hold off\n% title(sprintf('Distance from 1 to 1000 = %1.3f',cost))\n%\n% Web Resources:\n% Dijkstra's Algorithm\n% Graphs\n% Adjacency Matrix\n%\n% See also: gplot, gplotd, gplotdc, distmat, ve2axy, axy2ve\n%\n% Author: Joseph Kirk\n% Email: jdkirk630@gmail.com\n% Release: 1.1\n% Date: 4/29/09\n\n% Process Inputs\nerror(nargchk(2,5,nargin));\nall_positive = 1;\n[n,nc] = size(AorV);\n[m,mc] = size(xyCorE);\n[E,cost] = processInputs(AorV,xyCorE);\nif nargin < 5\n iswaitbar = 0;\nend\nif nargin < 4\n FID = (1:n);\nend\nif nargin < 3\n SID = (1:n);\nend\nif max(SID) > n || min(SID) < 1\n eval(['help ' mfilename]);\n error('Invalid [SID] input. See help notes above.');\nend\nif max(FID) > n || min(FID) < 1\n eval(['help ' mfilename]);\n error('Invalid [FID] input. See help notes above.');\nend\n\nisreversed = 0;\nif length(FID) < length(SID)\n E = E(:,[2 1]);\n cost = cost';\n tmp = SID;\n SID = FID;\n FID = tmp;\n isreversed = 1;\nend\n\nL = length(SID);\nM = length(FID);\ncosts = zeros(L,M);\npaths = num2cell(nan(L,M));\n\n% Find the Minimum Costs and Paths using Dijkstra's Algorithm\nif iswaitbar, wbh = waitbar(0,'Please Wait ... '); end\nfor k = 1:L\n % Initializations\n if all_positive, TBL = sparse(1,n); else TBL = NaN(1,n); end\n min_cost = Inf(1,n);\n settled = zeros(1,n);\n path = num2cell(nan(1,n));\n I = SID(k);\n min_cost(I) = 0;\n TBL(I) = 0;\n settled(I) = 1;\n path(I) = {I};\n\n while any(~settled(FID))\n % Update the Table\n TAB = TBL;\n if all_positive, TBL(I) = 0; else TBL(I) = NaN; end\n nids = find(E(:,1) == I);\n % Calculate the Costs to the Neighbor Points and Record Paths\n for kk = 1:length(nids)\n J = E(nids(kk),2);\n if ~settled(J)\n c = cost(I,J);\n if all_positive, empty = ~TAB(J); else empty = isnan(TAB(J)); end\n if empty || (TAB(J) > (TAB(I) + c))\n TBL(J) = TAB(I) + c;\n if isreversed\n path{J} = [J path{I}];\n else\n path{J} = [path{I} J];\n end\n else\n TBL(J) = TAB(J);\n end\n end\n end\n \n if all_positive, K = find(TBL); else K = find(~isnan(TBL)); end\n % Find the Minimum Value in the Table\n N = find(TBL(K) == min(TBL(K)));\n if isempty(N)\n break\n else\n % Settle the Minimum Value\n I = K(N(1));\n min_cost(I) = TBL(I);\n settled(I) = 1;\n end\n end\n % Store Costs and Paths\n costs(k,:) = min_cost(FID);\n paths(k,:) = path(FID);\n if iswaitbar, waitbar(k/L,wbh); end\nend\nif iswaitbar, close(wbh); end\n\nif isreversed\n costs = costs';\n paths = paths';\nend\n\nif L == 1 && M == 1\n paths = paths{1};\nend\n\n% -------------------------------------------------------------------\n function [E,C] = processInputs(AorV,xyCorE)\n C = sparse(n,n);\n if n == nc\n if m == n\n if m == mc % Inputs: A,cost\n A = AorV;\n A = A - diag(diag(A));\n C = xyCorE;\n all_positive = all(C(logical(A)) > 0);\n E = a2e(A);\n else % Inputs: A,xy\n A = AorV;\n A = A - diag(diag(A));\n xy = xyCorE;\n E = a2e(A);\n D = ve2d(xy,E);\n all_positive = all(D > 0);\n for row = 1:length(D)\n C(E(row,1),E(row,2)) = D(row);\n end\n end\n else\n eval(['help ' mfilename]);\n error('Invalid [A,xy] or [A,cost] inputs. See help notes above.');\n end\n else\n if mc == 2 % Inputs: V,E\n V = AorV;\n E = xyCorE;\n D = ve2d(V,E);\n all_positive = all(D > 0);\n for row = 1:m\n C(E(row,1),E(row,2)) = D(row);\n end\n elseif mc == 3 % Inputs: V,E3\n E3 = xyCorE;\n all_positive = all(E3 > 0);\n E = E3(:,1:2);\n for row = 1:m\n C(E3(row,1),E3(row,2)) = E3(row,3);\n end\n else\n eval(['help ' mfilename]);\n error('Invalid [V,E] inputs. See help notes above.');\n end\n end\n end\n\n % Convert Adjacency Matrix to Edge List\n function E = a2e(A)\n [I,J] = find(A);\n E = [I J];\n end\n\n % Compute Euclidean Distance for Edges\n function D = ve2d(V,E)\n VI = V(E(:,1),:);\n VJ = V(E(:,2),:);\n D = sqrt(sum((VI - VJ).^2,2));\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/20025-advanced-dijkstras-minimum-path-algorithm/dijkstra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.788188730201302}} {"text": "%\nfunction a = fitellipse(X,Y)\n\n% FITELLIPSE Least-squares fit of ellipse to 2D points.\n% A = FITELLIPSE(X,Y) returns the parameters of the best-fit\n% ellipse to 2D points (X,Y).\n% The returned vector A contains the center, radii, and orientation\n% of the ellipse, stored as (Cx, Cy, Rx, Ry, theta_radians)\n%\n% Authors: Andrew Fitzgibbon, Maurizio Pilu, Bob Fisher\n% Reference: \"Direct Least Squares Fitting of Ellipses\", IEEE T-PAMI, 1999\n%\n% @Article{Fitzgibbon99,\n% author = \"Fitzgibbon, A.~W.and Pilu, M. and Fisher, R.~B.\",\n% title = \"Direct least-squares fitting of ellipses\",\n% journal = pami,\n% year = 1999,\n% volume = 21,\n% number = 5,\n% month = may,\n% pages = \"476--480\"\n% }\n% \n% This is a more bulletproof version than that in the paper, incorporating\n% scaling to reduce roundoff error, correction of behaviour when the input \n% data are on a perfect hyperbola, and returns the geometric parameters\n% of the ellipse, rather than the coefficients of the quadratic form.\n%\n% Example: Run fitellipse without any arguments to get a demo\nif nargin == 0\n % Create an ellipse\n t = linspace(0,2);\n \n Rx = 300;\n Ry = 200;\n Cx = 250;\n Cy = 150;\n Rotation = .4; % Radians\n \n NoiseLevel = .5; % Will add Gaussian noise of this std.dev. to points\n \n x = Rx * cos(t);\n y = Ry * sin(t);\n nx = x*cos(Rotation)-y*sin(Rotation) + Cx + randn(size(t))*NoiseLevel; \n ny = x*sin(Rotation)+y*cos(Rotation) + Cy + randn(size(t))*NoiseLevel;\n \n % Clear figure\n clf\n % Draw it\n plot(nx,ny,'o');\n % Show the window\n figure(gcf)\n % Fit it\n params = fitellipse(nx,ny);\n % Note it may return (Rotation - pi/2) and swapped radii, this is fine.\n Given = round([Cx Cy Rx Ry Rotation*180]);\n Returned = round(params.*[1 1 1 1 180]);\n \n % Draw the returned ellipse\n t = linspace(0,pi*2);\n x = params(3) * cos(t);\n y = params(4) * sin(t);\n nx = x*cos(params(5))-y*sin(params(5)) + params(1); \n ny = x*sin(params(5))+y*cos(params(5)) + params(2);\n hold on\n plot(nx,ny,'r-')\n \n return\nend\n\n% normalize data\nmx = mean(X);\nmy = mean(Y);\nsx = (max(X)-min(X))/2;\nsy = (max(Y)-min(Y))/2; \n\nx = (X-mx)/sx;\ny = (Y-my)/sy;\n\n% Force to column vectors\nx = x(:);\ny = y(:);\n\n% Build design matrix\nD = [ x.*x x.*y y.*y x y ones(size(x)) ];\n\n% Build scatter matrix\nS = D'*D;\n\n% Build 6x6 constraint matrix\nC(6,6) = 0; C(1,3) = -2; C(2,2) = 1; C(3,1) = -2;\n\n% Solve eigensystem\nif 0\n % Old way, numerically unstable if not implemented in matlab\n [gevec, geval] = eig(S,C);\n\n % Find the negative eigenvalue\n I = find(real(diag(geval)) < 1e-8 & ~isinf(diag(geval)));\n \n % Extract eigenvector corresponding to negative eigenvalue\n A = real(gevec(:,I));\nelse\n % New way, numerically stabler in C [gevec, geval] = eig(S,C);\n \n % Break into blocks\n tmpA = S(1:3,1:3); \n tmpB = S(1:3,4:6); \n tmpC = S(4:6,4:6); \n tmpD = C(1:3,1:3);\n tmpE = inv(tmpC)*tmpB';\n \n % Return if tmpE contains nan\n if sum(sum(isnan(tmpE))) ~= 0\n a = [];\n return;\n end\n [evec_x, eval_x] = eig(inv(tmpD) * (tmpA - tmpB*tmpE));\n \n % Find the positive (as det(tmpD) < 0) eigenvalue\n I = find(real(diag(eval_x)) < 1e-8 & ~isinf(diag(eval_x)));\n \n % Extract eigenvector corresponding to negative eigenvalue\n A = real(evec_x(:,I));\n \n % Recover the bottom half...\n evec_y = -tmpE * A;\n A = [A; evec_y];\nend\n\n% unnormalize\npar = [\n A(1)*sy*sy, ...\n A(2)*sx*sy, ...\n A(3)*sx*sx, ...\n -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ...\n -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ...\n A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ...\n - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ...\n + A(6)*sx*sx*sy*sy ...\n ]';\n\n% Convert to geometric radii, and centers\n\nthetarad = 0.5*atan2(par(2),par(1) - par(3));\ncost = cos(thetarad);\nsint = sin(thetarad);\nsin_squared = sint.*sint;\ncos_squared = cost.*cost;\ncos_sin = sint .* cost;\n\nAo = par(6);\nAu = par(4) .* cost + par(5) .* sint;\nAv = - par(4) .* sint + par(5) .* cost;\nAuu = par(1) .* cos_squared + par(3) .* sin_squared + par(2) .* cos_sin;\nAvv = par(1) .* sin_squared + par(3) .* cos_squared - par(2) .* cos_sin;\n\n% ROTATED = [Ao Au Av Auu Avv]\n\ntuCentre = - Au./(2.*Auu);\ntvCentre = - Av./(2.*Avv);\nwCentre = Ao - Auu.*tuCentre.*tuCentre - Avv.*tvCentre.*tvCentre;\n\nuCentre = tuCentre .* cost - tvCentre .* sint;\nvCentre = tuCentre .* sint + tvCentre .* cost;\n\nRu = -wCentre./Auu;\nRv = -wCentre./Avv;\n\nRu = sqrt(abs(Ru)).*sign(Ru);\nRv = sqrt(abs(Rv)).*sign(Rv);\n\na = [uCentre, vCentre, Ru, Rv, thetarad];", "meta": {"author": "harishrithish7", "repo": "Fall-Detection", "sha": "a7f7d59cd2220aed3cb110ed075523fcfd8a1c9c", "save_path": "github-repos/MATLAB/harishrithish7-Fall-Detection", "path": "github-repos/MATLAB/harishrithish7-Fall-Detection/Fall-Detection-a7f7d59cd2220aed3cb110ed075523fcfd8a1c9c/fitellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.788188728756941}} {"text": "function f = bohach1 ( m, x )\n\n%*****************************************************************************80\n%\n%% BOHACH1 evaluates the Bohachevsky function #1.\n%\n% Discussion:\n%\n% The minimizer is\n%\n% X* = [ 0.0, 0.0 ]\n% F(X*) = 0.0\n%\n% Suggested starting point:\n%\n% X = [ 0.5, 1.0 ];\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, integer M, the number of variables.\n%\n% Input, real X(M), the argument of the function.\n%\n% Output, real F, the value of the function at X.\n%\n f = x(1) * x(1) - 0.3 * cos ( 3.0 * pi * x(1) ) ...\n + 2.0 * x(2) * x(2) - 0.4 * cos ( 4.0 * pi * x(2) ) ...\n + 0.7;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/compass_search/bohach1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7881887276213755}} {"text": "function b = Theil_Sen_Regress(x,y)\n\n[N c]=size(x);\n\n\nComb = combnk(1:N,2);\ndeltay=diff(y(Comb),1,2);\ndeltax=diff(x(Comb),1,2);\n\n\n\ntheil=diff(y(Comb),1,2)./diff(x(Comb),1,2);\nb=median(theil);\n\n\n\n\n\n\n%% Example code below !!\n\n% % % x = (-15:25)';\n% % % y =2*x + normrnd(0,3,41,1);\n% % % y([38 40 41]) = 0;\n% % % y([1 3])=20;\n% % % \n% % % bls = regress(y,[ones(41,1) x]);\n% % % [N c]=size(x);\n% % % Comb = combnk(1:N,2);\n% % % deltay=diff(y(Comb),1,2);\n% % % deltax=diff(x(Comb),1,2);\n% % % theil=diff(y(Comb),1,2)./diff(x(Comb),1,2);\n% % % b=median(theil);\n% % % \n% % % scatter(x,y,'filled'); grid on; hold on\n% % % plot(x,bls(1)+bls(2)*x,'r','LineWidth',2);\n% % % plot(x,b*x,'g','LineWidth',3);\n% % % plot(x,2*x,'k','LineWidth',2);\n% % % legend('Data','Ordinary Least Squares','Theil-Senn Estimator','Real 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/34308-theilsen-estimator/Theil_Sen_Regress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7881702316989705}} {"text": "function p_sign = perm_sign ( n, p )\n\n%*****************************************************************************80\n%\n%% PERM_SIGN returns the sign of a permutation.\n%\n% Discussion:\n%\n% A permutation can always be replaced by a sequence of pairwise\n% transpositions. A given permutation can be represented by\n% many different such transposition sequences, but the number of\n% such transpositions will always be odd or always be even.\n% If the number of transpositions is even or odd, the permutation is\n% said to be even or odd.\n%\n% Example:\n%\n% Input:\n%\n% N = 9\n% P = 2, 3, 9, 6, 7, 8, 5, 4, 1\n%\n% Output:\n%\n% P_SIGN = +1\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% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, the number of objects permuted.\n%\n% Input, integer P(N), a permutation, in standard index form.\n%\n% Output, integer P_SIGN, the \"sign\" of the permutation.\n% +1, the permutation is even,\n% -1, the permutation is odd.\n%\n ierror = perm_check ( n, p );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PERM_SIGN - Fatal error!\\n' );\n fprintf ( 1, ' The input array does not represent\\n' );\n fprintf ( 1, ' a proper permutation. In particular, the\\n' );\n fprintf ( 1, ' array is missing the value %d\\n', ierror );\n error ( 'PERM_SIGN - Fatal error!' );\n end\n%\n% Make a temporary copy of the permutation.\n%\n q(1:n) = p(1:n);\n%\n% Start with P_SIGN indicating an even permutation.\n% Restore each element of the permutation to its correct position,\n% updating P_SIGN as you go.\n%\n p_sign = 1;\n\n for i = 1 : n - 1\n\n j = i4vec_index ( n, q, i );\n\n if ( j ~= i )\n temp = q(i);\n q(i) = q(j);\n q(j) = temp;\n p_sign = - p_sign;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/perm_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7881279305927952}} {"text": "function [fx,dF_dX,dF_dTheta] = f_Henon(Xt,Theta,ut,inF)\n% Henon chaotic map evolution function\n\nx = Xt;\na = Theta(1);\nb = Theta(2);\n\nfx = zeros(2,1);\nfx(1) = x(2) + 1 -a.*x(1).^2;\nfx(2) = b.*x(1);\n\nJ = zeros(2,2);\nJ(1,:) = [-2.*a*x(1),1];\nJ(2,:) = [b,0];\ndF_dX = J';\n\ndF_dTheta = zeros(2,2);\ndF_dTheta(1,:) = [-x(1).^2,0];\ndF_dTheta(2,:) = [0,x(1)];\ndF_dTheta = dF_dTheta';\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_Henon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013549, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7880837268993934}} {"text": "function a = lietzke_inverse ( n )\n\n%*****************************************************************************80\n%\n%% LIETZKE_INVERSE returns the inverse of the LIETZKE matrix.\n%\n% Example:\n%\n% N = 5\n%\n% 0.5833 -0.5000 0 0 0.0833\n% -0.5000 1.0000 -0.5000 0 0\n% 0 -0.5000 1.0000 -0.5000 0\n% 0 0 -0.5000 1.0000 -0.5000\n% 0.0833 0 0 -0.5000 0.5833\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of rows and columns \n% of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n a(1,1) = ( n + 2 ) / ( 2 * n + 2 );\n for i = 2 : n - 1\n a(i,i) = 1.0;\n end\n a(n,n) = ( n + 2 ) / ( 2 * n + 2 );\n\n if ( n == 2 )\n\n for i = 1 : n - 1\n a(i,i+1) = - 1.0 / 3.0;\n end\n\n for i = 2 : n\n a(i,i-1) = - 1.0 / 3.0;\n end\n\n else\n\n for i = 1 : n - 1\n a(i,i+1) = - 0.5;\n end\n\n for i = 2 : n\n a(i,i-1) = - 0.5;\n end\n\n end\n\n a(1,n) = 1.0 / ( 2 * n + 2 );\n a(n,1) = 1.0 / ( 2 * 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/test_mat/lietzke_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7880589108861166}} {"text": "function u = dirichlet_condition ( node_num, node_xy, time )\n\n%*****************************************************************************80\n%\n%% DIRICHLET_CONDITION sets the value of a Dirichlet boundary condition.\n%\n% Discussion:\n%\n% For efficiency, this routine may be called once, with all the\n% nodes input. Of course, only those nodes that lie on the boundary\n% will need a meaningful value of U to be assigned. Other nodes\n% may be given a dummy value for U.\n%\n% This routine is set for the unit square.\n%\n% We assume that the equation to be solved is\n%\n% dUdT - Laplacian U + K * U = F\n%\n% with \n%\n% K(X,Y,T) = 0\n% F(X,Y,T) = (2*pi*pi-1)*sin(pi*x)*sin(pi*y)*exp(-t).\n%\n% The exact solution is:\n%\n% U = sin(pi*x) * sin(pi*y) * exp(-t)\n%\n% Modified:\n%\n% 07 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the coordinates of the points.\n%\n% Input, real TIME, the current time.\n%\n% Output, real U(NODE_NUM), the value of the solution at the\n% the points.\n%\n u(1:node_num) = sin ( pi * node_xy(1,1:node_num) ) ...\n .* sin ( pi * node_xy(2,1:node_num) ) * exp ( - time );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_heat_sparse_square/dirichlet_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7880589042827544}} {"text": "% Filename: givepd.m\n% Author: Shashank G. Sawant\n% email: sgsawant@gmail.com\n% Description: Given 2 sinusoidal signals of the \n% same frequency, the function gives the \"phase difference\" between the \n% 2 given signals \n% The phase difference is in RADIANS!!!!!!\n% The output is limited to pd={-pi,pi}radians\n% Time Stamp: 2010 October 19 2043hrs\n\n\n% pd - output phase difference (in radians)\n% v - first sinusoidal signal\n% i - second sinusoidal signal\n% Note: v and i should have the same frequency\nfunction pd=givepd(v,i)\nL=length(v);\nif(L~=length(i))\n error('The length of the 2 sinusoidal input vectors is not same!!!');\nend\n\n% The following block calculates the FFT\nNFFT = 2^nextpow2(L);\nV = fft(v,NFFT)/L; %Fourier Transform of signal v\n\n% The following block calculates the phase of the most significant \n% frequency component\n[value,index]=max(2*abs(V(1:NFFT/2+1)));\npV = angle(V(index));\n\n% The following block calculates the FFT\nNFFT = 2^nextpow2(L);\nI = fft(i,NFFT)/L; %Fourier Transform of signal i\n\n% The following block calculates the phase of the most significant \n% frequency component\n[value,index]=max(2*abs(I(1:NFFT/2+1)));\npI = angle(I(index));\n\n% The following is the phase difference between the 2 signals\npd=pV-pI;\n\n% The code below limits the output to pd={-pi,pi}radians\nwhile 1\n if pd>pi\n pd=pd-2*pi;\n elseif pd<-pi\n pd=pd+2*pi;\n else\n break;\n end\nend\n\nreturn;\nend\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/29075-find-phase-difference-between-2-sinusoidal-signals/givepd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7880589005620895}} {"text": "function y = tanh(x)\nexp_term = exp(x);\nexp_term2 = exp(-x);\ny = (exp_term - exp_term2) ./ (exp_term + exp_term2);\n\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/graph/tanh_back.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545304202038, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7880520502198568}} {"text": "clear;\nclc;\n% This program solves the economic emission dispatch dispatch with Bmn coefficients by\n% quadratic programming and equal incremental cost critetion\n% the elddata matrix should have 5 columns of fuel cost coefficients and plant limits.\n% 1.a ($/MW^2) 2. b $/MW 3. c ($) 4.lower lomit(MW) 5.Upper limit(MW)\n%no of rows denote the no of plants(n)\nelddata=[0.15247\t38.53973\t756.79886\t10\t125\n0.10587\t46.15916\t451.32513\t10\t150\n0.02803\t40.3965\t1049.9977\t35\t225\n0.03546\t38.30553\t1243.5311\t35\t210\n0.02111\t36.32782\t1658.5596\t130\t325\n0.01799\t38.27041\t1356.6592\t125\t315\n];\n% the emidata matrix should have 3 columns of fuel cost coefficients and plant limits.\n% 1.a (Kg/MW^2) 2. b Kg/MW 3. c (Kg)\n\nemidata=[0.00419\t0.32767\t13.85932\n0.00419\t0.32767\t13.85932\n0.00683\t-0.54551\t40.2669\n0.00683\t-0.54551\t40.2669\n0.00461\t-0.51116\t42.89553\n0.00461\t-0.51116\t42.8955];\n% h1 1nd h2 are is the weightage factor for economy and emission\nh1=1; h2=44.788;\n% Demand (MW)\nPd=700;\n% Loss coefficients it should be squarematrix of size nXn where n is the no\n% of plants\nB=1e-4*[1.4\t.17\t.15\t.19\t.26\t.22\n.17\t.6\t.13\t.16\t.15\t.2\n.15\t.13\t.65\t.17\t.24\t.19\n.19\t.16\t.17\t.71\t.3\t.25\n.26\t.15\t.24\t.3\t.69\t.32\n.22\t.2\t.19\t.25\t.32\t.85];\n[P Fcost Emi Pl]=emield(elddata,emidata,h1,h2,B,Pd)\n ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19546-economic-emission-dispatch/emission/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7880242744040622}} {"text": "function sphere = createSphere(varargin)\n%CREATESPHERE Create a sphere containing 4 points\n%\n% s = createSphere(p1, p2, p3, p4);\n% return in s the sphere common to the 4 pointsp1, p2, p3 and p4.\n%\n% Ref: P. Bourke\n% http://astronomy.swin.edu.au/~pbourke/geometry/spherefrom4/\n%\n% See also\n% spheres, circles3d\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 22/03/2005.\n%\n\n\nif length(varargin)==4\n pts = [varargin{1};varargin{2};varargin{3};varargin{4}];\nelseif length(varargin)==1\n pts = varargin{1};\nelse\n error('wrong number of arguments in createSphere');\nend\n\n\nm1 = det([pts ones(4,1)]);\ns2 = sum(pts.*pts, 2);\nm2 = det([s2 pts(:,2) pts(:,3) ones(4,1)]);\nm3 = det([pts(:,1) s2 pts(:,3) ones(4,1)]);\nm4 = det([pts(:,1) pts(:,2) s2 ones(4,1)]);\n\nm5 = det([s2 pts]);\n\nx0 = m2*.5/m1;\ny0 = m3*.5/m1;\nz0 = m4*.5/m1;\nr = sqrt(x0*x0 + y0*y0 + z0*z0 - m5/m1);\n\nsphere = [x0 y0 z0 r];\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/createSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7880242742460305}} {"text": "function a = biw ( n )\n\n%*****************************************************************************80\n%\n%% BIW returns the BIW matrix.\n%\n% Discussion:\n%\n% BIW is a bidiagonal matrix of Wilkinson. Originally, this matrix\n% was considered for N = 100.\n%\n% Formula:\n%\n% if ( I == J )\n% A(I,J) = 0.5 + I / ( 10 * N )\n% else if ( J == I+1 )\n% A(I,J) = -1.0\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% N = 5\n%\n% 0.52 -1.00 0.00 0.00 0.00\n% 0.00 0.54 -1.00 0.00 0.00\n% 0.00 0.00 0.56 -1.00 0.00\n% 0.00 0.00 0.00 0.58 -1.00\n% 0.00 0.00 0.00 0.00 0.60\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% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n a(i,i) = 0.5 + i / ( 10 * n );\n end\n\n for i = 1 : n - 1\n a(i,i+1) = - 1.0;\n end\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/biw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.7879863312790498}} {"text": "function [t, u] = swept_sine(f,cyc,res,plt)\n% generate a swept sine curve\n% function [t, u] = swept_sine(f,cyc,res,plt)\n%\n% inputs 4 - 3 optional\n% f frequency interval ([low high] (Hz) class real\n% cyc number of cycles to cover (total) class real - optional\n% res number of points per cycle (resolution) class integer - optional\n% plt plot function (0 / 1) class integer - optional\n%\n% outputs 2\n% t time increment vector (non-linear) class real\n% u steering input content class real\n%\n% michael arant - Aug 7, 2009\n%\n% ex\n%\t[t u] = swept_sine([.1 5],25,25,1,0)\n\nif nargin < 1; help swept_sine; error('Need inputs'); end\nif ~exist('cyc','var'); cyc = ceil((f(2) / f(1)) / 5); end\nif ~exist('res','var'); res = 50; end\nif ~exist('plt','var'); plt = 0; end\n\n% define sine cycles\na = linspace(0,pi*cyc*2,res*cyc)';\n% generate sine\nu = sin(a);\n\n% time step vector (time between points)\nti = linspace(1/(res * f(1)),1/(res * f(2)),res*cyc)';\n% time vector (point location in time) - scale by number of points and cycles\nt = (cumsum(ti) - ti(1)) * cyc / res;\n\n% proof of linear time reduction\n% diff(diff(t(1:res:end)))\n\n% debug plot\nif plt\n\tfigure; set(gcf,'color','w'); plot(u); grid on;\n\ttitle('Steering Input'); ylabel('Amplitude (deg)'); xlabel('Increment')\n\tfigure; set(gcf,'color','w'); plot(t,u); grid on;\n\ttitle('Steering Input'); ylabel('Amplitude (deg)'); xlabel('Time (s)')\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/24987-sweptsine/swept_sine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7879636652148957}} {"text": "function a = lehmer ( n )\n\n%*****************************************************************************80\n%\n%% LEHMER returns the Lehmer matrix.\n%\n% Discussion:\n%\n% The Lehmer matrix is a symmetric positive definite N by N \n% matrix with\n%\n% A(i,j) = min ( i, j ) / max ( i, j ) \n%\n% A is totally nonnegative. The inverse of A is tridiagonal, \n% and explicit formulas are known for its entries.\n%\n% The condition number of A satisfies the bounds:\n%\n% N <= condition ( A ) <= 4*N*N.\n%\n% Reference:\n%\n% M. Newman and J. Todd, \n% The evaluation of matrix inversion programs, \n% Journal of the Society for Industrial and Applied Mathematics, \n% Volume 6, 1958, pages 466-476.\n%\n% Solutions to problem E710 (proposed by D H Lehmer): \n% The inverse of a matrix, \n% American Mathematical Monthly, \n% Volume 53, 1946, pages 534-535.\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 = ones ( n, 1 ) * ( 1:n );\n a = a ./ a';\n a = tril ( a ) + tril ( a, -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/templates/lehmer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.787963663007213}} {"text": "function order = level_to_order_open ( dim_num, level )\n\n%*****************************************************************************80\n%\n%% LEVEL_TO_ORDER converts a level to an order for open rules.\n%\n% Discussion:\n%\n% Sparse grids can naturally be nested. A natural scheme is to use\n% a series of one-dimensional rules arranged in a series of \"levels\"\n% whose order roughly doubles with each step.\n%\n% The arrangement described here works naturally for the Fejer Type 1,\n% Fejer Type 2, Newton Cotes Open, Newton Cotes Half Open,\n% and Gauss-Patterson rules. It also can be used, partially, to describe\n% the growth of Gauss-Legendre rules.\n%\n% The idea is that we start with LEVEL = 0, ORDER = 1 indicating the single \n% point at the center, and for all values afterwards, we use the relationship\n%\n% ORDER = 2**(LEVEL+1) - 1.\n%\n% The following table shows how the growth will occur:\n%\n% Level Order\n%\n% 0 1\n% 1 3 = 4 - 1\n% 2 7 = 8 - 1\n% 3 15 = 16 - 1\n% 4 31 = 32 - 1\n% 5 63 = 64 - 1\n%\n% For the Fejer Type 1, Fejer Type 2, Newton Cotes Open, \n% Newton Cotes Open Half, and Gauss-Patterson rules, the point growth is\n% nested. If we have ORDER points on a particular LEVEL, the next level \n% includes all these old points, plus ORDER+1 new points, formed in the \n% gaps between successive pairs of old points plus an extra point at each \n% end.\n%\n% Level Order = New + Old\n%\n% 0 1 = 1 + 0\n% 1 3 = 2 + 1\n% 2 7 = 4 + 3\n% 3 15 = 8 + 7\n% 4 31 = 16 + 15\n% 5 63 = 32 + 31\n%\n% If we use a series of Gauss-Legendre rules, then there is almost no \n% nesting, except that the central point is shared. If we insist on \n% producing a comparable series of such points, then the \"nesting\" behavior\n% is as follows:\n%\n% Level Order = New + Old\n%\n% 0 1 = 1 + 0\n% 1 3 = 2 + 1\n% 2 7 = 6 + 1\n% 3 15 = 14 + 1\n% 4 31 = 30 + 1\n% 5 63 = 62 + 1\n%\n% Moreover, if we consider ALL the points used in such a set of \"nested\" \n% Gauss-Legendre rules, then we must sum the \"NEW\" column, and we see that\n% we get roughly twice as many points as for the truly nested rules.\n%\n% In this routine, we assume that a vector of levels is given,\n% and the corresponding orders are desired.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 18 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL(DIM_NUM), the nesting level.\n%\n% Output, integer ORDER(DIM_NUM), the order (number of points) of the rule.\n%\n for dim = 1 : dim_num\n\n if ( level(dim) < 0 )\n order(dim) = -1;\n elseif ( level(dim) == 0 )\n order(dim) = 1;\n else\n order(dim) = 2^( level(dim) + 1 ) - 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_laguerre/level_to_order_open.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.78784306722582}} {"text": "function variance = arcsin_variance ( a )\n\n%*****************************************************************************80\n%\n%% ARCSIN_VARIANCE returns the variance of the Arcsin PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the parameter of the CDF.\n% A must be positive.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = a * a / 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/prob/arcsin_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7878430636420021}} {"text": "function b = poisson_rhs ( nrow, ncol, rhs_num )\n\n%*****************************************************************************80\n%\n%% POISSON_RHS returns the right hand side of a Poisson linear system.\n%\n% Discussion:\n%\n% The Poisson matrix is associated with an NROW by NCOL rectangular\n% grid of points.\n%\n% Assume that the points are numbered from left to right, bottom to top.\n%\n% If the K-th point is in row I and column J, set X = I + J.\n%\n% This will be the solution to the linear system.\n%\n% The right hand side is easily determined from X. It is 0 for every\n% interior point.\n%\n% Example:\n%\n% NROW = 3, NCOL = 3\n%\n% ^\n% | 7 8 9\n% J 4 5 6\n% | 1 2 3\n% |\n% +-----I---->\n%\n% Solution vector X = ( 2, 3, 4, 3, 4, 5, 4, 5, 6 )\n%\n% Right hand side B = ( 2, 2, 8, 2, 0, 6, 8, 6, 14 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub, Charles Van Loan,\n% Matrix Computations, second edition,\n% Johns Hopkins University Press, Baltimore, Maryland, 1989\n% (Section 4.5.4).\n%\n% Parameters:\n%\n% Input, integer NROW, NCOL, the number of rows and columns\n% in the grid.\n%\n% Input, integer RHS_NUM, the number of right hand sides.\n%\n% Output, real B(NROW*NCOL,RHS_NUM), the right hand side.\n%\n n = nrow * ncol;\n\n b = zeros ( n, rhs_num );\n\n k = 0;\n for j = 1 : nrow\n for i = 1 : ncol\n k = k + 1;\n b(k,1) = 0.0;\n if ( i == 1 )\n b(k,1) = b(k,1) + i + j - 1;\n end\n if ( j == 1 )\n b(k,1) = b(k,1) + i + j - 1;\n end\n if ( i == ncol )\n b(k,1) = b(k,1) + i + j + 1;\n end\n if ( j == nrow )\n b(k,1) = b(k,1) + i + j + 1;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/poisson_rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.7877067853561373}} {"text": "function a = stirling_inverse ( n )\n\n%*****************************************************************************80\n%\n%% STIRLING_INVERSE returns the inverse of the STIRLING matrix.\n%\n% Comments:\n%\n% The inverse of S1, the matrix of Stirling numbers of the first kind,\n% is S2, the matrix of Stirling numbers of the second kind.\n%\n% S2(I,J) represents the number of distinct partitions of I elements\n% into J nonempty sets. For any I, the sum over J of the Stirling\n% numbers S2(I,J) is represented by B(I), called \"Bell's number\",\n% and represents the number of distinct partitions of I elements.\n%\n% For example, with 4 objects, there are:\n%\n% 1 partition into 1 set:\n%\n% (A,B,C,D)\n%\n% 7 partitions into 2 sets:\n%\n% (A,B,C) (D)\n% (A,B,D) (C)\n% (A,C,D) (B)\n% (A) (B,C,D)\n% (A,B) (C,D)\n% (A,C) (B,D)\n% (A,D) (B,C)\n%\n% 6 partitions into 3 sets:\n%\n% (A,B) (C) (D)\n% (A) (B,C) (D)\n% (A) (B) (C,D)\n% (A,C) (B) (D)\n% (A,D) (B) (C)\n% (A) (B,D) (C)\n%\n% 1 partition into 4 sets:\n%\n% (A) (B) (C) (D)\n%\n% So S2(4,1) = 1, S2(4,2) = 7, S2(4,3) = 6, S2(4,4) = 1, and B(4) = 15.\n%\n%\n% First terms:\n%\n% I/J: 1 2 3 4 5 6 7 8\n%\n% 1 1 0 0 0 0 0 0 0\n% 2 1 1 0 0 0 0 0 0\n% 3 1 3 1 0 0 0 0 0\n% 4 1 7 6 1 0 0 0 0\n% 5 1 15 25 10 1 0 0 0\n% 6 1 31 90 65 15 1 0 0\n% 7 1 63 301 350 140 21 1 0\n% 8 1 127 966 1701 1050 266 28 1\n%\n% Recursion:\n%\n% S2(I,1) = 1 for all I.\n% S2(I,I) = 1 for all I.\n% S2(I,J) = 0 if I < J.\n%\n% S2(I,J) = J * S2(I-1,J) + S2(I-1,J-1)\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is lower triangular.\n%\n% A is nonnegative.\n%\n% det ( A ) = 1.\n%\n% A is unimodular.\n%\n% LAMBDA(1:N) = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n a(1,1) = 1.0;\n a(1,2:n) = 0.0;\n\n for i = 2 : n\n\n a(i,1) = 1.0;\n\n for j = 2 : n\n a(i,j) = j * a(i-1,j) + a(i-1,j-1);\n end\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/stirling_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7877067767414885}} {"text": "function value = r8_degrees ( radians )\n\n%*****************************************************************************80\n%\n%% R8_DEGREES converts an angle from radian to degree measure.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real RADIANS, the angle measurement in radians.\n%\n% Output, real VALUE, the angle measurement in degrees.\n%\n value = radians * 180.0 / pi;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_degrees.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.7875862923962424}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters. \n% You should set p to a vector of 0's and 1's\n%\n\nresult = sigmoid(X * theta);\np = round(result);\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "rieder91", "repo": "MachineLearning", "sha": "f6708f216326cb5c9e9e5c3afc912060bfa10486", "save_path": "github-repos/MATLAB/rieder91-MachineLearning", "path": "github-repos/MATLAB/rieder91-MachineLearning/MachineLearning-f6708f216326cb5c9e9e5c3afc912060bfa10486/Exercise 2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7875862726536107}} {"text": "function kf = gaussian_correlation(xf, yf, sigma)\n%GAUSSIAN_CORRELATION Gaussian Kernel at all shifts, i.e. kernel correlation.\n% Evaluates a Gaussian kernel with bandwidth SIGMA for all relative\n% shifts between input images X and Y, which must both be MxN. They must \n% also be periodic (ie., pre-processed with a cosine window). The result\n% is an MxN map of responses.\n%\n% Inputs and output are all in the Fourier domain.\n%\n% Joao F. Henriques, 2014\n% http://www.isr.uc.pt/~henriques/\n\t\n\tN = size(xf,1) * size(xf,2);\n\txx = xf(:)' * xf(:) / N; %squared norm of x\n\tyy = yf(:)' * yf(:) / N; %squared norm of y\n\t\n\t%cross-correlation term in Fourier domain\n\txyf = xf .* conj(yf);\n\txy = sum(real(ifft2(xyf)), 3); %to spatial domain\n\t\n\t%calculate gaussian response for all positions, then go back to the\n\t%Fourier domain\n\tkf = fft2(exp(-1 / sigma^2 * max(0, (xx + yy - 2 * xy) / numel(xf))));\n\nend\n\n", "meta": {"author": "thias15", "repo": "Context-Aware-CF-Tracking", "sha": "2b1198a24aea6420d28987f68622f50a2970ffac", "save_path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking", "path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking/Context-Aware-CF-Tracking-2b1198a24aea6420d28987f68622f50a2970ffac/SAMF_CA/gaussian_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7875850538167892}} {"text": "function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...\n num_features, lambda)\n%COFICOSTFUNC Collaborative filtering cost function\n% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...\n% num_features, lambda) returns the cost and gradient for the\n% collaborative filtering problem.\n%\n\n% Unfold the U and W matrices from params\nX = reshape(params(1:num_movies*num_features), num_movies, num_features);\nTheta = reshape(params(num_movies*num_features+1:end), ...\n num_users, num_features);\n\n \n% You need to return the following values correctly\nJ = 0;\nX_grad = zeros(size(X));\nTheta_grad = zeros(size(Theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost function and gradient for collaborative\n% filtering. Concretely, you should first implement the cost\n% function (without regularization) and make sure it is\n% matches our costs. After that, you should implement the \n% gradient and use the checkCostFunction routine to check\n% that the gradient is correct. Finally, you should implement\n% regularization.\n%\n% Notes: X - num_movies x num_features matrix of movie features\n% Theta - num_users x num_features matrix of user features\n% Y - num_movies x num_users matrix of user ratings of movies\n% R - num_movies x num_users matrix, where R(i, j) = 1 if the \n% i-th movie was rated by the j-th user\n%\n% You should set the following variables correctly:\n%\n% X_grad - num_movies x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of X\n% Theta_grad - num_users x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of Theta\n%\n\n% FIXME(SaveTheRbtz@): Not optical: preforms calculations on cells with R(i,j) == 0\nJ = sum(sum((R==1) .* ((X * Theta' - Y) .^ 2))) / 2;\n\nX_grad = (R==1) .* (X * Theta' - Y) * Theta + lambda * X;\nTheta_grad = (R==1)' .* (X * Theta' - Y)' * X + lambda * Theta;\n\nRegularization = lambda * (sum(sum(Theta .^ 2)) + sum(sum(X .^ 2))) / 2;\nJ += Regularization;\n\n% =============================================================\n\ngrad = [X_grad(:); Theta_grad(:)];\n\nend\n", "meta": {"author": "SaveTheRbtz", "repo": "ml-class", "sha": "74ce689e21e9f3ca184e60313351b31112e5dd56", "save_path": "github-repos/MATLAB/SaveTheRbtz-ml-class", "path": "github-repos/MATLAB/SaveTheRbtz-ml-class/ml-class-74ce689e21e9f3ca184e60313351b31112e5dd56/ex8/cofiCostFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7875462371440574}} {"text": "function result = rectangle_sub_2d ( func, xval, yval, nsub, norder, xtab, ...\n ytab, weight )\n\n%*****************************************************************************80\n%\n%% RECTANGLE_SUB_2D carries out a composite quadrature over a rectangle in 2D.\n%\n% Integration region:\n%\n% XVAL(1) <= X <= XVAL(2),\n% YVAL(1) <= Y <= YVAL(2).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the function to be\n% integrated. The user must declare the name an EXTERNAL\n% parameter in the calling program, pass the name of the\n% function in FUNC, and write a function of the form\n% function value = func ( x, y )\n% which evaluates the function at the point (X,Y).\n%\n% Input, real XVAL(2), the left and right X coordinates.\n%\n% Input, real YVAL(2), the lower and upper Y coordinates.\n%\n% Input, integer NSUB(2).\n% NSUB(1) is the number of subintervals to use in the X direction,\n% and NSUB(2) is the same thing for Y.\n%\n% Input, integer NORDER, the order of the rule.\n%\n% Input, real XTAB(NORDER), YTAB(NORDER), the abscissas.\n%\n% Input, real WEIGHT(NORDER), the weights of the rule.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n a(1) = xval(1);\n a(2) = yval(1);\n b(1) = xval(2);\n b(2) = yval(2);\n\n for i = 1 : 2\n if ( a(i) == b(i) )\n result = 0.0E+00;\n return\n end\n end\n\n for i = 1 : 2\n if ( nsub(i) < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RECTANGLE_SUB_2D - Fatal error!\\n' );\n fprintf ( 1, ' Nonpositive value of NSUB(I) = %d\\n', nsub(i) );\n fprintf ( 1, ' for index I = %d\\n', i );\n error ( 'RECTANGLE_SUB_2D - Fatal error!' );\n end\n end\n%\n% Break up the X interval into NSUB(1) subintervals.\n%\n volume = 0.0E+00;\n result = 0.0E+00;\n\n for i = 1 : nsub(1)\n\n xlo = r8vec_even_select ( a(1), b(1), nsub(1)+1, i );\n xhi = r8vec_even_select ( a(1), b(1), nsub(1)+1, i+1 );\n%\n% Break up the Y interval into NSUB(2) subintervals.\n%\n for j = 1 : nsub(2)\n\n ylo = r8vec_even_select ( a(2), b(2), nsub(2)+1, j );\n yhi = r8vec_even_select ( a(2), b(2), nsub(2)+1, j+1 );\n\n quad_sub = 0.0E+00;\n for k = 1 : norder\n\n x = xlo + 0.5E+00 * ( xtab(k) + 1.0E+00 ) * ( xhi - xlo );\n y = ylo + 0.5E+00 * ( ytab(k) + 1.0E+00 ) * ( yhi - ylo );\n\n quad_sub = quad_sub + weight(k) * feval ( func, x, y ) / 4.0E+00;\n\n end\n\n volume_sub = ( xhi - xlo ) * ( yhi - ylo );\n result_sub = quad_sub * volume_sub;\n\n volume = volume + volume_sub;\n result = result + result_sub;\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/rectangle_sub_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7875462292316511}} {"text": "function value = r8vec_norm_lp ( n, a, p )\n\n%*****************************************************************************80\n%\n%% R8VEC_NORM_LP returns the LP norm of an R8VEC.\n%\n% Discussion:\n%\n% The vector LP norm is defined as:\n%\n% value = ( sum ( 1 <= I <= N ) ( abs ( A(I) ) )^P )^(1/P).\n%\n% This routine allows P to have the special Matlab value Inf,\n% in which case the L-infinity norm is returned.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in A.\n%\n% Input, real A(N), the vector whose LP norm is desired.\n%\n% Input, real P, the index of the norm. \n%\n% Output, real VALUE, the LP norm of A.\n%\n if ( p <= 0.0 )\n value = -1.0;\n elseif ( p == Inf )\n value = maxval ( abs ( a(1:n) ) );\n elseif ( p == 1.0 )\n value = sum ( abs ( a(1:n) ) );\n elseif ( p == 2.0 )\n value = sqrt ( sum ( a(1:n).^2 ) );\n else\n value = ( sum ( ( abs ( a(1:n) ) ).^p ) ).^( 1.0 / p );\n end\n\n return\nend\n", "meta": {"author": "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_norm_lp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7875462217143954}} {"text": "% Section 8.1.1: Separating a point from a polyhedron\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Joelle Skaf - 10/09/05\n%\n% The goal is to produce a hyperplane separating x0 and the polyhedron\n% defined as {x | Ax <= b}\n% minimize mu'*x0 - b'*lambda\n% A'*lambda = mu\n% norm(mu)* <= 1\n% lambda >= 0\n\n% Input data\nrandn('seed',0);\nn = 10;\nm = 2*n;\nx0 = randn(n,1);\nA = randn(m,n);\nb = rand(m,1);\n\n% CVX solution\nfprintf(1,'Finding a separating hyperplane between the 2 polyhedra...');\n\ncvx_begin quiet\n variables muu(n) lambda(m)\n maximize ( muu'*x0 - b'*lambda )\n A'*lambda == muu; %#ok\n norm(muu) <= 1; %#ok\n lambda >= 0; %#ok\ncvx_end\n\nfprintf(1,'Done! \\n');\n\n% Verification\ndisp('------------------------------------------------------------------');\ndisp('Note that 0 is in {x | Ax <= b} by construction...' );\ndisp('Verifying that x0 is separated from {x | Ax <= b} i.e. mu^T*x0 > 0');\ndisp([' mu^T*x0 = ' num2str(muu'*x0) ]);\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch08_geometric_probs/separate_pt_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7874873317931625}} {"text": "%% Create artificial low-rank image\nperHei = 10;\nperWid = 20;\nhei = 50*perHei;\nwid1 = 5*perWid; rect1 = ones(hei, wid1) * 75;\nwid2 = 15*perWid; rect2 = ones(hei, wid2) * 184;\nwid3 = 8*perWid; rect3 = ones(hei, wid3) * 223;\nwid4 = 18*perWid; rect4 = ones(hei, wid4) * 113;\nwid5 = 10*perWid; rect5 = ones(hei, wid5) * 38;\nA = uint8([rect1 rect2 rect3 rect4 rect5]);\nD = imnoise(A, 'salt & pepper');\nA = double(A);\nD = double(D);\nE = D - A;\n%% Create low-rank matrix\n% m = 100; % m = 100, 200, 400, 800\n% r = 5; % rank(A) = 5, 10, 20, 40\n% U = randn(m,r);\n% V = randn(m,r);\n% A = U*V';\n% E = (imnoise(zeros(size(A)),'salt & pepper',0.1) > 0) .* (rand(size(A))-0.5)*2*500;\n% D = A + E;\n%% Apply APG to recover A_hat and E_hat\n[rows, cols] = size(D);\nlambda = rows^(-1/2);\ntic\n[A_hat,E_hat,numIter] = proximal_gradient_rpca(D, lambda);\ntoc\n\nnorm(A_hat-A, 'fro') / norm(A, 'fro')\n\nfigure; imshow(A,[]); title('original A');\nfigure; imshow(A_hat,[]); title('recovered A');", "meta": {"author": "YimianDai", "repo": "Image-Processing-Codes-for-Easier-Understanding", "sha": "874302799e48852624bc3760b58b46bd9360f238", "save_path": "github-repos/MATLAB/YimianDai-Image-Processing-Codes-for-Easier-Understanding", "path": "github-repos/MATLAB/YimianDai-Image-Processing-Codes-for-Easier-Understanding/Image-Processing-Codes-for-Easier-Understanding-874302799e48852624bc3760b58b46bd9360f238/src/(NIPS 2009) Robust Principal Component Analysis Exact Recovery of Corrupted Low-Rank Matrices by Convex Optimization/Demo_APG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.787487331167178}} {"text": "function y = laplace_pdf(x,mu,sigma)\n%LAPLACE_PDF Laplace probability density function (pdf).\n%\n% Y = LAPLACE_PDF(X,MU,SIGMA) Returns the Laplace pdf with\n% mean, MU, and scale, SIGMA, at the values in X.\n%\n% The size of Y is the common size of the input arguments. A scalar input \n% functions as a constant matrix of the same size as the other inputs. \n%\n% Default values for MU and SIGMA are 0 and 1 respectively.\n\n% Copyright (c) 2005 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n sigma = 1;\nend\n\nif nargin < 2;\n mu = 0;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny= -abs(x-mu)./sigma - log(2.*sigma);\ny=exp(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/gpstuff/dist/laplace_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7874488538005185}} {"text": "function H = gmm_entropy(Priors,Mu,Sigma)\n%GMM_ENTROPY: Computes the differentinal entropy of a Gaussian Mixture\n%Model. \n\nD = size(Mu,1);\nK = size(Mu,2);\nH = 0;\n\nif D == 1\n for k=1:K \n H = H + Priors(k) * (-log(Priors(k)) + 0.5 * log(((2*pi*exp(1))^(D)) * det(Sigma(k)) )); \n end \nelse\n for k=1:K\n H = H + Priors(k) * (-log(Priors(k)) + 0.5 * log(((2*pi*exp(1))^(D)) * det(Sigma(:,:,k)) ));\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/methods/toolboxes/gmmbox/GMMfunctions/GMM_functions/gmm_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7874488472411965}} {"text": "function [phi,lambda] = LC_froca(x,y,maxlat,minlat,maxlon,minlon)\n \n %LC_FROM_CARTESIAN\n %\n %\t[phi,lambda] = LC_from_cartesian(x,y,maxlat,minlat,maxlon,minlon)\n %\n %\tFunction to compute the angular coordinates PHI (latitude) and\n %\tLAMBDA (longitude) from the cartesian coordinates X and Y\n %\tgiven the MAXLAT, MINLAT, MAXLON & MINLON of the Lambert\n %\tconformal map on which these points have to be mapped.\n %\n %\twhere * phi: current location latitude\n %\t * lambda: current location longitude\n %\t * x & y : current cartesian coordinates\n %\t * maxlat: maximum latitude limit of the map\n %\t * minlat: minimum latitude limit of the map\n %\t * maxlon: maximum longitude limit of the map\n %\t * minlon: minimum longitude limit of the map\n %\t (remember: West longitude is < 0!)\n %\n %\tIf the LC_MAP function has been called before this function\n %\tAND the same map limits are used, then it is not neccessary to\n %\tenter the last 4 arguments:\n %\n %\t[phi,lambda] = LC_to_cartesian(x,y)\n %\n %\tSource: Equations taken from \"Map Projections Used by the\n %\t U.S. Geological Survey\" by John P. Snyder\n %\t Geological Survey Bulletin 1532, pg: 101-109.\n \n report_this_filefun();\n \n todeg = 180 / pi;\n \n % set the global variables\n global scale\n global phi0 lambda0 phi1 phi2\n global maxlatg minlatg maxlong minlong\n ZG = ZmapGlobal.Data;\n torad = ZG.torad;\n Re = ZG.Re;\n \n if nargin == 2\n %get data from global variables\n maxlat = maxlatg; minlat = minlatg;\n maxlon = maxlong; minlon = minlong;\n elseif nargin == 6\n % set the global variable for later use\n maxlatg = maxlat; minlatg = minlat;\n maxlong = maxlon; minlong = minlon;\n \n % set some constants\n scale = 1;\n \n % get the Standard Parallels and Center Coordinates\n phi2 = (minlat + ((maxlat + minlat) / 4)) * torad;\n phi1 = (maxlat - ((maxlat + minlat) / 4)) * torad;\n phi0 = (phi1 + phi2) / 2;\n lambda0 = ((minlon + maxlon) / 2) * torad;\n else\n disp('This function requires 2 or 6 input arguments!')\n help LC_to_cartesian\n return\n end\n \n % compute the constant of the cone: sine_phi0\n tan1 = tan((pi/4) + (phi1/2));\n tan2 = tan((pi/4) + (phi2/2));\n sine_phi0 = log(cos(phi1)/cos(phi2)) / log(tan2/tan1);\n \n % compute the auxiliary function: psi\n psi = (cos(phi1) * (tan1.^sine_phi0)) / sine_phi0;\n \n % compute the polar radius to the origin: rho0\n tan0 = tan((pi/4) + (phi0/2));\n rho0 = (Re * psi) / (tan0.^sine_phi0);\n \n % compute the polar angles: theta\n theta = atan(x ./ (rho0 - y));\n \n % compute rho (inverse)\n rho = sign(sine_phi0) * sqrt((x.^2) + (rho0 - y).^2);\n \n % store the latitudes and longitudes in output variables\n arctan = atan((Re * psi ./ rho).^(1/sine_phi0));\n phi = ((2 * arctan) - (pi/2)) * todeg;\n lambda = ((theta / sine_phi0) + lambda0) * todeg;\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/lc_froca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7874091641657028}} {"text": "%% Example demonstrating MOL-WENO3-LF and MOL-WENO5-LF schemes\n%% from J. Comp. Phys. 126, pp. 202-228 (1996) by Jiang and Shu\n%% \"Efficient Implementation of Weighted ENO Schemes\"\nfunction WENO_Buckley_Leverett\nclose all; clc;\nglobal dx\n\n% Spatial variable interval (-1, 1) from (8.1) example 2\nx = linspace(-1.0, 1.0, 80);\nN = length(x);\ndx = x(2)-x(1);\n\n% Initial conditions for 1D Buckey-Leverett problem\nu0(1:N) = 0.0;\nu0((N/4):(N/2)) = 1.0;\n\n% Time interval (as in Example 2)\nt = linspace(0.0, 0.4, 100);\n\n% Solve MOL ODEs system for WENO3-LF and WENO5-LF schemes with RKF45 solver\ntic;\n[ZZ, u1] = ode45(@MOL_WENO3, t, u0);\n[ZZ, u2] = ode45(@MOL_WENO5, t, u0);\ntoc\n\n% Plot each solution\nfor I=1:100\n plot(x, u0, 'b-', x, u1(I,:), 'ro', x, u2(I,:), 'k-', 'LineWidth', 2);\n legend('Initial', 'MOL + WENO3-LF', 'MOL + WENO5-LF', 'Location', 'NorthEast');\n axis([x(1) x(end) 0 1.1]);\n grid on;\n pause(0.01)\n drawnow;\nend\n\n%% Buckey-Leverett flux F(u)\nfunction res = Flux(u)\nres = 4*u.^2./(4*u.^2+(1-u).^2);\n\n%% Exact expression for partial derivative from F(u) by u\nfunction res = Jacobian(u)\nres = 8*u.*(1-u)./(5*u.^2-2*u+1).^2;\n\n%% MOL ODEs for semi-discrete Buckley-Leverett equation with WENO3 flux\n%% reconstruction\nfunction [res] = MOL_WENO3(t, u)\nglobal dx\n\nN = length(u); I = 2:(N+1);\n\n% Preallocate memory and add ghost nodes at the ends\nU(1) = u(1); U(I) = u(I-1); U(N+2) = u(end); U(N+3) = u(end);\nalpha1 = zeros(size(U)); alpha2 = zeros(size(U)); \nR_minus = zeros(size(U)); R_plus = zeros(size(U)); \n\n% Lax-Friedrichs (LF) flux splitting\na = max(abs(Jacobian(U)));\nFp = 0.5*( Flux(U) + a*U ); Fm = 0.5*( Flux(U) - a*U );\n\n% WENO3 \"right\" flux reconstruction\nalpha1(I) = (1/3)./(eps + (Fp(I)-Fp(I-1)).^2).^2; alpha2(I) = (2/3)./(eps + (Fp(I+1)-Fp(I)).^2).^2;\nomega1 = alpha1./(alpha1 + alpha2); omega2 = alpha2./(alpha1 + alpha2);\nR_plus(I) = omega1(I).*(3/2*Fp(I) - 1/2*Fp(I-1)) + omega2(I).*(1/2*Fp(I) + 1/2*Fp(I+1));\n\n% WENO3 \"left\" flux reconstruction\nalpha1(I) = (1/3)./(eps + (Fm(I+2)-Fm(I+1)).^2).^2; alpha2(I) = (2/3)./(eps + (Fm(I+1)-Fm(I)).^2).^2; \nomega1 = alpha1./(alpha1 + alpha2); omega2 = alpha2./(alpha1 + alpha2);\nR_minus(I) = omega1(I).*(3/2*Fm(I+1) - 1/2*Fm(I+2)) + omega2(I).*(1/2*Fm(I) + 1/2*Fm(I+1));\n\n% Combine fluxes and find finite volume spatial derivative\nres(I-1) = -(R_plus(I)+R_minus(I)-R_plus(I-1)-R_minus(I-1))/dx;\nres = res';\n\n%% MOL ODEs for semi-discrete Buckley-Leverett equation with WENO5 flux\n%% reconstruction\nfunction [res] = MOL_WENO5(t, u)\nglobal dx\n\nN = length(u); I = 3:(N+2);\n\n% Preallocate memory and add ghost nodes at the ends\nU(1) = u(1); U(2) = u(1); U(I) = u(I-2); U(N+3) = u(end); U(N+4) = u(end); U(N+5) = u(end);\nalpha1 = zeros(size(U)); alpha2 = zeros(size(U)); alpha3 = zeros(size(U));\nbeta1 = zeros(size(U)); beta2 = zeros(size(U)); beta3 = zeros(size(U));\nR_minus = zeros(size(U)); R_plus = zeros(size(U)); \n\n% Lax-Friedrichs (LF) flux splitting\na = max(abs(Jacobian(U)));\nFp = 0.5*( Flux(U) + a*U ); Fm = 0.5*( Flux(U) - a*U );\n\n% WENO5 \"right\" flux reconstruction\nbeta1(I) = (13.0/12.0)*(Fp(I) - 2.0*Fp(I+1) + Fp(I+2)).^2 ...\n + (1.0/4.0)*(3.0*Fp(I) - 4.0*Fp(I+1) + Fp(I+2)).^2;\nbeta2(I) = (13.0/12.0)*(Fp(I-1) - 2.0*Fp(I) + Fp(I+1)).^2 ... \n + (1.0/4.0)*(Fp(I-1) - Fp(I+1)).^2;\nbeta3(I) = (13.0/12.0)*(Fp(I-2) - 2.0*Fp(I-1) + Fp(I)).^2 ...\n + (1.0/4.0)*(Fp(I-2) - 4.0*Fp(I-1) + 3.0*Fp(I)).^2;\n\nalpha1(I) = (3.0/10.0)./(eps + beta1(I)).^2;\nalpha2(I) = (3.0/5.0)./(eps + beta2(I)).^2;\nalpha3(I) = (1.0/10.0)./(eps + beta3(I)).^2;\n\nomega1 = alpha1./(alpha1 + alpha2 + alpha3);\nomega2 = alpha2./(alpha1 + alpha2 + alpha3);\nomega3 = alpha3./(alpha1 + alpha2 + alpha3);\n\nR_plus(I) = omega1(I).*(1.0/3.0*Fp(I) + 5.0/6.0*Fp(I+1) - 1.0/6.0*Fp(I+2)) ...\n + omega2(I).*(-1.0/6.0*Fp(I-1) + 5.0/6.0*Fp(I) + 1.0/3.0*Fp(I+1)) ...\n + omega3(I).*(1.0/3.0*Fp(I-2) - 7.0/6.0*Fp(I-1) + 11.0/6.0*Fp(I));\n\n% WENO5 \"left\" flux reconstruction\nbeta1(I) = (13.0/12.0)*(Fm(I+1) - 2.0*Fm(I+2) + Fm(I+3)).^2 ...\n + (1.0/4.0)*(3.0*Fm(I+1) - 4.0*Fm(I+2) + Fm(I+3)).^2;\nbeta2(I) = (13.0/12.0)*(Fm(I) - 2.0*Fm(I+1) + Fm(I+2)).^2 ...\n + (1.0/4.0)*(Fm(I) - Fm(I+2)).^2;\nbeta3(I) = (13.0/12.0)*(Fm(I-1) - 2.0*Fm(I) + Fm(I+1)).^2 ...\n + (1.0/4.0)*(Fm(I-1) - 4.0*Fm(I) + 3.0*Fm(I+1)).^2;\n\nalpha1 = (1.0/10.0)./(eps + beta1).^2;\nalpha2 = (3.0/5.0)./(eps + beta2).^2;\nalpha3 = (3.0/10.0)./(eps + beta3).^2;\n\nomega1 = alpha1./(alpha1 + alpha2 + alpha3);\nomega2 = alpha2./(alpha1 + alpha2 + alpha3);\nomega3 = alpha3./(alpha1 + alpha2 + alpha3);\n\nR_minus(I) = omega1(I).*(1.0/3.0*Fm(I+3) - 7.0/6.0*Fm(I+2) + 11.0/6.0*Fm(I+1)) ...\n + omega2(I).*(-1.0/6.0*Fm(I+2) + 5.0/6.0*Fm(I+1) + 1.0/3.0*Fm(I)) ...\n + omega3(I).*(1.0/3.0*Fm(I+1) + 5.0/6.0*Fm(I) - 1.0/6.0*Fm(I-1));\n\n% Combine fluxes and find finite volume spatial derivative\nres(I-2) = -(R_plus(I)+R_minus(I)-R_plus(I-1)-R_minus(I-1))/dx;\nres = res';\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40956-example-of-weno3-lf-and-weno5-lf-scheme-for-1d-buckey-leverett-problem/WENO_Buckley_Leverett.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7873986818916074}} {"text": "% Generate MAR(2) and fit MAR model\n\ndisp('Generating data from known MAR(2) model');\nd=2;\np=2;\nT=100;\nw=[0;0];\n\n% Coeffs at lag 1\nA1 = [ 0.4 1.2; 0.3 0.7 ];\n% Coeffs at lag 2\nA2 = [ 0.35 -0.3; -0.4 -0.5 ];\nA = [ A1 A2 ];\n\nC = [ 1.00 0.50; 0.50 1.50 ];\nlambda_true=inv(C);\n\n% Generate observations\nx = spm_mar_gen (w, A, C, T);\n\nlogev=[];\nfor m=1:5,\n disp(sprintf('Fitting MAR model with %d components',m));\n mar=spm_mar(x,m);\n logev=[logev; mar.fm];\nend\nlogev=logev-min(logev);\n\nfigure\nsubplot(2,1,1);\nplot(x);\ntitle('Bivariate time series from MAR(2) model');\nsubplot(2,1,2);\nbar(logev);\nxlabel('Number of time lags');\nylabel('Log Evidence');\n\n\n% Specify prior - this is optional. \n% spm_mar.m runs without the prior being set.\nprior=spm_mar_prior(d,p,'global');\n[mar,y,y_pred]=spm_mar(x,2,prior);\n\ndisp(' ');\ndisp('Estimates from fitting MAR(2) model');\ndisp('Lag 1');\ndisp('True coefficients');\ndisp(A1);\ndisp('Estimated coefficients');\ndisp(-mar.lag(1).a)\n\ndisp('Lag 2');\ndisp('True coefficients');\ndisp(A2);\ndisp('Estimated coefficients');\ndisp(-mar.lag(2).a)\n\ndisp('Noise covariance');\ndisp('True:');\ndisp(C);\ndisp('Estimated:');\ndisp(mar.noise_cov);\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/spectral/spm_mar_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7873986724498294}} {"text": "function pdf = log_uniform_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% LOG_UNIFORM_PDF evaluates the Log Uniform PDF.\n%\n% Discussion:\n%\n% PDF(A,B;X) = 1 / ( X * ( log ( B ) - log ( A ) ) ) for A <= X <= B\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 1.0 < A < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < a )\n pdf = 0.0;\n elseif ( x <= b )\n pdf = 1.0 / ( x * ( log ( b ) - log ( a ) ) );\n else\n pdf = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/log_uniform_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7873986709326506}} {"text": "function y=PSNR(noisyImage,restoredImage)\n \nnoisyImage = double(noisyImage);\nrestoredImage = double(restoredImage);\n% Compute the PSNR of two gray scale image\n% Traditional progarmming using loops \n% Class input : [0,1] \n% july, 25 , 2012\n% KHMOU Youssef\n \nN=size(noisyImage);\nif length(N)> 2\n error('Input must be grayscale image');\nend\nif size(noisyImage)~=size(restoredImage)\n error('The images must have the same size');\nend\n \n%if ~isa(noisyImage,'double') \n% noisyImage=double(noisyImage)./255.00;\n%end\n%if ~isa(restoredImage,'double')\n% restoredImage=double(restoredImage)./255.00;\n%end\n \n% begin\n \nd1=max(noisyImage(:));\nd2=max(restoredImage(:));\nd=max(d1,d2);\n\n\nMSE=0;\nfor i=1:N(1)\n for j=1:N(2)\n if isnan(noisyImage(i,j)) || isinf(restoredImage(i,j))...\n || isnan(restoredImage(i,j)) || isinf(noisyImage(i,j))\n continue;\n end\n MSE=MSE+((abs(noisyImage(i,j)-restoredImage(i,j))).^2);\n end\nend\n \nMSE=MSE./(N(1)*N(2));\n\n \ny=10*log10((d.^2) /MSE);\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/Evaluation/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7873314705920884}} {"text": "function U = randunitary(n, N)\n% Generates uniformly random unitary matrices.\n%\n% function U = randunitary(n, N)\n%\n% U is a n-by-n-by-N array such that each slice U(:, :, i) is a random\n% unitary matrix of size n (i.e., a matrix in the unitary group U(n)),\n% sampled from the Haar measure (uniform distribution).\n% \n% By default, N = 1.\n%\n% Complexity: N times O(n^3).\n% For details on the algorithm, see Mezzadri 2007,\n% \"How to generate random matrices from the classical compact groups.\"\n%\n% See also: randrot qr_unique\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, June 18, 2019.\n% Contributors: \n% Change log: \n\n if nargin < 2\n N = 1;\n end\n \n if n == 1\n U = sign(randn(1, 1, N) + 1i*randn(1, 1, N));\n return;\n end\n \n % Generated as such, the slides of U are uniformly distributed over\n % U(n), the set of unitary matrices: see Mezzadri 2007, p597.\n U = qr_unique(randn(n, n, N) + 1i*randn(n, 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/rotations/randunitary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7873252129469956}} {"text": "function [alpha, beta, gamma, stability] = evalABGParam(process, noisy, dt)\n% evalABGParam - evaluates alpha, beta and gamma parameters\n% With this parameters, alpha-beta filter becomes a steady-state Kalman filter\n%\n% Syntax: [alpha,beta,gamma,stability] = evalABGParam(process,noisy,dt)\n% [alpha,beta,gamma,stability] = evalABGParam([alpha,beta,gamma])\n%\n% Inputs:\n% process - real system state\n% noisy - measured system state\n% dt - delta time (sample rate)\n%\n% Outputs:\n% alpha - alpha parameter\n% beta - beta parameter\n% gamma - gamma parameter\n% stability - Juri's Stability Test\n%\n% Other m-files required: none\n% Subfunctions: none\n% MAT-files required: none\n%\n% See also: abgFilter;\n\n% Author: Marco Borges, Ph.D. Student, Computer/Biomedical Engineer\n% UFMG, PPGEE, Neurodinamica Lab, Brazil\n% email address: marcoafborges@gmail.com\n% Website: http://www.cpdee.ufmg.br/\n% References:\n% NEAL, S. R., Parametric relations for a-b-g filter predictor, IEEE\n% Trans. on Automatic Control, AC-12, June 1967\n% TENNE, D. and Singh, T., Characterizing Performance a-b-g Filters, IEEE\n% Transactions on Aerospace and Electronic Systems, 38, 2002\n% September 2013; Version: v1; Last revision: 2013-09-18\n% Changelog:\n%\n%------------------------------- BEGIN CODE -------------------------------\n\nif nargin == 3\n varProcess = var(process);\n varNoise = var(noisy);\n l = varProcess * dt / varNoise; % lambda\n r = (4+l-sqrt(8*l+l^2))/4;\n alpha = 1 - r^2;\n beta = 2*(2-alpha)-4*sqrt(1-alpha);\n gamma = beta^2/(2*alpha);\nelseif nargin == 1 && length(process) == 3\n alpha = process(1);\n beta = process(2);\n gamma = process(3);\nelse\n error('evalABGParam : Incorrect Parameters!');\nend\n\nif ( alpha > 0 && alpha < 2 && beta > 0 && beta < (4-2*alpha) && ...\n gamma > 0 && gamma < (4*alpha*beta)/(2*alpha) )\n stability = 'Stable';\nelse\n stability = 'Unstable';\nend\n%-------------------------------- END CODE --------------------------------", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43571-evalabgparam/evalABGParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002493, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7873252128609018}} {"text": "function f = p27_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P27_F evaluates the objective function for problem 27.\n%\n% Discussion:\n%\n% F can be regarded as a function of R = SQRT ( X(1)^2 + X(2)^2 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the argument of the objective function.\n%\n% Output, real F, the value of the objective function.\n%\n r = sqrt ( x(1)^2 + x(2)^2 );\n\n a = ( 1.0 + 0.001 * r^2 )^( -2 );\n\n b = ( sin ( r ) )^2 - 0.5;\n\n f = 0.5 + a * b;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p27_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7873252023534162}} {"text": "function [ distMoment ] = CalcNormalDistributionMoments( paramMu, paramSigmaSquared, momentOrder )\n% See https://en.wikipedia.org/wiki/Normal_distribution#Moments.\n\nswitch(momentOrder)\n case(1)\n distMoment = (paramMu ^ momentOrder);\n case(2)\n distMoment = (paramMu ^ momentOrder) + paramSigmaSquared;\n case(3)\n distMoment = (paramMu ^ momentOrder) + (3 * paramMu * paramSigmaSquared);\n case(4)\n distMoment = (paramMu ^ momentOrder) + (6 * (paramMu ^ 2) * paramSigmaSquared) + (3 * (paramSigmaSquared ^ 2));\n case(5)\n distMoment = (paramMu ^ momentOrder) + (10 * (paramMu ^ 3) * paramSigmaSquared) + (15 * paramMu * (paramSigmaSquared ^ 2));\n case(6)\n distMoment = (paramMu ^ momentOrder) + (15 * (paramMu ^ 4) * paramSigmaSquared) + (45 * (paramMu ^ 2) * (paramSigmaSquared ^ 2)) + (15 * (paramSigmaSquared ^ 3));\n case(7)\n distMoment = (paramMu ^ momentOrder) + (21 * (paramMu ^ 5) * paramSigmaSquared) + (105 * (paramMu ^ 3) * (paramSigmaSquared ^ 2)) + (105 * paramMu * (paramSigmaSquared ^ 3));\n case(8)\n distMoment = (paramMu ^ momentOrder) + (28 * (paramMu ^ 6) * paramSigmaSquared) + (210 * (paramMu ^ 4) * (paramSigmaSquared ^ 2)) + (420 * (paramMu ^ 2) * (paramSigmaSquared ^ 3)) + (105 * (paramSigmaSquared ^ 4));\n otherwise\n gridRadius = 10 * sqrt(paramSigmaSquared);\n gridNaumSamles = 1e6;\n vX = linspace(paramMu - gridRadius, paramMu + gridRadius, gridNaumSamles);\n dX = mean(diff(vX));\n vNormalPdf = (1 / sqrt(2 * pi * paramSigmaSquared)) * exp(-( (vX - paramMu) .^ 2 ) ./ (2 * paramSigmaSquared));\n distMoment = sum( (vX .^ momentOrder) .* vNormalPdf * dX);\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/CrossValidated/Q334017/CalcNormalDistributionMoments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.787290192742437}} {"text": "function [ll,lls]=stdtloglik(x,mu,sigma2,nu)\n% Log likelihood of the Standardized T distribution\n%\n% USAGE:\n% [LL,LLS]=stdtloglik(X,MU,SIGMA2,NU)\n%\n% INPUTS:\n% X - Standardized T random variables, either scalar or column vector\n% MU - Mean of X, either scalar or size(x) \n% SIGMA2 - Variance of X, either scalar or size(x)\n% V - Degree of freedom parameters, either scalar or size(x)\n%\n% OUTPUTS:\n% LL - Log-likelihood evaluated at X\n% LLS - Vector of log-likelihoods corresponding to X\n%\n% COMMENTS:\n% V>2\n%\n% REFERENCES:\n% [1] Cassella and Berger (1990) 'Statistical Inference'\n%\n% See also STDTCDF, STDTINV, STDTRND, STDTPDF \n\n% Copyright: \n% Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 9/1/2004\n\n[T,K]=size(x);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif K~=1\n error('X must be a column vector');\nend\n\nif nargin==4\n if length(mu)~=1 && ~all(size(mu)==[T K])\n error('mu must be either a scalar or the same size as X');\n end\n if any(sigma2<=0)\n error('sigma2 must contain only positive elements')\n end\n if length(sigma2)==1\n sigma2=sigma2*ones(T,K);\n elseif size(sigma2,1)~=T || size(sigma2,2)~=1\n error('sigma2 must be a scalar or a vector with the same dimensions as X');\n end\n if length(nu)>1 || nu<=2\n error('nu must be a scalar greater than 2');\n end\n x=x-mu;\nelse\n error('Only 4 inputs supported');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Compute the log likelihood\nll = T*gammaln(0.5*(nu+1)) - T*gammaln(nu/2) - T/2*log(pi*(nu-2)) ...\n - 0.5*sum(log(sigma2)) - ((nu+1)/2)*sum(log(1 + (x.^2)./(sigma2*(nu-2))));\n\n%Compute the individual log likelihoods if needed\nif nargout>1\n lls = gammaln(0.5*(nu+1)) - gammaln(nu/2) - 1/2*log(pi*(nu-2))...\n - 0.5*(log(sigma2)) - ((nu+1)/2)*(log(1 + (x.^2)./(sigma2*(nu-2))));\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/distributions/stdtloglik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7872901813882637}} {"text": "% Box volume maximization\n% Boyd, Kim, Vandenberghe, and Hassibi, \"A Tutorial on Geometric Programming\"\n% Written for CVX by Almir Mutapcic 02/08/06\n% (a figure is generated)\n%\n% Maximizes volume of a box-shaped structure which has constraints\n% on its total wall area, its total floor area, and which has lower\n% and upper bounds on the aspect ratios. This leads to a GP:\n%\n% maximize h*w*d\n% s.t. 2(h*w + h*d) <= Awall, w*d <= Afloor\n% alpha <= h/w <= beta\n% gamma <= d/w <= delta\n%\n% where variables are the box height h, width w, and depth d.\n\n% problem constants\nalpha = 0.5; beta = 2; gamma = 0.5; delta = 2;\n\n% varying parameters for an optimal trade-off curve\nN = 10;\nAfloor = logspace(1,3,N);\nAwall = [100 1000 10000];\nopt_volumes = zeros(length(Awall),N);\n\ndisp('Computing optimal box volume for:')\n\n% setup various GP problems with varying parameters\ncvx_setpath\ncvx_setspath\nfor k = 1:length(Awall)\n Awall_k = Awall(k);\n fprintf( 'Awall = %d:\\n', Awall(k) );\n for n = 1:N\n % resolve the problem with varying parameters\n Afloor_n = Afloor(n);\n fprintf( ' Afloor = %7.2f: ', Afloor(n) );\n cvx_begin gp quiet\n variables h w d\n % objective function is the box volume\n maximize( h*w*d )\n subject to\n 2*(h*w + h*d) <= Awall_k; %#ok\n w*d <= Afloor_n; %#ok\n alpha <= h/w <= beta; %#ok\n gamma <= d/w <= delta; %#ok\n cvx_end\n fprintf( 'max_volume = %3.2f\\n', cvx_optval );\n opt_volumes(k,n) = cvx_optval;\n end\nend\ncvx_clearspath\ncvx_clearpath\n\n% plot the tradeoff curve\nfigure, clf\nloglog(Afloor,opt_volumes(1,:), Afloor,opt_volumes(2,:), Afloor,opt_volumes(3,:));\nxlabel('Afloor'); ylabel('V');\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/gp_tutorial/max_volume_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7872734677111741}} {"text": "function f1 = p09_f1 ( x )\n\n%*****************************************************************************80\n%\n%% P09_F1 evaluates the first derivative for problem 9.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 January 2008\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 = 2.0 * x ...\n - 10.0 * cos ( x * x - 3.0 * x + 2.0 ) ...\n * ( 2.0 * x - 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/p09_f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7872734614038541}} {"text": "function pdf = quasigeometric_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% QUASIGEOMETRIC_PDF evaluates the Quasigeometric PDF.\n%\n% Discussion:\n%\n% PDF(A,B;X) = A if 0 = X;\n% = (1-A) * (1-B) * B^(X-1) if 1 <= X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Darren Glass, Philip Lowry,\n% Quasiquasigeometric Distributions and Extra Inning Baseball Games,\n% Mathematics Magazine,\n% Volume 81, Number 2, April 2008, pages 127-137.\n%\n% Paul Nahin,\n% Digital Dice: Computational Solutions to Practical Probability Problems,\n% Princeton University Press, 2008,\n% ISBN13: 978-0-691-12698-2,\n% LC: QA273.25.N34.\n%\n% Parameters:\n%\n% Input, integer X, the independent variable.\n% 0 <= X\n%\n% Input, real A, the probability of 0 successes.\n% 0.0 <= A <= 1.0.\n%\n% Input, real B, the depreciation constant.\n% 0.0 <= B < 1.0.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0 )\n\n pdf = 0.0;\n\n elseif ( x == 0 )\n\n pdf = a;\n\n elseif ( b == 0.0 )\n\n if ( x == 1 )\n pdf = 1.0;\n else\n pdf = 0.0;\n end\n\n else\n\n pdf = ( 1.0 - a ) * ( 1.0 - b ) * b^( x - 1 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/quasigeometric_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7872408188622438}} {"text": "function normVal=dualQuatNorm(dq)\n%%DUALQUATNORM Compute the norm of a dual quaternion. This is defined as\n% dq*dq^*, where dq^* is the conjugate of the dual quaternion.\n% The result is a dual quaternion with no hypercomplex components\n% (but it might have both a real and a dual component). Dual\n% quaternions are often used for simultaneously representing\n% orientation and position. A dual quaternion consists of two\n% parts dq=q1+eps*q2, where q1 and q2 are quaternions and eps is\n% a dual number. Dual numbers are such that eps^2=0 and have\n% various rules for multiplication with complex numbers. Note\n% that the norm does not depend on the handedness of the\n% quaternion algebra, even though the dualQuatMult and quatMult\n% functions do.\n%\n%INPUTS: dq A dual quaternion represented as a 4X2 matrix dq(:,1) is the\n% non-dual quaternion and dq(:,2) is the dual quaternion (the\n% ones times eps, the dual number). The elements of each\n% quaternion are ordered q(1,1)+i*q(2,1)+j*q(3,1)+k*q(4,1), where\n% i,j and k are the typical hypercomplex numbers.\n%\n%OUTPUTS: normVal The value of the norm of the dual quaternion. This is a\n% dual quaternion with no complex parts, but it might have\n% a dual part (normVal(1,:) can be nonzero). A unit dual\n% quaternion has only a real part and no dual part\n% (normVal(1,1)=1,normVal(2,1)=0) nor complex parts.\n%\n%Dual quaternions and common operations including computation of the norm\n%of the dual quaternion are discussed in [1]. The norm of a standard\n%(non-dual) quaternion is generally just taken to be the same as the norm\n%of a typical 4X1 vector.\n%\n%REFERENCES:\n%[1] B. Kenwright, \"A beginners guide to dual-quaternions: What they are,\n% how they work, and how to use them for 3D character hierarchies,\" in\n% Proceedings of the 20th International Conference on Computer Graphics,\n% Visualization and Computer Vision, Prague, Czech Republic, 24-27 Jun.\n% 2012.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnormVal=dualQuatMult(dq,dualQuatConj(dq));\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/Dual_Quaternions/dualQuatNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7872408171485232}} {"text": "function c = correlation_besselj ( n, rho, rho0 )\n\n%*****************************************************************************80\n%\n%% CORRELATION_BESSELJ evaluates the Bessel J correlation function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 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, integer N, the number of arguments.\n%\n% Input, real RHO(N,1), the arguments.\n%\n% Input, real RHO0, the correlation length.\n%\n% Output, real C(N,1), the correlations.\n%\n rho = rho ( : );\n\n rhohat = abs ( rho ) / rho0;\n\n c = besselj ( 0, rhohat );\n\n return\nend\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/correlation/correlation_besselj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7872408134848451}} {"text": "% f6.m\n% Schaffer's F6 function\n% commonly used to test optimization/global minimization problems\n%\n% z = 0.5+ (sin^2(sqrt(x^2+y^2))-0.5)/((1+0.01*(x^2+y^2))^2)\n\nfunction [out]=f6(in)\n x=in(:,1);\n y=in(:,2);\n num=sin(sqrt(x.^2+y.^2)).^2 - 0.5;\n den=(1.0+0.01*(x.^2+y.^2)).^2;\n\n out=0.5 +num./den;\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智能算法30个案例分析/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7872177821450859}} {"text": "function mean = rayleigh_mean ( a )\n\n%*****************************************************************************80\n%\n%% RAYLEIGH_MEAN returns the mean of the Rayleigh PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the parameter of the PDF.\n% 0.0 < A.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a * sqrt ( 0.5 * pi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/rayleigh_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7871672408331977}} {"text": "function g=firkaiser(L,beta,varargin)\n%FIRKAISER Kaiser-Bessel window\n% Usage: g=firkaiser(L,beta);\n% g=firkaiser(L,beta,...);\n%\n% `firkaiser(L,beta)` computes the Kaiser-Bessel window of length *L* with\n% parameter *beta*. The smallest element of the window is set to zero when\n% the window has an even length. This gives the window perfect whole-point\n% even symmetry, and makes it possible to use the window for a Wilson\n% basis.\n%\n% `firkaiser` takes the following flags at the end of the input arguments:\n%\n% 'normal' Normal Kaiser-Bessel window. This is the default.\n%\n% 'derived' Derived Kaiser-Bessel window.\n%\n% 'wp' Generate a whole point even window. This is the default.\n%\n% 'hp' Generate half point even window.\n% \n% Additionally, `firkaiser` accepts flags to normalize the output. Please\n% see the help of |setnorm|. Default is to use `'null'` normalization.\n%\n% Note that odd-length Derived Kaiser-Bessel windows are not\n% mathematically defined, yet they are supported by this code.\n%\n% See also: firwin, setnorm\n%\n% References: opsc89\n\n% AUTHOR: unknown. Additions by Clara Hollomey\n\nif nargin<2\n error('Too few input arguments.');\nend;\n\nif numel(beta)>1\n error('beta must be a scalar.');\nend;\n\n% Define initial value for flags and key/value pairs.\ndefinput.import={'setnorm'};\ndefinput.importdefaults={'null'};\ndefinput.flags.centering={'wp','hp'};\ndefinput.flags.stype={'normal','derived'};\n\n[flags,keyvals]=ltfatarghelper({},definput,varargin);\n\ncent=0;\nif flags.do_hp\n cent=.5;\nend;\n\nif flags.do_normal\n \n if (L == 1)\n g = 1;\n else\n m = L - 1;\n k = (0:m)'+rem(L,2)/2-.5+cent;\n k = 2*beta/(m)*sqrt(k.*(m-k));\n g = besseli(0,k)/besseli(0,beta);\n end;\n\n g=ifftshift(g);\n \n if ((flags.do_wp && rem(L,2)==0) || ...\n (flags.do_hp && rem(L,2)==1))\n \n % Explicitly zero last element. This is done to get the right\n % symmetry, and because that element sometimes turns negative.\n g(floor(L/2)+1)=0;\n end;\n \nelse\n \n %if rem(L,2)==1 \n % error('The length of the choosen window must be even.');\n %end;\n \n if flags.do_wp\n %if rem(L,4)==0\n % L2=L/2+2;\n %else\n L2=floor(L/2+1);\n %end;\n else\n L2=floor((L+1)/2);\n end;\n \n % Compute a normal Kaiser window\n g_normal=fftshift(firkaiser(L2,beta,flags.centering));\n \n g1=sqrt(cumsum(g_normal(1:L2))./sum(g_normal(1:L2)));\n \n if flags.do_wp\n if rem(L,2)==0\n g=[flipud(g1);...\n g1(2:L/2)];\n else\n g=[flipud(g1);...\n g1(1:floor(L/2))];\n end; \n else\n if rem(L,2)==0\n g=[flipud(g1);0;...\n g1(1:end-1)];\n else\n g=[flipud(g1);...\n g1(1:end-1)];\n end\n end;\n\n if ((flags.do_wp && rem(L,2)==0)) %|| ...\n %(flags.do_hp && rem(L,2)==1))\n \n % Explicitly zero last element. This is done to get the right\n % symmetry, and because that element sometimes turn negative.\n g(floor(L/2)+1)=0;\n end;\n \nend;\n\n% The besseli computation sometimes generates a zero imaginary component.\ng=real(g);\n\ng=setnorm(g,flags.norm);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/firkaiser.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7871672375849654}} {"text": "%Recursive Zonal Equal Area Sphere Partitioning: Utilities\n%\n% Recursive Zonal Equal Area (EQ) Sphere Partitioning Toolbox.\n% Release 1.10 2005-06-01\n%\n%Functions\n%=========\n%\n% area_of_cap Area of spherical cap\n% area_of_collar Area of spherical collar\n% area_of_ideal_region Area of one region of an EQ partition\n% area_of_sphere Area of sphere\n% cart2polar2 Convert Cartesian to spherical polar coordinates on S^2\n% euc2sph_dist Convert Euclidean to spherical distance\n% euclidean_dist Euclidean distance between two points\n% fatcurve Create a parameterized cylindrical surface\n% haslight Check if axis handle has a light attached\n% ideal_collar_angle Ideal angle for spherical collars of an EQ partition\n% illustration_options Options for illustrations of EQ partitions\n% partition_options Options for EQ partition\n% polar2cart Convert spherical polar to Cartesian coordinates\n% sph2euc_dist Convert spherical to Euclidean distance\n% spherical_dist Spherical distance between two points on the sphere\n% sradius_of_cap Spherical radius of spherical cap of given area\n% volume_of_ball Volume of the unit ball\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from e2s to euc2sph_dist\n% Function changed name from s2e to sph2euc_dist\n% Function changed name from s2x to polar2cart\n% Function changed name from x2s2 to cart2polar2\n% Add new function fatcurve\n% Add new function haslight\n% Clean up descriptions\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\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_utilities/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7871672347780923}} {"text": "function [X_mean]=wmean(X,W)\n\n% function [X_mean]=wmean(X,W)\n% ------------------------------------------------------------------------\n% This function calculates the weighted mean of X using the weights defined\n% in the vector W. \n%\n% Uses the following formula: X_mean=sum(X.*W)./sum(W);\n%\n% 12/09/2008\n% ------------------------------------------------------------------------\n\n%%\n\nX=X(:);\nW=W(:);\nX_mean=sum(X.*W)./sum(W);\n\n%% END\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/wmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137298, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7871672327328063}} {"text": "function [C, sigma] = dataset3Params(X, y, Xval, yval)\n%EX6PARAMS 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] = EX6PARAMS(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\nchoice = [0.01 0.03 0.1 0.3 1 3 10 30]';\nminError = Inf;\ncurC = Inf;\ncur_sigma = Inf;\n\nfor i = 1:8\n\tfor j = 1:8\n\t\tmodel = svmTrain(X, y, choice(i), @(x1, x2) gaussianKernel(x1, x2, choice(j)));\n\t\tpredictions = svmPredict(model,Xval);\n\t\terror = mean(double(predictions ~= yval));\n\t\tif error < minError\n\t\t\tminError = error;\n\t\t\tcurC = choice(i);\n\t\t\tcur_sigma = choice(j);\n\t\tend\n\tend\nend\t\t\n\nC = curC;\nsigma = cur_sigma;\n\n\nsteps = [ 0.01 0.03 0.1 0.3 1 3 10 30 ];\nminError = Inf;\nminC = Inf;\nminSigma = Inf;\n\n% =========================================================================\n\nend\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex6/ex6/dataset3Params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8688267796346598, "lm_q1q2_score": 0.7871482180255175}} {"text": "function [ a, b, c ] = line_exp2imp_2d ( p1, p2 )\n\n%*****************************************************************************80\n%\n%% LINE_EXP2IMP_2D converts an explicit line to implicit form in 2D.\n%\n% Discussion:\n%\n% The explicit form of a line in 2D is:\n%\n% ( P1, P2 ) = ( (X1,Y1), (X2,Y2) ).\n%\n% The implicit form of a line in 2D is:\n%\n% A * X + B * Y + C = 0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), two points on the line.\n%\n% Output, real A, B, C, the implicit form of the line.\n%\n\n%\n% Take care of degenerate cases.\n%\n if ( p1(1:2,1) == p2(1:2,1) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_EXP2IMP_2D - Fatal error!\\n' );\n fprintf ( 1, ' P1 = P2\\n' );\n fprintf ( 1, ' P1 = %f %f\\n', p1(1:2,1) );\n fprintf ( 1, ' P2 = %f %f\\n', p2(1:2,1) );\n error ( 'LINE_EXP2IMP_2D - Fatal error!' );\n end\n\n a = p2(2,1) - p1(2,1);\n b = p1(1,1) - p2(1,1);\n c = p2(1,1) * p1(2,1) - p1(1,1) * p2(2,1);\n\n norm = a * a + b * b + c * c;\n\n if ( 0.0 < norm )\n a = a / norm;\n b = b / norm;\n c = c / norm;\n end\n\n if ( a < 0.0 )\n a = -a;\n b = -b;\n c = -c;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/line_exp2imp_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7871326038290085}} {"text": "function A = genWattsStrogotzGraph(N,K,rewireProb)\n%%GENWATTSSTROGOTZGRAPH Generates a random instance of the Watts-Strogotz\n% model as described in [1].\n%\n%INPUT:\n% N: The number of nodes to be used in generating the graph.\n% K: The number of connected neighbors for each node. This must be an even\n% number.\n% rewireProb: The probability that any single edge connecting a given node\n% to its neighbor will be changed to connect to a different\n% node chosen uniformly at random from the set of nodes which\n% do not at that time share an edge with the given node.\n%\n%OUTPUT:\n% A: The adjacency matrix for the final graph.\n%\n%EXAMPLE: Generates an instance of the Watts-Strogotz model.\n% N = 30;\n% K = 4;\n% rewireProb = 0.3;\n% A = genWattsStrogotzGraph(N,K,rewireProb);\n% g = graph(A);\n% plot(g,\"MarkerSize\",degree(g),\"Layout\",\"circle\")\n%\n%REFERENCES:\n%[1] D. J. Watts and S. H. Strogatz, \"Collective dynamics of 'small-world'\n% networks,\" Nature, vol. 393, no. 6684, pp. 440-442, 1998.\n%\n%August 2022 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif mod(K,2)==1\n error('K must be even')\nend\nif rewireProb>1 || rewireProb<0\n error('rewireProb must be in the interval [0,1]')\nend\n\nA = zeros(N);\nfor i = 1:N-1\n for j = i+1:N\n A(i,j) = mod(abs(i-1-(j-1)),N-K/2)<=K/2;\n end\nend\nfor i = 1:N\n for j = i+1:i+K/2\n jNode = mod(j-1,N)+1;\n if rand()0 )\n figure\n subplot(3,1,1)\n postplot(fea,'surfexpr','u','axequal','on')\n title('Solution u')\n subplot(3,1,2)\n postplot(fea,'surfexpr',opt.refsol,'axequal','on')\n title('Exact solution')\n subplot(3,1,3)\n postplot(fea,'surfexpr',s_err,'axequal','on')\n title('Error')\nend\n\n\n% Error checking.\nif ( size(fea.grid.c,1)==4 )\n xi = [0;0];\nelse\n xi = [1/3;1/3;1/3];\nend\nerr = evalexpr0(s_err,xi,1,1:size(fea.grid.c,2),[],fea);\nref = evalexpr0('u',xi,1,1:size(fea.grid.c,2),[],fea);\nerr = sqrt(sum(err.^2)/sum(ref.^2));\n\nif( ~isempty(fid) )\n fprintf(fid,'\\nL2 Error: %f\\n',err)\n fprintf(fid,'\\n\\n')\nend\n\n\nout.err = err;\nout.pass = out.err<5e-3;\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_laplace2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7871141141518891}} {"text": "function z = v_polynomial_zeros ( n )\n\n%*****************************************************************************80\n%\n%% V_POLYNOMIAL_ZEROS returns zeroes of the Chebyshev polynomial V(n,x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the polynomial.\n%\n% Output, real Z(N), the zeroes.\n%\n for i = 1 : n\n angle = ( 2 * n - 2 * i + 1 ) * pi / ( 2 * n + 1 );\n z(i) = 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/chebyshev_polynomial/v_polynomial_zeros.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.7871127681980965}} {"text": "function value = octahedron_unit_volume_nd ( n )\n\n%*****************************************************************************80\n%\n%% OCTAHEDRON_UNIT_VOLUME_ND returns the volume of the unit octahedron in ND.\n%\n% Integration region:\n%\n% Points X(1:N) such that:\n%\n% Sum ( Abs ( X(1:N) ) ) <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 27 November 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the space.\n%\n% Output, real OCTAHEDRON_UNIT_VOLUME_ND, the volume of\n% the unit octahedron.\n%\n value = 2^n / prod ( 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/stroud/octahedron_unit_volume_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7870771184896477}} {"text": "function [Rt]=RateSimCIR(theta,kappa,sigma,lambda,dt,ratestart,months,tau)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CIR term structure simulation, inputs below\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% clear all\n% theta=0.10;\n% kappa=0.05;\n% sigma=0.075;\n% lambda=-0.4;\n% dt=1/12;\n% months=120;\n% ratestart=0.10;\n% tau=[3/12,6/12,2,5];\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Short Rate Dynamics\nrt(1)=ratestart;\nfor i=1:months*4\n rt(i+1)=rt(i)+kappa*(theta-rt(i))*dt/4+sqrt(rt(i))*sigma*sqrt(dt/4)*randn(1);\nend\n% Term Structure Dynamics\nfor i=1:months\n rttemp=rt(i*4-3);\n rttemp1(i)=rt(i*4-3);\n for j=1:numel(tau)\n AffineG=sqrt((kappa+lambda)^2+2*sigma^2); \n AffineB=2*(exp(AffineG*tau(j))-1)/((AffineG+kappa+lambda)...\n *(exp(AffineG*tau(j))-1)+2*AffineG); \n AffineA=2*kappa*theta/(sigma^2)*log(2*AffineG*...\n exp((AffineG+kappa+lambda)*tau(j)/2)/((AffineG+kappa+lambda)*...\n (exp(AffineG*tau(j))-1)+2*AffineG)); \n A(j)=-AffineA/tau(j); \n B(j)=AffineB/tau(j); \n Rt(i,j)=A(j)+B(j)*rttemp;\n end\nend\nRt;\n\n%%%%%%%%%%%%% MAKE THE GRAPH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Rt;\n% figure(2)\n% surf(tau,1:120,Rt)\n% xlabel('Time to Maturity (Fixed)')\n% ylabel('Months Passed')\n% title('A Given Simulation of the Term Structure (CIR)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27704-kalman-filter-application-cir/RateSimCIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394881, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7870569778854961}} {"text": "function pyramid_rule ( legendre_order, jacobi_order, filename )\n\n%*****************************************************************************80\n%\n%% PYRAMID_RULE generates a quadrature rule for a pyramid.\n%\n% Discussion:\n%\n% This program computes a quadrature rule for a pyramid\n% and writes it to a file.\n%\n% The user specifies:\n% * the LEGENDRE_ORDER (number of points in the X and Y dimensions)\n% * the JACOBI_ORDER (number of points in the Z dimension)\n% * FILENAME< the root name of the output files.\n%\n% The integration region is:\n% \n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% When Z is zero, the integration region is a square lying in the (X,Y) \n% plane, centered at (0,0,0) with \"radius\" 1. As Z increases to 1, the \n% radius of the square diminishes, and when Z reaches 1, the square has \n% contracted to the single point (0,0,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 23 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a quadrature rule for approximating\\n' );\n fprintf ( 1, ' the integral of a function over a pyramid.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEGENDRE_ORDER, the order of the Legendre rule for X and Y.\\n' );\n fprintf ( 1, ' JACOBI_ORDER, the order of the Jacobi rule for Z,\\n' );\n fprintf ( 1, ' FILENAME, the prefix for the three output 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 the Legendre order.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n legendre_order = input ( ' Enter the Legendre rule order:' );\n elseif ( ischar ( legendre_order ) )\n legendre_order = str2num ( legendre_order );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The requested Legendre order of the rule is %d.\\n', ...\n legendre_order );\n%\n% Get the Jacobi order.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n jacobi_order = input ( ' Enter the Jacobi rule order:' );\n elseif ( ischar ( jacobi_order ) )\n jacobi_order = str2num ( jacobi_order ); \n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The requested Jacobi order of the rule is %d.\\n', ...\n jacobi_order );\n%\n% Get the output option or quadrature file root name:\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n filename = input ( ' Enter the \"root name\" of the quadrature files).' );\n end\n\n pyramid_handle ( legendre_order, jacobi_order, filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ x, w ] = jacobi_compute ( order, alpha, beta )\n\n%*****************************************************************************80\n%\n%% JACOBI_COMPUTE computes the abscissa and weights for Jacobi quadrature.\n%\n% Discussion:\n%\n% The integration interval is [ -1, 1 ].\n%\n% The weight function is w(x) = (1-X)^ALPHA * (1+X)^BETA.\n%\n% The integral to approximate is:\n%\n% Integral ( -1 <= X <= 1 ) (1-X)^ALPHA * (1+X)^BETA * F(X) dX\n%\n% The quadrature formula is:\n%\n% Sum ( 1 <= I <= ORDER ) W(I) * F ( X(I) )\n%\n% Thanks to Xu Xiang of Fudan University for pointing out that\n% an earlier implementation of this routine was incorrect!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 February 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Arthur Stroud, Don Secrest.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the quadrature rule to be computed.\n%\n% Input, real ALPHA, BETA, the exponents of (1-X) and\n% (1+X) in the quadrature rule. For simple Legendre quadrature,\n% set ALPHA = BETA = 0.0. -1.0 < ALPHA and -1.0 < BETA are required.\n%\n% Output, real X(ORDER), the abscissas.\n%\n% Output, real W(ORDER), the weights.\n%\n if ( order < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_COMPUTE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of ORDER = %d\\n', order );\n error ( 'JACOBI_COMPUTE - Fatal error!' );\n end\n%\n% Check ALPHA and BETA.\n%\n if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_COMPUTE - Fatal error!\\n' );\n fprintf ( 1, ' -1.0 < ALPHA is required.\\n' );\n error ( 'JACOBI_COMPUTE - Fatal error!' );\n end\n\n if ( beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_COMPUTE - Fatal error!\\n' );\n fprintf ( 1, ' -1.0 < BETA is required.\\n' );\n error ( 'JACOBI_COMPUTE - Fatal error!' );\n end\n%\n% Set the recursion coefficients.\n%\n b = zeros ( order, 1 );\n c = zeros ( order, 1 );\n w = zeros ( order, 1 );\n x = zeros ( order, 1 );\n \n for i = 1 : order\n\n if ( alpha + beta == 0.0 || beta - alpha == 0.0 )\n\n b(i) = 0.0;\n\n else\n\n b(i) = ( alpha + beta ) * ( beta - alpha ) / ...\n ( ( alpha + beta + 2 * i ) ...\n * ( alpha + beta + 2 * i - 2 ) );\n\n end\n\n if ( i == 1 )\n\n c(i) = 0.0;\n\n else\n\n c(i) = 4.0 * ( i - 1 ) * ( alpha + i - 1 ) * ( beta + i - 1 ) ...\n * ( alpha + beta + i - 1 ) / ( ( alpha + beta + 2 * i - 1 ) ...\n * ( alpha + beta + 2 * i - 2 )^2 * ( alpha + beta + 2 * i - 3 ) );\n\n end\n\n end\n\n delta = r8_gamma ( alpha + 1.0 ) ...\n * r8_gamma ( beta + 1.0 ) ...\n / r8_gamma ( alpha + beta + 2.0 );\n\n cc = delta * 2.0^( alpha + beta + 1.0 ) * prod ( c(2:order) );\n\n for i = 1 : order\n\n if ( i == 1 )\n\n an = alpha / order;\n bn = beta / order;\n\n r1 = ( 1.0 + alpha ) * ( 2.78 / ( 4.0 + order * order ) ...\n + 0.768 * an / order );\n\n r2 = 1.0 + 1.48 * an + 0.96 * bn + 0.452 * an^2 + 0.83 * an * bn;\n\n x0 = ( r2 - r1 ) / r2;\n\n elseif ( i == 2 )\n\n r1 = ( 4.1 + alpha ) / ...\n ( ( 1.0 + alpha ) * ( 1.0 + 0.156 * alpha ) );\n\n r2 = 1.0 + 0.06 * ( order - 8.0 ) * ( 1.0 + 0.12 * alpha ) / order;\n\n r3 = 1.0 + 0.012 * beta * ...\n ( 1.0 + 0.25 * abs ( alpha ) ) / order;\n\n x0 = x0 - r1 * r2 * r3 * ( 1.0 - x0 );\n\n elseif ( i == 3 )\n\n r1 = ( 1.67 + 0.28 * alpha ) / ( 1.0 + 0.37 * alpha );\n\n r2 = 1.0 + 0.22 * ( order - 8.0 ) / order;\n\n r3 = 1.0 + 8.0 * beta / ( ( 6.28 + beta ) * order * order );\n\n x0 = x0 - r1 * r2 * r3 * ( x(1) - x0 );\n\n elseif ( i < order - 1 )\n\n x0 = 3.0 * x(i-1) - 3.0 * x(i-2) + x(i-3);\n\n elseif ( i == order - 1 )\n\n r1 = ( 1.0 + 0.235 * beta ) / ( 0.766 + 0.119 * beta );\n\n r2 = 1.0 / ( 1.0 + 0.639 * ( order - 4.0 ) ...\n / ( 1.0 + 0.71 * ( order - 4.0 ) ) );\n\n r3 = 1.0 / ( 1.0 + 20.0 * alpha / ( ( 7.5 + alpha ) * order * order ) );\n\n x0 = x0 + r1 * r2 * r3 * ( x0 - x(i-2) );\n\n elseif ( i == order )\n\n r1 = ( 1.0 + 0.37 * beta ) / ( 1.67 + 0.28 * beta );\n\n r2 = 1.0 / ( 1.0 + 0.22 * ( order - 8.0 ) / order );\n\n r3 = 1.0 / ( 1.0 + 8.0 * alpha / ( ( 6.28 + alpha ) * order * order ) );\n\n x0 = x0 + r1 * r2 * r3 * ( x0 - x(i-2) );\n\n end\n\n [ x0, dp2, p1 ] = jacobi_root ( x0, order, alpha, beta, b, c );\n\n x(i) = x0;\n w(i) = cc / ( dp2 * p1 );\n\n end\n%\n% Reverse the order of the values.\n%\n x(1:order) = x(order:-1:1);\n w(1:order) = w(order:-1:1);\n\n return\nend\nfunction [ p2, dp2, p1 ] = jacobi_recur ( x, order, alpha, beta, b, c )\n\n%*****************************************************************************80\n%\n%% JACOBI_RECUR finds the value and derivative of a Jacobi polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Arthur Stroud, Don Secrest.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, real X, the point at which polynomials are evaluated.\n%\n% Input, integer ORDER, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, BETA, the exponents of (1+X) and\n% (1-X) in the quadrature rule.\n%\n% Input, real B(ORDER), C(ORDER), the recursion\n% coefficients.\n%\n% Output, real P2, the value of J(ORDER)(X).\n%\n% Output, real DP2, the value of J'(ORDER)(X).\n%\n% Output, real P1, the value of J(ORDER-1)(X).\n%\n p1 = 1.0;\n dp1 = 0.0;\n\n p2 = x + ( alpha - beta ) / ( alpha + beta + 2.0 );\n dp2 = 1.0;\n\n for i = 2 : order\n\n p0 = p1;\n dp0 = dp1;\n\n p1 = p2;\n dp1 = dp2;\n\n p2 = ( x - b(i) ) * p1 - c(i) * p0;\n dp2 = ( x - b(i) ) * dp1 + p1 - c(i) * dp0;\n\n end\n\n return\nend\nfunction [ x, dp2, p1 ] = jacobi_root ( x, order, alpha, beta, b, c )\n\n%*****************************************************************************80\n%\n%% JACOBI_ROOT improves an approximate root of a Jacobi polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Arthur Stroud, Don Secrest.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, real X, the approximate root.\n%\n% Input, integer ORDER, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, BETA, the exponents of (1+X) and\n% (1-X) in the quadrature rule.\n%\n% Input, real B(ORDER), C(ORDER), the recursion coefficients.\n%\n% Output, real X, the improved approximate root.\n%\n% Output, real DP2, the value of J'(ORDER)(X).\n%\n% Output, real P1, the value of J(ORDER-1)(X).\n%\n maxstep = 10;\n\n eps = r8_epsilon ( );\n\n for i = 1 : maxstep\n\n [ p2, dp2, p1 ] = jacobi_recur ( x, order, alpha, beta, b, c );\n\n d = p2 / dp2;\n x = x - d;\n\n if ( abs ( d ) <= eps * ( abs ( x ) + 1.0 ) )\n return\n end\n\n end\n\n return\nend\nfunction [ x, w ] = legendre_compute ( order )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_COMPUTE computes a Legendre quadrature rule.\n%\n% Discussion:\n%\n% The integration interval is [ -1, 1 ].\n%\n% The weight function is w(x) = 1.0.\n%\n% The integral to approximate:\n%\n% Integral ( -1 <= X <= 1 ) F(X) dX\n%\n% The quadrature rule:\n%\n% Sum ( 1 <= I <= ORDER ) W(I) * F ( X(I) )\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 Philip Davis, Philip Rabinowitz.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n% ORDER must be greater than 0.\n%\n% Output, real X(ORDER), the abscissas of the rule.\n%\n% Output, real W(ORDER), the weights of the rule.\n% The weights are positive, symmetric, and should sum to 2.\n%\n if ( order < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_COMPUTE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of ORDER = %d\\n', order );\n error ( 'LEGENDRE_COMPUTE - Fatal error!' );\n end\n\n w = zeros ( order, 1 );\n x = zeros ( order, 1 );\n \n e1 = order * ( order + 1 );\n\n m = floor ( ( order + 1 ) / 2 );\n\n for i = 1 : floor ( ( order + 1 ) / 2 )\n\n mp1mi = m + 1 - i;\n\n t = ( 4 * i - 1 ) * pi / ( 4 * order + 2 );\n\n x0 = cos(t) * ( 1.0 - ( 1.0 - 1.0 / ( order ) ) / ( 8 * order * order ) );\n\n pkm1 = 1.0;\n pk = x0;\n\n for k = 2 : order\n pkp1 = 2.0 * x0 * pk - pkm1 - ( x0 * pk - pkm1 ) / k;\n pkm1 = pk;\n pk = pkp1;\n end\n\n d1 = order * ( pkm1 - x0 * pk );\n\n dpn = d1 / ( 1.0 - x0 * x0 );\n\n d2pn = ( 2.0 * x0 * dpn - e1 * pk ) / ( 1.0 - x0 * x0 );\n\n d3pn = ( 4.0 * x0 * d2pn + ( 2.0 - e1 ) * dpn ) / ( 1.0 - x0 * x0 );\n\n d4pn = ( 6.0 * x0 * d3pn + ( 6.0 - e1 ) * d2pn ) / ( 1.0 - x0 * x0 );\n\n u = pk / dpn;\n v = d2pn / dpn;\n%\n% Initial approximation H:\n%\n h = - u * ( 1.0 + 0.5 * u * ( v + u * ( v * v - d3pn / ( 3.0 * dpn ) ) ) );\n%\n% Refine H using one step of Newton's method:\n%\n p = pk + h * ( dpn + 0.5 * h * ( d2pn + h / 3.0 ...\n * ( d3pn + 0.25 * h * d4pn ) ) );\n\n dp = dpn + h * ( d2pn + 0.5 * h * ( d3pn + h * d4pn / 3.0 ) );\n\n h = h - p / dp;\n\n xtemp = x0 + h;\n\n x(mp1mi) = xtemp;\n\n fx = d1 - h * e1 * ( pk + 0.5 * h * ( dpn + h / 3.0 ...\n * ( d2pn + 0.25 * h * ( d3pn + 0.2 * h * d4pn ) ) ) );\n\n w(mp1mi) = 2.0 * ( 1.0 - xtemp * xtemp ) / fx / fx;\n\n end\n\n if ( mod ( order, 2 ) == 1 )\n x(1) = 0.0;\n end\n%\n% Shift the data up.\n%\n nmove = floor ( ( order + 1 ) / 2 );\n ncopy = order - nmove;\n\n for i = 1 : nmove\n iback = order + 1 - i;\n x(iback) = x(iback-ncopy);\n w(iback) = w(iback-ncopy);\n end\n%\n% Reflect values for the negative abscissas.\n%\n for i = 1 : order - nmove\n x(i) = - x(order+1-i);\n w(i) = w(order+1-i);\n end\n\n return\nend\nfunction pyramid_handle ( legendre_order, jacobi_order, filename )\n\n%*****************************************************************************80\n%\n%% PYRAMID_HANDLE computes the requested pyramid rule and outputs it.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LEGENDRE_ORDER, JACOBI_ORDER, the orders\n% of the component Legendre and Jacobi rules.\n%\n% Input, string FILENAME, the rootname for the files,\n% write files 'file_w.txt' and 'file_x.txt', and 'file_r.txt', weights,\n% abscissas, and region.\n%\n dim_num = 3;\n%\n% Compute the factor rules.\n%\n [ legendre_x, legendre_w ] = legendre_compute ( legendre_order );\n\n jacobi_alpha = 2.0;\n jacobi_beta = 0.0;\n\n [ jacobi_x, jacobi_w ] = jacobi_compute ( jacobi_order, jacobi_alpha, ...\n jacobi_beta );\n%\n% Compute the pyramid rule.\n%\n pyramid_order = legendre_order * legendre_order * jacobi_order;\n\n volume = 4.0 / 3.0;\n\n pyramid_w = zeros ( pyramid_order, 1 );\n pyramid_x = zeros ( dim_num, pyramid_order );\n \n l = 0;\n for k = 1 : jacobi_order\n xk = ( jacobi_x(k) + 1.0 ) / 2.0;\n wk = jacobi_w(k) / 2.0;\n for j = 1 : legendre_order\n xj = legendre_x(j);\n wj = legendre_w(j);\n for i = 1 : legendre_order\n xi = legendre_x(i);\n wi = legendre_w(i);\n l = l + 1;\n pyramid_w(l) = wi * wj * wk / 4.0 / volume;\n pyramid_x(1,l) = xi * ( 1.0 - xk );\n pyramid_x(2,l) = xj * ( 1.0 - xk );\n pyramid_x(3,l) = xk;\n end\n end\n end\n\n pyramid_r(1:dim_num,1) = [ -1.0, -1.0, 0.0 ]';\n pyramid_r(1:dim_num,2) = [ +1.0, -1.0, 0.0 ]';\n pyramid_r(1:dim_num,3) = [ -1.0, +1.0, 0.0 ]';\n pyramid_r(1:dim_num,4) = [ +1.0, +1.0, 0.0 ]';\n pyramid_r(1:dim_num,5) = [ 0.0, 0.0, 1.0 ]';\n%\n% Write the rule to files.\n%\n filename_w = strcat ( filename, '_w.txt' );\n filename_x = strcat ( filename, '_x.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, pyramid_order, pyramid_w' );\n r8mat_write ( filename_x, dim_num, pyramid_order, pyramid_x );\n r8mat_write ( filename_r, dim_num, 5, pyramid_r );\n\n return\nend\nfunction value = r8_epsilon ( )\n\n%*****************************************************************************80\n%\n%% R8_EPSILON returns the R8 roundoff unit.\n%\n% Discussion:\n%\n% The roundoff unit is a number R which is a power of 2 with the \n% property that, to the precision of the computer's arithmetic,\n% 1 < 1 + R\n% but \n% 1 = ( 1 + R / 2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, the roundoff unit.\n%\n value = eps;\n\n return\nend\nfunction 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% 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 one = 1.0;\n half = 0.5;\n twelve = 12.0;\n two = 2.0;\n zero = 0.0;\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 = one;\n n = 0;\n y = x;\n%\n% Argument is negative.\n%\n if ( y <= zero )\n\n y = - x;\n y1 = floor ( y );\n res = y - y1;\n\n if ( res ~= zero )\n\n if ( y1 ~= floor ( y1 * half ) * two )\n parity = 1;\n end\n\n fact = - pi / sin ( pi * res );\n y = y + one;\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 = one / y;\n else\n res = xinf;\n value = res;\n return\n end\n\n elseif ( y < twelve )\n\n y1 = y;\n%\n% 0.0 < argument < 1.0.\n%\n if ( y < one )\n\n z = y;\n y = y + one;\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 - one;\n\n end\n%\n% Evaluate approximation for 1.0 < argument < 2.0.\n%\n xnum = zero;\n xden = one;\n for i = 1 : 8\n xnum = ( xnum + p(i) ) * z;\n xden = xden * z + q(i);\n end\n\n res = xnum / xden + one;\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 + one;\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 - half ) * 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 ~= one )\n res = fact / res;\n end\n\n value = res;\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 timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n\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/pyramid_rule/pyramid_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.7870550748567992}} {"text": "function lam = line_adj_eigenvalues ( n )\n\n%*****************************************************************************80\n%\n%% LINE_ADJ_EIGENVALUES returns the eigenvalues of the LINE_ADJ 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 the matrix.\n%\n% Output, real LAM(N), the eigenvalues.\n%\n lam = zeros ( n, 1 );\n\n for i = 1 : n\n angle = i * pi / ( n + 1 );\n lam(i) = 2.0 * cos ( angle );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/line_adj_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.7870550586102614}} {"text": "%% Projection onto the intersection of two sets \n% Our goal is to find a point in the intersection of two convex sets C1 and C2.\n% A similar goal is to find the projection of an arbitrary point onto the \n% intersection (or if the intersection is empty, find the point(s) in C1\n% that are as close as possible to C2). In this demo, the intersection\n% of C1 and C2 is a singleton, so the concepts are the same.\n%\n% We assume that we know how to project on the sets C1 and C2 individually,\n% but not onto C1 intersect C2.\n%\n% The basic algorithm to solve this problem is the alternating projection method,\n% first studied by John von Neumann for the case where C1 and C2 are affine\n% spaces. This algorithm can be extended to arbitrary convex sets, although\n% you may not converge to the *projection* of the original point.\n%\n% This algorithm is very simple: starting at some point y, and with x <-- y,\n% we update\n% x <-- Proj_{C1}( Proj_{C2}( x ) )\n% where Proj_{C1} is the projector onto the set C1.\n%\n% Better methods (which actually give you the projection of y onto the intersection)\n% are based on Dykstra's algorithm (not to be confused with the Dijkstra algorithm\n% described here: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm ).\n%\n% Dykstra's algorithm also uses only Proj_{C1} and Proj_{C2}, but with a few\n% intermediate steps. For an overview, see the 2011 book by Raydan:\n% http://www.amazon.com/Alternating-Projection-Methods-Fundamentals-Algorithms/dp/1611971934\n%\n% Another overview of both alternating projection and Dykstra are in the book chapter\n% \"Proximal splitting methods in signal processing\" by P. L. Combettes and J.-C. Pesquet, \n% in the book 'Fixed-Point Algorithms for Inverse Problems in Science and Engineering',\n% (ed.: H. H. Bauschke, R. S. Burachik, P. L. Combettes, V. Elser, D. R. Luke, and \n% H. Wolkowicz, Editors), pp. 185-212. Springer, New York, 2011.\n% The chapter can be downloaded at http://www.ann.jussieu.fr/~plc/prox.pdf\n%\n% The purpose of this demo is to show the above two methods, and also\n% how to formulate this with TFOCS. The advantage of solving this with TFOCS\n% is that we can use an accelerated solver (Nesterov-style) and use large\n% step-sizes and line search (whereas Dykstra has no step-size parameter).\n% In the first example, it is especially apparent that TFOCS avoids\n% the slow convergence that both the alternating projection and Dykstra\n% algorithms suffer from. In the second example, the performance\n% of alternating projections and TFOCS are quite similar.\n\n%% Mathematical formulation\n% For a given point y, and two convex sets C1 and C2, we wish to find\n% the closest point x to y, such that x is in both C1 and C2. We write this\n% as:\n%\n% $$ \\textrm{minimize}_{x\\in C_1 \\cap C_2} \\,\\, \\mu/2||x\\textrm{--}y||_2^2 $$\n%\n% The parameter $\\mu > 0$ is arbitrary and does not affect the answer.\n%\n% This fits naturally into the TFOCS formulation since the primal\n% problem is already strongly convex.\n\n\n\n%% Demo with two polygon sets in 2D that intersect at (0,0)\n% Set the dimension to 2\nN = 2; % 2D is best for visualization\n\n%%\n% Define some 2D polygons\n\nmx = 1;\nx1a = [1;.1];\nx1b = [1;.2];\nxx1 = [0,x1a(1),2*mx,x1b(1)];\nyy1 = [0,x1a(2),2*mx,x1b(2)];\n\n\nx2a = [1;.3];\nx2b = [1;.35];\nxx2 = [0,x2a(1),2*mx,x2b(1)];\nyy2 = [0,x2a(2),2*mx,x2b(2)];\n\n%%\n% The solution is at x = (0,0), so our error function is simple\n\nerr = @(x) norm(x);\n%%\n% plot the regions\n\nfigure\nred = [255,153,153]/255;\nblue = [204,204,255]/255;\nfill( xx1, yy1,red); \nhold on\nfill( xx2, yy2,blue); \n\nxlim( [0,mx] ); ylim( [0,.5*mx] ); \naxis equal\ntext(.5,.07,'set C1');\ntext(.5,.22,'set C2');\n\n%%\n% Make some operators that will be used with TFOCS\n\naddpath ~/Dropbox/TFOCS/ % modify this to wherever it is installed on your computer\nop1 = project2DCone(x1a, x1b );\nop2 = project2DCone(x2a, x2b );\n\noffset1 = 0;\noffset2 = 0;\nop1_d = prox_dualize(op1);\nop2_d = prox_dualize(op2);\n\n% and some simpler operators that we will use with alternating projections\n% and with Dykstra\nproj1 = @(x) callandmap( op1, 2, x, 1); % gamma is irrelevant\nproj2 = @(x) callandmap( op2, 2, x, 1 ); % gamma is irrelevant\n\n% for all methods, we need to specify a starting point\n\nx0 = [1; 1/4];\n\n\n%% solve in TFOCS\n% We can pick any mu and should get the same result, although due to \n% some scaling issues in stopping criteria, it does have a small effect.\nmu = 1e-6; \n\nopts = struct('debug',false,'printEvery',20,'maxIts',200);\nopts.errFcn{1} = @(f,d,x) err(x);\nopts.errFcn{2} = @(f,d,x) recordPoints(x);\nrecordPoints(); % zero-out counter. We use this to plot the points later\n\nopts.tol = 1e-15;\n\naffineOperator = {eye(N),offset1;eye(N),offset2};\ndualProx = {op1_d,op2_d};\n% Solve in TFOCS:\n[x,out,optsOut] = tfocs_SCD( [], affineOperator, dualProx , mu, x0, [], opts );\n\n% Record the path:\npath = recordPoints();\npath = [x0,path];\n\nfigure\nsubplot(1,2,1);\nfill( xx1, yy1,red); \nhold on\nfill( xx2, yy2,blue); \nxlim( [0,mx] ); ylim( [0,.5*mx] ); \ntext(.5,.07,'set C1');\ntext(.5,.22,'set C2');\nplot( path(1,:), path(2,:),'ko-','linewidth',2 )\ntitle('Path for TFOCS solving the intersection of 2 polygons');\n\nsubplot(1,2,2);\nsemilogy( out.err(:,1) ,'o-'); xlabel('iterations'); ylabel('error');\ntitle('Error for TFOCS method');\nset(gcf, 'Position', [400 200 800 400]);\n%% solve via alternating projection method\nmaxIts = 500;\nx = x0;\npath = [x0];\nerrHist = [];\nfor k = 1:maxIts\n % basic alternating projection method:\n x = proj1(x);\n path= [path, x];\n x = proj2(x);\n path= [path, x];\n errHist = [ errHist; err(x) ];\n if ~mod(k,50)\n fprintf('Iter %4d, error is %.2e\\n', k, errHist(end) );\n end\nend\nfigure\nsubplot(1,2,1);\nfill( xx1, yy1,red); \nhold on\nfill( xx2, yy2,blue); \nxlim( [0,mx] ); ylim( [0,.5*mx] ); \ntext(.5,.07,'set C1');\ntext(.5,.22,'set C2');\nplot( path(1,:), path(2,:),'ko-','linewidth',1 )\ntitle('Path for alternating projection method solving the intersection of 2 polygons');\n\nsubplot(1,2,2);\nsemilogy( errHist, 'o-' ); xlabel('iterations'); ylabel('error');\nerrHist_1 = errHist;\ntitle('Error for alternating projection method');\nset(gcf, 'Position', [400 200 800 400]);\n%% solve via Dykstra's algorithm\n\nmaxIts = 500;\nx = x0;\n[p,q] = deal( 0*x0 );\np = -.25*[1;1];\npath = [x0];\nerrHist = [];\nfor k = 1:maxIts\n % If x + p is feasible, the y = (x+p), so p=x+p-y = 0.\n y = proj1( x + p );\n p = x + p - y;\n x = proj2( y + q );\n q = y + q - x;\n path = [path,y,x];\n errHist = [ errHist; err(x) ];\n if ~mod(k,50)\n fprintf('Iter %4d, error is %.2e\\n', k, errHist(end) );\n end\nend\nfigure\nsubplot(1,2,1);\nfill( xx1, yy1,red); \nhold on\nfill( xx2, yy2,blue); \nxlim( [0,mx] ); ylim( [0,.5*mx] ); \ntext(.5,.07,'set C1');\ntext(.5,.22,'set C2');\nplot( path(1,:), path(2,:),'ko-' )\ntitle('Path for Dykstra''s algo solving the intersection of 2 polygons');\n\nsubplot(1,2,2);\nsemilogy( errHist, 'o-' ); xlabel('iterations'); ylabel('error');\ntitle('Error for Dykstra''s method');\nset(gcf, 'Position', [400 200 800 400]);\n\n%%\n% With Dykstra's algo (and alternating projections), we get\n% very slow convergence, because of the very low angle between the\n% two sets. Here is a zoom in on the graph of the iterates:\nfigure\nfill( xx1, yy1,red); \nhold on\nfill( xx2, yy2,blue); \nxlim( [0,mx] ); ylim( [0,.5*mx] ); \ntext(.5,.07,'set C1');\ntext(.5,.22,'set C2');\nplot( path(1,:), path(2,:),'ko-' )\ntitle('Path for Dykstra''s algo solving the intersection of 2 polygons (zoom)');\nxlim( [.25,.4] );\nylim( [.058,.1])\n%% Plot all the errors together\nfigure\nsemilogy( out.err(:,1),'-' ,'linewidth',3);\nhold all\nsemilogy( errHist_1,'-','linewidth',3);\nsemilogy( errHist,'--','linewidth',3);\nlegend('TFOCS','Alternating projection','Dykstra');\nxlabel('iteration'); ylabel('error');\n%% Demo with two circles that intersect at (0,0)\ncenter1 = [0;.5];\nradius1 = .5;\ncenter2 = -center1;\nradius2 = radius1;\n\nfigure\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\naxis equal\nhold on\ntext(0,.5,'set C1');\ntext(0,-.5,'set C2');\n\n\noffset1 = center1;\noffset2 = center2;\n\nop1_d = prox_l2(radius1);\nop2_d = prox_l2(radius2);\nx0 = [1; .2];\n\n% and some simpler operators that we will use with alternating projections\n% and with Dykstra\nproj1 = @(x) radius1*(x-center1)/norm(x-center1) + center1;\nproj2 = @(x) radius2*(x-center2)/norm(x-center2) + center2;\n%% solve in TFOCS\nopts.maxIts = 300;\naffineOperator = {eye(N),offset1;eye(N),offset2};\ndualProx = {op1_d,op2_d};\n% Solve in TFOCS:\n[x,out,optsOut] = tfocs_SCD( [], affineOperator, dualProx , mu, x0, [], opts );\n\n% Record the path:\npath = recordPoints();\npath = [x0,path];\n% Plot:\nfigure\nsubplot(1,3,1);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\ntext(0,.5,'set C1');\ntext(0,-.5,'set C2');\nplot( path(1,:), path(2,:),'ko-','linewidth',2 )\ntitle('Path for TFOCS solving the intersection of 2 circles');\n\nsubplot(1,3,2);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\nplot( path(1,:), path(2,:),'ko-','linewidth',2 )\nxlim([0,.15]);\nylim([-.1,.1]);\ntitle('(zoom)');\n\nsubplot(1,3,3);\nsemilogy( out.err,'o-')\ntitle('Error of iterates for TFOCS method');\nset(gcf, 'Position', [400 200 800 400]);\n%% solve via alternating projection method\nmaxIts = 300;\nx = x0;\npath = [x0];\nerrHist = [];\nfor k = 1:maxIts\n % basic alternating projection method:\n x = proj1(x);\n path= [path, x];\n x = proj2(x);\n path= [path, x];\n errHist = [ errHist; err(x) ];\n if ~mod(k,50)\n fprintf('Iter %4d, error is %.2e\\n', k, errHist(end) );\n end\nend\nfigure\nsubplot(1,3,1);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\ntext(0,.5,'set C1');\ntext(0,-.5,'set C2');\nplot( path(1,:), path(2,:),'ko-' )\ntitle('Path for alternating projection method solving the intersection of 2 circles');\n\nsubplot(1,3,2);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\nplot( path(1,:), path(2,:),'ko-','linewidth',2 )\nxlim([0,.15]);\nylim([-.1,.1]);\ntitle('(zoom)');\n\nsubplot(1,3,3);\nsemilogy( errHist,'o-')\nerrHist_1 = errHist;\ntitle('Error of iterates for alternating projection method');\nset(gcf, 'Position', [400 200 800 400]);\n%% solve via Dykstra's algorithm\n\nmaxIts = 300;\nx = x0;\n[p,q] = deal( 0*x0 );\npath = [x0];\nerrHist = [];\nfor k = 1:maxIts\n % If x + p is feasible, the y = (x+p), so p=x+p-y = 0.\n y = proj1( x + p );\n p = x + p - y;\n x = proj2( y + q );\n q = y + q - x;\n path = [path,y];\n path = [path,x];\n errHist = [ errHist; err(x) ];\n if ~mod(k,50)\n fprintf('Iter %4d, error is %.2e\\n', k, errHist(end) );\n end\nend\nfigure\nsubplot(1,3,1);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\ntext(0,.5,'set C1');\ntext(0,-.5,'set C2');\nplot( path(1,:), path(2,:),'ko-' )\ntitle('Path for Dykstra''s algo solving the intersection of 2 circles');\n\nsubplot(1,3,2);\nrectangle('Position',[-radius1,0,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',red)\nrectangle('Position',[-radius1,-2*radius2,2*radius1,2*radius1],'Curvature',[1,1],'FaceColor',blue)\nhold on\nplot( path(1,:), path(2,:),'ko-','linewidth',2 )\nxlim([0,.15]);\nylim([-.1,.1]);\ntitle('(zoom)');\n\nsubplot(1,3,3);\nsemilogy( errHist,'o-')\ntitle('Error of iterates for Dykstra''s algo');\nset(gcf, 'Position', [400 200 800 400]);\n\n%% Plot all the errors together\nfigure\nsemilogy( out.err(:,1),'-' ,'linewidth',3);\nhold all\nsemilogy( errHist_1,'-','linewidth',3);\nsemilogy( errHist,'--','linewidth',3);\nlegend('TFOCS','Alternating projection','Dykstra');\nxlabel('iteration'); ylabel('error');\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/demos/demo_alternatingProjections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7869589100540775}} {"text": "function j = jacobi_symbol ( q, p )\n\n%*****************************************************************************80\n%\n%% JACOBI_SYMBOL evaluates the Jacobi symbol (Q/P).\n%\n% Definition:\n%\n% If P is prime, then\n%\n% Jacobi Symbol (Q/P) = Legendre Symbol (Q/P)\n%\n% Else \n%\n% let P have the prime factorization\n%\n% P = Product ( 1 <= I <= N ) P(I)^E(I)\n%\n% Jacobi Symbol (Q/P) =\n%\n% Product ( 1 <= I <= N ) Legendre Symbol (Q/P(I))^E(I)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996, pages 86-87.\n%\n% Parameters:\n%\n% Input, integer Q, an integer whose Jacobi symbol with\n% respect to P is desired.\n%\n% Input, integer P, the number with respect to which the Jacobi\n% symbol of Q is desired. P should be 2 or greater.\n%\n% Output, integer J, the Jacobi symbol (Q/P).\n% Ordinarily, J will be -1, 0 or 1.\n% -2, not enough factorization space.\n% -3, an error during Legendre symbol calculation.\n%\n\n%\n% P must be greater than 1.\n%\n if ( p <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' P must be greater than 1.\\n' );\n j = -2;\n return\n end\n%\n% Decompose P into factors of prime powers.\n%\n [ nfactor, factor, power, nleft ] = i4_factor ( p );\n\n if ( nleft ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' Not enough factorization space.\\n' );\n j = -2;\n error ( 'JACOBI_SYMBOL - Fatal error!' );\n end\n%\n% Force Q to be nonnegative.\n%\n qq = q;\n\n while ( qq < 0 )\n qq = qq + p;\n end\n%\n% For each prime factor, compute the Legendre symbol, and\n% multiply the Jacobi symbol by the appropriate factor.\n%\n j = 1;\n for i = 1 : nfactor\n pp = factor(i);\n l = legendre_symbol ( qq, pp );\n if ( l < -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' Error during Legendre symbol calculation.\\n' );\n j = -3;\n error ( 'JACOBI_SYMBOL - Fatal error!' );\n end\n j = j * l^power(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/polpak/jacobi_symbol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8824278556326343, "lm_q1q2_score": 0.7869588983057794}} {"text": "% Exercise 4.31: Design of a cantilever beam (GP)\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Almir Mutapcic - 01/30/06\n% Updated to use GP mode 02/08/06\n% (a figure is generated)\n%\n% We have a segmented cantilever beam with N segments. Each segment\n% has a unit length and variable width and height (rectangular profile).\n% The goal is minimize the total volume of the beam, over all segment\n% widths w_i and heights h_i, subject to constraints on aspect ratios,\n% maximum allowable stress in the material, vertical deflection y, etc.\n%\n% The problem can be posed as a geometric program (posynomial form)\n% minimize sum( w_i* h_i)\n% s.t. w_min <= w_i <= w_max, for all i = 1,...,N\n% h_min <= h_i <= h_max\n% S_min <= h_i/w_i <= S_max\n% 6*i*F/(w_i*h_i^2) <= sigma_max\n% 6*F/(E*w_i*h_i^3) == d_i\n% (2*i - 1)*d_i + v_(i+1) <= v_i\n% (i - 1/3)*d_i + v_(i+1) + y_(i+1) <= y_i\n% y_1 <= y_max\n%\n% with variables w_i, h_i, d_i, (i = 1,...,N) and v_i, y_i (i = 1,...,N+1).\n% (Consult the book for other definitions and a recursive formulation of\n% this problem.)\n\n% optimization variables\nN = 8;\n\n% constants\nwmin = .1; wmax = 100;\nhmin = .1; hmax = 6;\nSmin = 1/5; Smax = 5;\nsigma_max = 1;\nymax = 10;\nE = 1; F = 1;\n\ncvx_begin gp\n % optimization variables\n variables w(N) h(N) v(N+1) y(N+1);\n\n % objective is the total volume of the beam\n % obj = sum of (widths*heights*lengths) over each section\n % (recall that the length of each segment is set to be 1)\n minimize( w'*h )\n subject to\n % non-recursive formulation\n d = 6*F*ones(N,1)./(E*ones(N,1).*w.*h.^3);\n for i = 1:N\n (2*i-1)*d(i) + v(i+1) <= v(i); %#ok\n (i-1/3)*d(i) + v(i+1) + y(i+1) <= y(i); %#ok\n end\n\n % constraint set\n wmin <= w <= wmax; %#ok\n hmin <= h <= hmax; %#ok\n Smin <= h./w <= Smax; %#ok\n 6*F*[1:N]'./(w.*(h.^2)) <= sigma_max; %#ok\n y(1) <= ymax; %#ok\ncvx_end\n\n% display results\ndisp('The optimal widths and heights are: ');\nw, h\nfprintf('The optimal minimum volume of the beam is %3.4f.\\n', sum(w.*h));\n\n% plot the 3D model of the optimal cantilever beam\nfigure, clf\ncantilever_beam_plot([h; w])\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch04_cvx_opt_probs/cantilever_beam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7869165502094237}} {"text": "function d = sqdist(x, y)\n% L2 dist from x to y\n% x: [1 x d]\n% y: [n x d]\n% d: [n x 1]\n\nd = sqrt(sum((repmat(x, size(y,1), 1) - y).^2, 2));\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/sqdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7868927830312171}} {"text": "function [A,b,x] = foxgood(n)\n%FOXGOOD Test problem: severely ill-posed problem.\n%\n% [A,b,x] = foxgood(n)\n%\n% This is a model problem which does not satisfy the\n% discrete Picard condition for the small singular values.\n% The problem was first used by Fox & Goodwin.\n\n% Reference: C. T. H. Baker, \"The Numerical Treatment of\n% Integral Equations\", Clarendon Press, Oxford, 1977; p. 665.\n\n% Discretized by simple quadrature (midpoint rule).\n\n% Per Christian Hansen, IMM, 03/16/93.\n\n% Initialization.\nh = 1/n; t = h*((1:n)' - 0.5);\n\nA = h*sqrt((t.^2)*ones(1,n) + ones(n,1)*(t.^2)');\nx = t; b = ((1+t.^2).^1.5 - t.^3)/3;\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/regu/regu/foxgood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7868927720486605}} {"text": "function [ f, g, H ] = opt12_fgh ( x, flag )\n\n%*****************************************************************************80\n%\n%% OPT12_FGH evaluates F, G and H for test case #2.\n%\n% Discussion:\n%\n% This is the Beale function.\n%\n% Suggested initial values for X include:\n%\n% X init = ( 1, 1 )\n%\n% X init = ( 1, 4 ) (may have trouble converging)\n%\n% The optimizing value is\n%\n% X* = ( 3.0, 0.5 )\n%\n% and the optimal function value is\n%\n% F(X*) = 0.\n%\n% Modified:\n%\n% 28 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Evelyn Beale,\n% On an Iterative Method for Finding a Local Minimum of a Function\n% of More than One Variable,\n% Technical Report 25, \n% Statistical Techniques Research Group,\n% Princeton University, 1958.\n%\n% Richard Brent,\n% Algorithms for Minimization with Derivatives,\n% Dover, 2002,\n% ISBN: 0-486-41998-3,\n% LC: QA402.5.B74.\n%\n% Parameters:\n%\n% Input, real X(2), the evaluation point.\n%\n% Input, string FLAG, indicates what must be computed.\n% 'f' means only the value of F is needed,\n% 'g' means only the value of G is needed,\n% 'all' means F, G and H (if appropriate) are needed.\n% It is acceptable to behave as though FLAG was 'all'\n% on every call.\n%\n% Output, real F, the optimization function.\n%\n% Output, real G(2,1), the gradient column vector.\n%\n% Output, real H(2,2), the Hessian matrix.\n%\n n = length ( x );\n\n if ( n ~= 2 )\n fprintf ( '\\n' );\n fprintf ( 'OPT12_FGH - Fatal error!\\n' );\n fprintf ( ' The input vector X should have length 2.\\n'), \n fprintf ( ' Instead, it has length = %d.\\n', n );\n keyboard\n end\n\n f1 = 1.5 - x(1) * ( 1.0 - x(2) );\n f2 = 2.25 - x(1) * ( 1.0 - x(2) * x(2) );\n f3 = 2.625 - x(1) * ( 1.0 - x(2) * x(2) * x(2) );\n\n f = f1 * f1 + f2 * f2 + f3 * f3;\n\n df1dx1 = - ( 1.0 - x(2) );\n df1dx2 = x(1);\n df2dx1 = - ( 1.0 - x(2) * x(2) );\n df2dx2 = 2.0 * x(1) * x(2);\n df3dx1 = - ( 1.0 - x(2) * x(2) * x(2) );\n df3dx2 = 3.0 * x(1) * x(2) * x(2);\n\n g(1,1) = 2.0 * ( f1 * df1dx1 + f2 * df2dx1 + f3 * df3dx1 );\n g(2,1) = 2.0 * ( f1 * df1dx2 + f2 * df2dx2 + f3 * df3dx2 );\n\n d2f1dx12 = 1.0;\n d2f1dx21 = 1.0;\n \n d2f2dx12 = 2.0 * x(2);\n d2f2dx21 = 2.0 * x(2);\n d2f2dx22 = 2.0 * x(1);\n\n d2f3dx12 = 3.0 * x(2) * x(2);\n d2f3dx21 = 3.0 * x(2) * x(2);\n d2f3dx22 = 6.0 * x(1) * x(2);\n\n H(1,1) = 2.0 * ( df1dx1 * df1dx1 ...\n + df2dx1 * df2dx1 ...\n + df3dx1 * df3dx1 );\n\n H(1,2) = 2.0 * ( df1dx2 * df1dx1 + f1 * d2f1dx12 ...\n + df2dx2 * df2dx1 + f2 * d2f2dx12 ...\n + df3dx2 * df3dx1 + f3 * d2f3dx12 );\n\n H(2,1) = 2.0 * ( df1dx1 * df1dx2 + f1 * d2f1dx21 ...\n + df2dx1 * df2dx2 + f2 * d2f2dx21 ...\n + df3dx1 * df3dx2 + f3 * d2f3dx21 );\n\n H(2,2) = 2.0 * ( df1dx2 * df1dx2 ...\n + df2dx2 * df2dx2 + f2 * d2f2dx22 ...\n + df3dx2 * df3dx2 + f3 * d2f3dx22 );\n", "meta": {"author": "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/opt12_fgh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7868329604083885}} {"text": "clear all; close all; clc\n\nn=200; L=8;\nx=linspace(0,L,n);\nx1=x(1:100); % train\nx2=x(101:200); % test\nn1=length(x1);\nn2=length(x2);\nftrain=(x1.^2).'; % train parabola x=[0,4]\nftest=(x2.^2).'; % test parbola x=[4,5]\nfigure(1), subplot(3,1,1),\nplot(x1,ftrain,'r',x2,ftest,'b','Linewidth',[2])\nlegend('','','Location','Northwest')\nlegend boxoff\n\nM=30; % number of model terms\nEni=zeros(100,M); Ene=zeros(100,M);\nfor jj=1:M\n for j=1:jj\n phi_i(:,j)=(x1.').^(j-1); % interpolation key\n phi_e(:,j)=(x2.').^(j-1); % extrapolation key\n end\n \n f=(x.^2).';\n for j=1:100\n fni=(x1.^2+0.1*randn(1,n1)).'; % interpolation\n fne=(x2.^2+0.1*randn(1,n2)).'; % extrapolation\n \n ani=pinv(phi_i)*fni; fnai=phi_i*ani;\n Eni(j,jj)=norm(ftrain-fnai)/norm(ftrain);\n \n fnae=phi_e*ani; % use loadings from x in [0,4]\n Ene(j,jj)=norm(ftest-fnae)/norm(ftest);\n end\nend\n\nsubplot(3,2,3), boxplot(Eni), axis([0.5 30.5 0 0.7]), set(gca,'Xlim',[0.5 30.5],'Xtick',1:30,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20','','','','','25','','','','','30'})\nsubplot(3,2,4), boxplot(Eni), axis([0.5 30.5 0 0.02]), set(gca,'Xlim',[0.5 30.5],'Xtick',1:30,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20','','','','','25','','','','','30'})\nsubplot(3,2,5), boxplot(Ene), set(gca,'Xlim',[0.5 30.5],'Xtick',1:30,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20','','','','','25','','','','','30'})\nsubplot(3,2,6), boxplot(log(Ene+1)), axis([0.5 30.5 0 30]), set(gca,'Xtick',1:30,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20','','','','','25','','','','','30'})\n\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH04/CH04_SEC05_1_CrossValidate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7868329579260265}} {"text": "function [dmodedr, dmodeds] = GradSimplex2DP(a,b,id,jd)\n\n% function [dmodedr, dmodeds] = GradSimplex2DP(a,b,id,jd)\n% Purpose: Return the derivatives of the modal basis (id,jd) on the 2D simplex at (a,b). \n\nfa = JacobiP(a, 0, 0, id); dfa = GradJacobiP(a, 0, 0, id);\ngb = JacobiP(b, 2*id+1,0, jd); dgb = GradJacobiP(b, 2*id+1,0, jd);\n\n% r-derivative\n% d/dr = da/dr d/da + db/dr d/db = (2/(1-s)) d/da = (2/(1-b)) d/da\ndmodedr = dfa.*gb;\nif(id>0)\n dmodedr = dmodedr.*((0.5*(1-b)).^(id-1));\nend\n\n% s-derivative\n% d/ds = ((1+a)/2)/((1-b)/2) d/da + d/db\ndmodeds = dfa.*(gb.*(0.5*(1+a)));\nif(id>0)\n dmodeds = dmodeds.*((0.5*(1-b)).^(id-1));\nend\n\ntmp = dgb.*((0.5*(1-b)).^id);\nif(id>0)\n tmp = tmp-0.5*id*gb.*((0.5*(1-b)).^(id-1));\nend\ndmodeds = dmodeds+fa.*tmp;\n\n% Normalize\ndmodedr = 2^(id+0.5)*dmodedr; dmodeds = 2^(id+0.5)*dmodeds;\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/GradSimplex2DP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7868058014349282}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1) %'\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters. \n% You should set p to a vector of 0's and 1's\n%\n\n\np = round(sigmoid(X * theta));\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "gopaczewski", "repo": "coursera-ml", "sha": "9f68b71ac6b65bfd7cea32c7c22b4abd40401579", "save_path": "github-repos/MATLAB/gopaczewski-coursera-ml", "path": "github-repos/MATLAB/gopaczewski-coursera-ml/coursera-ml-9f68b71ac6b65bfd7cea32c7c22b4abd40401579/mlclass-ex2-005/mlclass-ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7867881494143348}} {"text": "function y = coshminus1(x)\n%COSHMINUS1 Hyperbolic cosine minus one.\n%\n% COSHMINUS1(X) is COSH(X)-1 calculated in a way that is numerically better\n% when X is close zero.\n%\n% This illustrates the difference\n%\n% x = 5e-8*(-1:0.01:1);\n% plot(x, cosh(x)-1, 'b-', x, coshminus1(x), 'r-');\n%\n% See also ACOSHPLUS1.\n\n% Author: Peter J. Acklam\n% Time-stamp: 2003-10-13 14:57:06 +0200\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n % check number of input arguments\n error(nargchk(1, 1, nargin));\n\n y = 2 * sinh(x / 2).^2;\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/coshminus1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.786788144231077}} {"text": "function fx = p10_fx ( x )\n\n%*****************************************************************************80\n%\n%% P10_FX evaluates the Repeller.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(*), the point at which F is to be evaluated.\n%\n% Output, real FX(*), the value of the function at X.\n%\n fx = 20.0 * x ./ ( 100.0 * x .* x + 1.0 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_zero/p10_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7867049161631394}} {"text": "function [ bvec3, overflow ] = bvec_add ( n, bvec1, bvec2 )\n\n%*****************************************************************************80\n%\n%% BVEC_ADD adds two binary vectors.\n%\n% Discussion:\n%\n% A BVEC is an integer vector of binary digits, intended to\n% represent an integer. BVEC(1) is the units digit, BVEC(N-1)\n% is the coefficient of 2**(N-2), and BVEC(N) contains sign\n% information. It is 0 if the number is positive, and 1 if\n% the number is negative.\n%\n% Example:\n%\n% N = 4\n%\n% BVEC1 dec BVEC2 dec BVEC3 dec\n% ------- --- ------- --- ------- ---\n% 1 0 0 0 1 1 1 0 0 3 0 0 1 0 4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the length of the vectors.\n%\n% Input, integer BVEC1(N), BVEC2(N), the vectors to be added.\n%\n% Output, integer BVEC3(N), the sum of the two input vectors.\n%\n% Output, logical OVERFLOW, is true if the sum overflows.\n%\n base = 2;\n overflow = 0;\n\n bvec3(1:n) = floor ( bvec1(1:n) ) + floor ( bvec2(1:n) );\n\n for i = 1 : n\n while ( base <= bvec3(i) )\n bvec3(i) = bvec3(i) - base;\n if ( i < n )\n bvec3(i+1) = bvec3(i+1) + 1;\n else\n overflow = 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/bvec/bvec_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8670357735451835, "lm_q1q2_score": 0.7866721450022741}} {"text": "% Compute the values of parameter theta (controlling sparsity) that should\n% be expected to give each sparsity level. Return upper and lower bounds \n% each sparsity level k=[1, ..., n-1] neighbors/node.\n%\n% USAGE: [theta_l, theta_u, Z_sorted] = gsp_compute_theta_bounds(Z)\n% gsp_compute_theta_bounds(Z, geom_mean)\n% gsp_compute_theta_bounds(Z, geom_mean, is_sorted)\n% \n% geom_mean: use geometric mean instead of arithmetic mean? default: 0\n% is_sorted: is Z already sorted? default: 0\n%\n%\n%\n% \n%\n% code author: Vassilis Kalofolias\n% date: Aug 2016\n\n\nfunction [theta_l, theta_u, Z_sorted] = gsp_compute_theta_bounds(Z, geom_mean, is_sorted)\n\nif nargin < 2 || isempty(geom_mean)\n geom_mean = 0;\nend\n\nif nargin < 3\n is_sorted = 0;\nend\n\n% Z is the zero-diagonal pairwise distance matrix between nodes\n\n\nif ismatrix(Z)\n \n if is_sorted\n Z_sorted = Z;\n else\n n = length(Z);\n % don't take into account the diagonal of Z\n Z_sorted = zeros(n, n-1);\n for i=1:n\n Z_sorted(i, :) = sort(Z(i, [1:i-1, i+1:n]), 2, 'ascend');\n end\n end\n [m, n] = size(Z_sorted);\n \n B_k = cumsum(Z_sorted, 2); % cummulative sum for each row\n K_mat = repmat((1:n), m, 1);\n\n %% Theoretical intervals of theta for each desired sparsity level:\n if geom_mean == 0\n theta_u = mean(1./sqrt(K_mat.*Z_sorted.^2 - B_k.*Z_sorted));\n else\n % try geometric mean instead of arithmetic:\n theta_u = exp(mean(log(1./sqrt(K_mat.*Z_sorted.^2 - B_k.*Z_sorted))));\n end \n theta_l = [theta_u(2:end), 0];\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/utils/gsp_compute_theta_bounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7865978087867603}} {"text": "fprintf('METODO NEWTON-RAPHSON\\n'); \t\t\t%TITULO\nsyms f(x) %crea una variable simbolica \nf(x)=input('Ingrese la funcion: '); \t\t% se ingresara la funcion\nr0=input('ingrese la primera aproximacion: '); \t%se ingresa el primer punto o raiz\ntol=input('Ingrese la tolerancia: '); \t%valor del error minimo aceptable\nn=input('Ingrese numero maximo de iteraciones: '); \t%hasta cuantas iteraciones \ndf=diff(f,x); %derivada de f(x)\nerror=100; %para ingresar al while\ni=0; %contador\nri=r0;\nfprintf('iteraciones\\t\\t\\t\\tri\\t\\t\\t\\t\\tri+1\\t\\t\\t\\terror\\n'); \t%el encabezado a imprimir\nfprintf('%i\\t\\t\\t\\t%4.11f\\t\\t\\t\\t---------\\t\\t\\t\\t-----------\\n',i,r0); %imprime nuestros datos inciales\nwhile(error>=tol && i<=n)\n i=i+1;\n rim1=ri-(f(ri)/df(ri)); %hallamos la nueva raiz\n error=abs(((ri-rim1)/rim1)*100); \t\t\t\t%hallamos el error al tratar de encontrar la raiz\n fprintf('%i\\t\\t\\t\\t%4.11f\\t\\t\\t\\t%4.11f\\t\\t\\t\\t%4.11f\\n',i,r0,rim1,error); %se imprimen los valores hallados por el metodo newton\n ri=rim1; \t\t\t\t\t\t\t\t%en caso no termine el bucle se vuelve a repetir con una nueva raiz\nend\nfprintf('La raiz es %4.11f y el error es %4.11f\\n',rim1,error); \t%se imprimen los datos finales", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/projects/antimisiles_3/Proceso/newtonsistema2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.786594344414902}} {"text": "function [ x, w ] = ncoh_compute ( n )\n\n%*****************************************************************************80\n%\n%% NCOH_COMPUTE computes a Newton-Cotes \"open half\" quadrature rule.\n%\n% Discussion:\n%\n% The input value N is used to define N equal subintervals of [-1,+1].\n% The I-th abscissa is the center of the I-th subinterval.\n%\n% The integral:\n%\n% Integral ( X_MIN <= X <= X_MAX ) 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% 03 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n x = zeros ( n, 1 );\n\n x_min = -1.0;\n x_max = 1.0;\n\n for i = 1 : n\n x(i) = ( ( 2 * n - 2 * i + 1 ) * x_min ...\n + ( 2 * i - 1 ) * x_max ) ...\n / ( 2 * n );\n end\n\n w = nc_compute ( n, x_min, x_max, x );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/ncoh_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7865071890090226}} {"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 = getGradientNodal(omega,m);\n% \n% Builds the gradient operator B for a domain defined by omega\n% and a nodal grid discretization defined by m:\n%\n% \n% EXAMPLE FOR 2D:\n%\n% o--x--o--x--o--x--o \n% | | | | \n% + + + + \n% | | | | \n% o--x--o--x--o--x--o \n% | | | | WHERE:\n% + + + + 'o' - uc (nodal)\n% | | | | 'x' - d_1 uc (staggered-2)\n% o--x--o--x--o--x--o '+' - d_2 uc (staggered-1)\n%\n% Note: the matrices are simple, it is size that matters. \n% =============================================================================\n\nfunction B = getGradientNodal(omega,m)\nif nargin == 0,\n help(mfilename);\n runMinimalExample;\n return;\nend;\n\nh = (omega(2:2:end)-omega(1:2:end))./m;\ndim = size(omega,2)/2;\nid = @(i) speye(m(i)+1); % (m(i)+1) identity matrix\n % short difference operator\ndx = @(i) spdiags(ones(m(i),1)*[-1,1],[0,1],m(i),m(i)+1)/h(i); \nswitch dim \n case 2\n B = [kron(id(2),dx(1));kron(dx(2),id(1))];\n z = sparse(size(B,1),size(B,2));\n B = sparse([B z; z B]);\n case 3\n B = [\n kron(id(3),kron(id(2),dx(1)))\n kron(id(3),kron(dx(2),id(1)))\n kron(dx(3),kron(id(2),id(1)))\n ];\n z = sparse(size(B,1),size(B,2));\n B = sparse([B z z; z B z; z z B]);\n otherwise\n error('Dimension must be either 2 or 3.')\nend\n%------------------------------------------------------------------------------\nfunction runMinimalExample\n\n% 2D\nomega = [0,3,0,5]; m = [10,13];\nB2 = getGradientNodal(omega,m);\nfigure(1); clf;\nsubplot(1,2,1)\nspy(B2); \ntitle(sprintf('%s matrix (2D)',mfilename));\n\n\n% 3D\nomega = [0,1,0,2,0,3]; m = [4,5,6];\nB2 = getGradientNodal(omega,m);\nsubplot(1,2,2);\nspy(B2); \ntitle(sprintf('%s matrix (3D)',mfilename));\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/getGradientNodal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.786418790889795}} {"text": "function res=accurateSumK(p,K)\n%%ACCURATESUMK Sum the elements in a vector in a manner that reduces finite\n% precision errors when summing large and small values as\n% compared to sequentially summing the terms. In comparison to\n% the accurateSum function, this function allows for K-fold\n% precision (K=2 is fixed in accurateSum with algorithm 0).\n%\n%INPUTS: p An nX1 or 1Xn vector of real values.\n% K The multiple of the standard double precision desired for\n% intermediate results. If omitted or an empty matrix is passed,\n% the default is K=3. Values larger than n are clipped to n.\n%\n%OUTPUTS: res The value of the sum of the values in p.\n%\n%This function implements algorithm 4.8 in [1].\n%\n%EXAMPLE:\n%The simplest example demonstrates how using higher intermediate precision\n%can make sorting the input less important. We compare this function to the\n%unsorted accurateSum function.\n% a=[1e100;2;1;eps();eps();eps();-1e100];\n% res0=accurateSumK(a)\n% res1=accurateSum(a,[],false)%false makes it unsorted.\n%One gets res0=3.000000000000001 and res=3. res0 is more accurate.\n%\n%REFERENCES:\n%[1] T. Ogita, S. M. Rump, and S. Oishi, \"Accurate sum and dot product,\"\n% SIAM Journal on Scientific Computing, no. 6, pp. 1955-1988, 2005.\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<2||isempty(K))\n K=3;\nend\n\nn=length(p);\nK=min(K,n);\nfor k=1:(K-1)\n p=VecSum(p);\nend\n\nres=p(1);\nfor i=2:n\n res=res+p(i);\nend\nend\n\nfunction p=VecSum(p)\n n=length(p);\n for k=2:n\n [p1,p2]=exactPairSum(p(k),p(k-1));\n p(k)=p1;\n p(k-1)=p2;\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/Accurate_Arithmetic/accurateSumK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7864054765074293}} {"text": "function legendre_exactness ( n, x, w, p_max )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_EXACTNESS: quadrature rule exactness for Legendre integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points in the rule.\n%\n% Input, real X(N), the quadrature points.\n%\n% Input, real W(N), the quadrature weights.\n%\n% Input, integer P_MAX, the maximum exponent.\n% 0 <= P_MAX.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Quadrature rule of order %d for the Legendre integral.\\n', n );\n fprintf ( 1, ' Degree Relative Error\\n' );\n fprintf ( 1, '\\n' );\n\n for p = 0 : p_max\n\n e = legendre_monomial_quadrature ( n, x, w, p );\n\n fprintf ( 1, ' %6d %24.16f\\n', p, e );\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/cc_project/legendre_exactness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7864054689579534}} {"text": "function [ center, eccent, parity ] = tree_arc_center ( nnode, inode, jnode )\n\n%*****************************************************************************80\n%\n%% TREE_ARC_CENTER computes the center, eccentricity, and parity of a tree.\n%\n% Discussion:\n%\n% A tree is an undirected graph of N nodes, which uses N-1 edges,\n% and is connected. \n%\n% A graph with N-1 edges is not guaranteed to be a tree, and so this\n% routine must first check that condition before proceeding.\n%\n% The edge distance between two nodes I and J is the minimum number of\n% edges that must be traversed in a path from I and J.\n%\n% The eccentricity of a node I is the maximum edge distance between\n% node I and the other nodes J in the graph.\n%\n% The radius of a graph is the minimum eccentricity over all nodes\n% in the graph.\n%\n% The diameter of a graph is the maximum eccentricity over all nodes\n% in the graph.\n%\n% The center of a graph is the set of nodes whose eccentricity is \n% equal to the radius, that is, the set of nodes of minimum eccentricity.\n%\n% For a tree, the center is either a single node, or a pair of\n% neighbor nodes.\n%\n% The parity of the tree is 1 if the center is a single node, or 2 if\n% the center is 2 nodes.\n%\n% The center of a tree can be found by removing all \"leaves\", that is,\n% nodes of degree 1. This step is repeated until only 1 or 2 nodes\n% are left.\n%\n% Thanks to Alexander Sax for pointing out that a previous version of the\n% code was failing when the tree had an odd parity, that is, a single\n% center node, 15 April 2013.\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 INODE(NNODE-1), JNODE(NNODE-1), the edges of\n% the tree. Edge I connects nodes INODE(I) and JNODE(I).\n%\n% Output, integer CENTER(2). CENTER(1) is the index of the\n% first node in the center. CENTER(2) is 0 if there is only one node\n% in the center, or else the index of the second node.\n%\n% Output, integer ECCENT, the eccentricity of the nodes in \n% the center, and the radius of the the tree.\n%\n% Output, integer PARITY, the parity of the tree, which is\n% normally 1 or 2.\n%\n eccent = 0;\n center(1) = 0;\n center(2) = 0;\n parity = 0;\n\n if ( nnode <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TREE_ARC_CENTER - Fatal error!\\n' );\n fprintf ( 1, ' NNODE <= 0.\\n' );\n error ( 'TREE_ARC_CENTER - Fatal error!' );\n elseif ( nnode == 1 )\n eccent = 0;\n center(1) = 1;\n center(2) = 0;\n parity = 1;\n return\n elseif ( nnode == 2 )\n eccent = 1;\n center(1) = 1;\n center(2) = 2;\n parity = 2;\n return\n end\n%\n% Is this graph really a tree?\n%\n nedge = nnode - 1;\n result = graph_arc_is_tree ( nedge, inode, jnode, nnode );\n\n if ( result == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TREE_ARC_CENTER - Fatal error!\\n' );\n fprintf ( 1, ' This graph is NOT a tree.\\n' );\n error ( 'TREE_ARC_CENTER - Fatal error!' );\n end\n%\n% Compute the degrees.\n%\n degree = graph_arc_degree ( nnode, nedge, inode, jnode );\n%\n% Defoliate the tree.\n%\n nnode2 = nnode;\n\n while ( 1 )\n\n eccent = eccent + 1;\n%\n% Find and mark the leaves.\n%\n nleaf = 0;\n\n for i = 1 : nnode\n\n if ( degree(i) == 1 )\n nleaf = nleaf + 1;\n list(nleaf) = i;\n end\n\n end\n%\n% Delete the leaves.\n%\n for ileaf = 1 : nleaf\n\n i = list(ileaf);\n\n iedge = 0;\n j = 0;\n\n while ( 1 )\n\n iedge = iedge + 1;\n\n if ( nedge < iedge )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TREE_ARC_CENTER - Fatal error!\\n' );\n fprintf ( 1, ' Data or algorithm failure.\\n' );\n error ( 'TREE_ARC_CENTER - Fatal error!' );\n end\n\n if ( inode(iedge) == i )\n j = jnode(iedge);\n inode(iedge) = - inode(iedge);\n jnode(iedge) = - jnode(iedge);\n elseif ( jnode(iedge) == i )\n j = inode(iedge);\n inode(iedge) = - inode(iedge);\n jnode(iedge) = - jnode(iedge);\n end\n\n if ( j ~= 0 )\n break\n end\n\n end\n\n degree(i) = -1;\n nnode2 = nnode2 - 1;\n degree(j) = degree(j) - 1;\n%\n% If the other node has degree 0, we must have just finished\n% stripping all leaves from the tree, leaving a single node.\n% Don't kill it here. It is our odd center.\n%\n% if ( degree(j) == 0 )\n% nnode2 = nnode2 - 1;\n% end\n\n end\n%\n% Find the remaining nodes.\n%\n nnode2 = 0;\n\n for i = 1 : nnode\n\n if ( 0 <= degree(i) )\n nnode2 = nnode2 + 1;\n list(nnode2) = i;\n end\n\n end\n%\n% If at least 3, more pruning is required.\n%\n if ( nnode2 < 3 )\n break\n end\n\n end\n%\n% If only one or two nodes left, we are done.\n%\n parity = nnode2;\n\n center(1:nnode2) = list(1:nnode2);\n inode(1:nedge) = abs ( inode(1:nedge) );\n jnode(1:nedge) = abs ( jnode(1:nedge) );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/treepack/tree_arc_center.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7864054598271709}} {"text": "function value = r8poly_value_horner ( m, c, x )\n\n%*****************************************************************************80\n%\n%% R8POLY_VALUE_HORNER evaluates a polynomial using Horner's method.\n%\n% Discussion:\n%\n% The polynomial \n%\n% p(x) = c0 + c1 * x + c2 * x^2 + ... + cm * x^m\n%\n% is to be evaluated at the value X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the degree.\n%\n% Input, real C(M+1), the polynomial coefficients. \n% C(I) is the coefficient of X^(I-1).\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the polynomial value.\n%\n value = c(m+1);\n for i = m : -1 : 1\n value = value * x + c(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/polpak/r8poly_value_horner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7863858129707275}} {"text": "function [ f_rec , X ] = abel_inversion(h,R,upf,plot_results)\n% This function calculates a Fourier-based Abel inversion based on the\n% method described in [1]. Assuming cylindrical symmetry, the distribution \n% function f_rec can be reconstructed from the measured profile h .\n%\n% The main idea is a Fourier-series-like expansion of the unknown\n% distribution function f(r) into \n% f(r) = sum_{n=lof}^{upf} (A_n * f_n(r)) (1)\n% where the lower frequency is set to 1 and the upper frequency upf is\n% important for noise-filtering.\n%\n%\n% INPUT: H - dataset to be analyzed (1xN - matrix). \n% For optimum results, H(1) should be the center and H(N) the \n% edge of the investigated object and H(N) should be approx zero.\n% If no input H is given, a sampla dataset will be created.\n% R - radius of given system (i.e. distance between H(1) and H(N))\n% UPF - upper frequency limit. Defines the number of cosinus\n% expansions (and critically determines computation time). \n% Choosing a very low value (e.g. 4) results in a low-pass \n% filtering effect, reducing noise (but also potential features) \n% PLOT_RESULTS - set to 1 to plot the results\n%\n% OUTPUT: F_REC - reconstructed density profile\n% X - x-vector containing spatial coordinates for F_REC\n%\n% \n% [1] G. Pretzler, Z. Naturforsch. 46a, 639 (1991)\n%\n% See also: COMPUTE_EXPANSION, GENERATE_TEST_DATA, SOLVE_LSQ\n%\n% written by C. Killer, Sept. 2013\n\n\n%% format data / generate sample data\n\n% create sample data based on a polynomial distribution function\n% if no data input is given\nif ~exist('h', 'var') || isempty(h)\n [X,h,R]=generate_test_data;\n plot_results=1;\nelse\n X=linspace(0,R-0.01,length(h))';\nend \n\n% default value for number of expansion elements\nif ~exist('upf', 'var'); upf=10; end; \n\n% avoiding problems if this flag is not given in input\nif ~exist('plot_results', 'var'); plot_results=0; end; \n\n%% calculate series expansions fn and corresponding integrals hn\n\n[fn,hn] = compute_expansion( X,upf,R );\n\n%% Solving optimization problem\n\n% guess some initial values for optimisation\nx0=1*ones(upf+1,1); \n\n% solve for amplitudes A\nA = solve_lsq(h,hn,x0);\n\n% create vector for resulting reconstructed distribution\nf_rec=zeros(length(h),1); \n\n% special case for n=0 (where f_0(r) = 1)\nf_rec = f_rec + A(1)*1;\n\n% iterate eq. (1) for n=1:upf\nfor c=2:length(x0)\n f_rec = f_rec + A(c).*fn(:,c);\nend\n\nif plot_results==1 \n figure; % normalized profiles for better comparison\n set(gca,'linewidth',1.5,'fontsize',16)\n plot(X,f_rec./max(f_rec),'k','Linewidth',1.5); \n hold on; plot(X,h./max(h),'b','Linewidth',1.5); \n grid on; box on; \n title(sprintf('number of cos-expansions: %i',upf))\n legend('reconstructed distribution','measured profile','Location','SouthWest')\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/43639-abel-inversion-algorithm/abel_inversion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8519527982093668, "lm_q1q2_score": 0.786385798885606}} {"text": "function p = circle_imp_points_arc_2d ( r, center, theta1, theta2, n )\n\n%*****************************************************************************80\n%\n%% CIRCLE_IMP_POINTS_ARC_2D returns N points on an arc of an implicit circle in 2D.\n%\n% Discussion:\n%\n% The first point is\n% ( CENTER(1) + R * COS ( THETA1 ), CENTER(2) + R * SIN ( THETA1 ) );\n% The last point is\n% ( CENTER(1) + R * COS ( THETA2 ), CENTER(2) + R * SIN ( THETA2 ) );\n% and the intermediate points are evenly spaced in angle between these,\n% and in counterclockwise order.\n%\n% An implicit circle in 2D satisfies the equation:\n%\n% ( X - CENTER(1) )^2 + ( Y - CENTER(2) )^2 = R^2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2,1), the center of the circle.\n%\n% Input, real THETA1, THETA2, the angular coordinates of\n% the first and last points to be drawn, in radians.\n%\n% Input, integer N, the number of points desired. N must be at least 1.\n%\n% Output, real P(2,N), the points on the circle.\n%\n\n%\n% THETA3 is the smallest angle, no less than THETA1, which\n% coincides with THETA2.\n%\n theta3 = theta1 + r8_modp ( theta2 - theta1, 2.0 * pi );\n\n for i = 1 : n\n\n if ( 1 < n )\n theta = ( ( n - i ) * theta1 ...\n + ( i - 1 ) * theta3 ) ...\n / ( n - 1 );\n else\n theta = 0.5 * ( theta1 + theta3 );\n end\n\n p(1,i) = center(1,1) + r * cos ( theta );\n p(2,i) = center(2,1) + r * sin ( theta );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/circle_imp_points_arc_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7863857968754296}} {"text": "function ndvi = NDVI( red,nir )\n%NDVI Calculate Normalized Difference Vegetation Index (NDVI) using NIR and\n% Red bands.\n%\n% Syntax\n%\n% ndvi = NDVI(red,nir)\n%\n% Description\n%\n% This function calculates Normalized Difference Vegetation Index (NDVI) \n% using NIR and Red bands (as following equation). This range is between\n% -1 and 1.\n% NDVI=(NIR-Red)/(NIR+Red).\n%\n% Input arguments\n%\n% red Red band\n% nir Near-infrared band\n%\n% Output arguments\n%\n% ndvi Normalized Difference Vegetation Index\n%\n%\n% Author: Shi Qiu (shi.qiu@ttu.edu)\n% Date: 19. October, 2017\n\n % calculate NDVI\n ndvi=(nir-red)./(nir+red);\n \n % fix unnormal pixels\n ndvi((nir+red)==0)=0.01;\n\nend\n\n", "meta": {"author": "GERSL", "repo": "Fmask", "sha": "e9e0e23af163ec55c60b7f93e6ab8e72617ee851", "save_path": "github-repos/MATLAB/GERSL-Fmask", "path": "github-repos/MATLAB/GERSL-Fmask/Fmask-e9e0e23af163ec55c60b7f93e6ab8e72617ee851/NDVI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7863741801183111}} {"text": "classdef snr\n %SNR helper functions for calculating SNR\n \n properties\n end\n\n methods(Static)\n function result = SNR(signal, noise)\n sigEnergy = sum(signal .* conj(signal));\n noiseEnergy = sum(noise .* conj(noise));\n result=10*log10(sigEnergy./noiseEnergy);\n end\n function result = recSNRdB(signal, reconstruction)\n result=20*log10(norm(signal)/norm(signal-reconstruction));\n end\n \n function result = energyDB(signal)\n result = 20*log10(norm(signal));\n end\n function result = recSNR(signal, reconstruction)\n noise = (signal - reconstruction);\n result = (signal' * signal) / (noise'*noise);\n end\n function result = normalizedErrorEnergy(signal, reconstruction)\n noise = (signal - reconstruction);\n result = (noise' * noise) / (signal'*signal);\n end\n \n function result = recSNRsdB(signals, reconstructions)\n ratios = spx.snr.recSNRs(signals, reconstructions);\n result= 10 * log10(ratios);\n end\n \n function result = recSNRs(signals, reconstructions)\n sigEngergies = spx.snr.energies(signals);\n noiseEnergies = spx.snr.energies(signals - reconstructions);\n result = sigEngergies ./ noiseEnergies;\n end\n \n function result = energies(signals)\n signals = abs(signals);\n signals = signals .^2;\n result = sum(signals, 1);\n end\n \n function result = energiesDB(signals)\n energies = spx.snr.energies(signals);\n result = 10* log10(energies);\n end\n end\n \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/+spx/snr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.786374164560035}} {"text": "function [Az El] = RaDec2AzEl(Ra,Dec,lat,lon,time)\n% Programed by Darin C. Koblick 01/23/2010\n%--------------------------------------------------------------------------\n% External Function Call Sequence:\n% [Az El] = RaDec2AzEl(0,0,0,-104,'1992/08/20 12:14:00')\n%\n% Worked Example: pg. 262 Vallado\n%[Az El] = RaDec2AzEl(294.9891115,-20.8235624,39.007,-104.883,'1994/05/14 13:11:20.59856')\n%[210.7514 23.9036] = RaDec2AzEl(294.9891115,-20.8235624,39.007,-104.883,'1994/05/14 13:11:20.59856')\n%\n% Worked Example: http://www.stargazing.net/kepler/altaz.html\n% [Az El] = RaDec2AzEl(344.95,42.71667,52.5,-1.91667,'1997/03/14 19:00:00')\n% [311.92258 22.40100] = RaDec2AzEl(344.95,42.71667,52.5,-1.91667,'1997/03/14 19:00:00')\n%\n% [Beta,el] = RaDec2AzEl(alpha_t,delta_t,phi,lamda,'yyyy/mm/dd hh:mm:ss')\n%\n% Function Description:\n%--------------------------------------------------------------------------\n% RaDec2AzEl will take the Right Ascension and Declination in the topocentric \n% reference frame, site latitude and longitude as well as a time in GMT\n% and output the Azimuth and Elevation in the local horizon\n% reference frame.\n%\n% Inputs: Format:\n%--------------------------------------------------------------------------\n% Topocentric Right Ascension (Degrees) [N x 1]\n% Topocentric Declination Angle (Degrees) [N x 1]\n% Lat (Site Latitude in degrees -90:90 -> S(-) N(+)) [N x 1]\n% Lon (Site Longitude in degrees -180:180 W(-) E(+)) [N x 1]\n% UTC (Coordinated Universal Time YYYY/MM/DD hh:mm:ss) [N x 1]\n%\n% Outputs: Format:\n%--------------------------------------------------------------------------\n% Local Azimuth Angle (degrees) [N x 1]\n% Local Elevation Angle (degrees) [N x 1]\n%\n%\n% External Source References:\n% Fundamentals of Astrodynamics and Applications \n% D. Vallado, Second Edition\n% Example 3-5. Finding Local Siderial Time (pg. 192) \n% Algorithm 28: AzElToRaDec (pg. 259)\n% -------------------------------------------------------------------------\n\n%Example 3-5\n[yyyy mm dd HH MM SS] = datevec(datenum(time,'yyyy/mm/dd HH:MM:SS'));\nJD = juliandate(yyyy,mm,dd,HH,MM,SS);\nT_UT1 = (JD-2451545)./36525;\nThetaGMST = 67310.54841 + (876600*3600 + 8640184.812866).*T_UT1 ...\n+ .093104.*(T_UT1.^2) - (6.2*10^-6).*(T_UT1.^3);\nThetaGMST = mod((mod(ThetaGMST,86400*(ThetaGMST./abs(ThetaGMST)))/240),360);\nThetaLST = ThetaGMST + lon;\n\n%Equation 4-11 (Define Siderial Time LHA)\nLHA = mod(ThetaLST - Ra,360);\n\n%Equation 4-12 (Elevation Deg)\nEl = asind(sind(lat).*sind(Dec)+cosd(lat).*cosd(Dec).*cosd(LHA));\n\n%Equation 4-13 / 4-14 (Adaptation) (Azimuth Deg)\n%Az = mod(atand(-(sind(LHA).*cosd(Dec)./(cosd(lat).*sind(Dec) - sind(lat).*cosd(Dec).*cosd(LHA)))),360);\nAz = mod(atan2(-sind(LHA).*cosd(Dec)./cosd(El),...\n (sind(Dec)-sind(El).*sind(lat))./(cosd(El).*cosd(lat))).*(180/pi),360);\n\n\nfunction jd = juliandate(year, month, day, hour, min, sec) \nYearDur = 365.25;\nfor i = length(month):-1:1\n if (month(i)<=2)\n year(i)=year(i)-1;\n month(i)=month(i)+12;\n end\nend\nA = floor(YearDur*(year+4716));\nB = floor(30.6001*(month+1));\nC = 2;\nD = floor(year/100);\nE = floor(floor(year/100)*.25);\nF = day-1524.5;\nG = (hour+(min/60)+sec/3600)/24;\njd =A+B+C-D+E+F+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/26458-convert-right-ascension-and-declination-to-azimuth-and-elevation/RaDec2AzEl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7863204899617436}} {"text": "function dw2dx2 = r8poly_lagrange_2 ( npol, xpol, xval )\n\n%*****************************************************************************80\n%\n%% R8POLY_LAGRANGE_2 evaluates the second derivative of the Lagrange factor.\n%\n% Formula:\n%\n% W(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )\n%\n% W'(X) = Sum ( 1 <= J <= NPOL )\n% Product ( I /= J ) ( X - XPOL(I) )\n%\n% W\"(X) = Sum ( 1 <= K <= NPOL )\n% Sum ( J =/ K )\n% Product ( I /= K, J ) ( X - XPOL(I) )\n%\n% For a set of points XPOL(I), 1 <= I <= NPOL, the IPOL-th Lagrange basis\n% polynomial L(IPOL)(X), has the property:\n%\n% L(IPOL)( XPOL(J) ) = delta ( IPOL, J )\n%\n% and may be expressed as:\n%\n% L(IPOL)(X) = W(X) / ( ( X - XPOL(IPOL) ) * W'(XPOL(IPOL)) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NPOL, the number of abscissas.\n% NPOL must be at least 1.\n%\n% Input, real XPOL(NPOL), the abscissas, which should be distinct.\n%\n% Input, real XVAL, the point at which the Lagrange factor is to be\n% evaluated.\n%\n% Output, real DW2DX2, the second derivative of W with respect to XVAL.\n%\n dw2dx2 = 0.0;\n\n for k = 1 : npol\n\n for j = 1 : npol\n\n if ( j ~= k )\n term = 1.0;\n\n for i = 1: npol\n if ( i ~= j && i ~= k )\n term = term * ( xval - xpol(i) );\n end\n end\n\n dw2dx2 = dw2dx2 + term;\n\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8poly_lagrange_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7862740541650407}} {"text": "function IMs = slinv2x2(Ms)\n%SLINV2X2 Computes inverse matrices for 2 x 2 matrices in a fast way\n%\n% $ Syntax $\n% - IMs = slinv2x2(Ms)\n%\n% $ Arguments $\n% - Ms: the 2 x 2 matrix (matrices)\n% - IMs: the computed inverse matrix (matrices)\n%\n% $ Description $\n% - IMs = slinv2x2(Ms) computes the inverse of 2x2 matrices. If Ms is\n% a 2 x 2 matrix, then r is its inverse.\n% Or, if Ms is a 2 x 2 x ... array, then r would be a 2 x 2 x ... array \n% storing the inverse matrices.\n%\n% $ Remarks $\n% - The function uses the following formula for fast calculation of\n% inverse of 2 x 2 matrices:\n% inv(A) = [a22, -a12; -a21, a11] / det(A)\n%\n% $ History $\n% - Created by Dahua Lin on Apr 22nd, 2006\n%\n\n%% parse and verify input arguments\n\nif size(Ms, 1) ~= 2 || size(Ms, 2) ~= 2\n error('sltoolbox:invalidarg', 'Ms should be set of 2 x 2 matrices');\nend\n\n%% compute\n\nif ndims(Ms) == 2 % single matrix\n IMs = [Ms(4), -Ms(2); -Ms(3), Ms(1)] / (Ms(1) * Ms(4) - Ms(2) * Ms(3));\n \nelse % a set of matrices\n \n IMs = zeros(size(Ms));\n \n % compute adjacent matrix\n IMs(1,1,:) = Ms(2,2,:);\n IMs(1,2,:) = -Ms(1,2,:);\n IMs(2,1,:) = -Ms(2,1,:);\n IMs(2,2,:) = Ms(1,1,:);\n \n % compute the determinants\n d = sldet2x2(Ms);\n \n % scale\n d = reshape(d, [1, 1, size(d)]);\n IMs = slmul(IMs, 1 ./ d);\n \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/smallmat/slinv2x2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7862530805343314}} {"text": "function K = levelsetCurvature(phi,mode)\n%levelsetCurvature Computes the curvature of a level set function.\n% K = levelsetCurvature(PHI,MODE) computes the curvature, K, of level\n% set function PHI. If MODE = 'Cu' the curvature is not normalized\n% (this is the default). If MODE = 'Cn', the curvature is normalized\n% by dividing it by its maximum value. This function is based on Eqs.\n% (12-61) and (12-62) of DIPUM3E.\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\n% PRELIMINARIES\n% Set default.\nif nargin == 1\n mode = 'Cu';\nend\n[M,N] = size(phi);\nphi = double(phi);\n\n% PAD WITH 1'S TO BE ABLE TO COMPUTE THE DERIVATIVE AT IMAGE BORDERS.\nphip = padarray(phi,[1 1],1,'both');\n\n% COMPUTE THE CENTRAL DIFFERENCES.\nphix = 0.5*(phip(3:end,2:N+1) - phip(1:M,2:N+1));\nphiy = 0.5*(phip(2:M+1,3:end) - phip(2:M+1,1:N));\nphixx = phip(3:end,2:N+1) + phip(1:M,2:N+1) - 2*phi;\nphiyy = phip(2:M+1,3:end) + phip(2:M+1,1:N) - 2*phi;\nphixy = 0.25.*(phip(3:end,3:end) - phip(1:M,3:end)...\n - phip(3:end,1:N) + phip(1:M,1:N));\n% COMPUTE THE CURVATURE.\nDEN = (phix.^2 + phiy.^2 + eps).^1.5;\nK = (phixx.*(phiy.^2) - 2*(phix.*phiy.*phixy) + phiyy.*(phix.^2))./DEN;\n\n% CHECK FOR NORMALIZATION.\nif isequal(mode,'Cn')\n K = K/max(abs(K(:)));\nend\n \n% COMPENSATE FOR BORDER EFFECTS BY SETTING THE FIRST AND LAST ROWS AND\n% COLUMNS EQUAL TO THEIR IMMEDIATE PREDECESSORS. \n% CURVATURE \n% Rows.\nK(:,1) = K(:,2);\nK(:,end) = K(:,end-1);\n% Columns.\nK(1,:) = K(2,:);\nK(end,:) = K(end-1,:);\n\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/levelSetFunctions/levelsetCurvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8976953023710936, "lm_q1q2_score": 0.7861898566386891}} {"text": "function result = polygon_1 ( n, v )\n\n%*****************************************************************************80\n%\n%% POLYGON_INTEGRAL_1 integrates the function 1 over a polygon.\n%\n% Discussion\n%\n% The polygon is bounded by the points (X(1:N), Y(1:N)).\n%\n% INTEGRAL = 0.5 * SUM ( 1 <= I <= N )\n% ( X(I) + X(I-1) ) * ( Y(I) - Y(I-1) )\n%\n% where X(0) and Y(0) should be replaced by X(N) and Y(N).\n%\n% Note that the integral of 1 over a polygon is the area of the polygon.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% S F Bockman,\n% Generalizing the Formula for Areas of Polygons to Moments,\n% American Mathematical Society Monthly,\n% 1989, pages 131-132.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n% N should be at least 3 for a nonzero result.\n%\n% Input, real V(2,N), the coordinates of the vertices\n% of the polygon. These vertices should be given in counter-clockwise order.\n%\n% Output, real RESULT, the value of the integral.\n%\n result = 0.0;\n\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_INTEGRAL_1 - Warning!\\n' );\n fprintf ( 1, ' The number of vertices must be at least 3.\\n' );\n fprintf ( 1, ' The input value of N = %d\\n', n );\n error ( 'POLYGON_INTEGRAL_1 - Fatal error!' );\n end\n\n for i = 1 : n\n\n if ( i == 1 )\n im1 = n;\n else\n im1 = i - 1;\n end\n\n result = result + 0.5 * ( v(1,i) + v(1,im1) ) * ( v(2,i) - v(2,im1) );\n\n end\n\n return\nend\n", "meta": {"author": "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_integral_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7861580910233545}} {"text": "%VEX Convert skew-symmetric matrix to vector\n%\n% V = VEX(S) is the vector which has the corresponding skew-symmetric \n% matrix S. \n%\n% In the case that S (2x2) =\n%\n% | 0 -v |\n% | v 0 |\n%\n% then V = [v]. In the case that S (3x3) =\n%\n% | 0 -vz vy |\n% | vz 0 -vx |\n% |-vy vx 0 |\n%\n% then V = [vx; vy; vz].\n%\n% Notes::\n% - This is the inverse of the function SKEW().\n% - Only rudimentary checking (zero diagonal) is done to ensure that the \n% matrix is actually skew-symmetric.\n% - The function takes the mean of the two elements that correspond to \n% each unique element of the matrix.\n% - The matrices are the generator matrices for so(2) and so(3).\n%\n% References::\n% - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p25+43.\n%\n% See also SKEW, VEXA.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction v = vex(S)\n% if trace(abs(S)) > 10*eps\n% error('SMTB:vex:badarg', 'argument is not skew symmetric tr=%g', trace(abs(S)));\n% end\n if all(size(S) == [3 3])\n v = 0.5*[S(3,2)-S(2,3); S(1,3)-S(3,1); S(2,1)-S(1,2)];\n elseif all(size(S) == [2 2])\n v = 0.5*(S(2,1)-S(1,2));\n else\n error('SMTB:vex:badarg', 'argument must be a 2x2 or 3x3 matrix');\n end\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/vex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7861580835836}} {"text": "function R = functionRlocalscattering(M,theta,ASDdeg,antennaSpacing,distribution)\n%Generate the spatial correlation matrix for the local scattering model,\n%defined in (2.23) for different angular distributions.\n%\n%INPUT:\n%M = Number of antennas\n%theta = Nominal angle\n%ASDdeg = Angular standard deviation around the nominal angle\n% (measured in degrees)\n%antennaSpacing = (Optional) Spacing between antennas (in wavelengths)\n%distribution = (Optional) Choose between 'Gaussian', 'Uniform', and\n% 'Laplace' angular distribution. Gaussian is default\n%\n%OUTPUT:\n%R = M x M spatial correlation matrix\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.1 (Last edited: 2017-11-16)\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%Set the antenna spacing if not specified by input\nif nargin < 4\n \n %Half a wavelength distance\n antennaSpacing = 1/2;\n \nend\n\n%Set angular distribution to Gaussian if not specified by input\nif nargin<5\n distribution = 'Gaussian';\nend\n\n\n%Compute the ASD in radians based on input\nASD = ASDdeg*pi/180;\n\n\n%The correlation matrix has a Toeplitz structure, so we only need to\n%compute the first row of the matrix\nfirstRow = zeros(M,1);\n\n\n%Go through all the columns of the first row\nfor column = 1:M\n \n %Distance from the first antenna\n distance = antennaSpacing*(column-1);\n \n \n %For Gaussian angular distribution\n if strcmp(distribution,'Gaussian')\n \n %Define integrand of (2.23)\n F = @(Delta)exp(1i*2*pi*distance*sin(theta+Delta)).*exp(-Delta.^2/(2*ASD^2))/(sqrt(2*pi)*ASD);\n \n %Compute the integral in (2.23) by including 20 standard deviations\n firstRow(column) = integral(F,-20*ASD,20*ASD);\n \n \n %For uniform angular distribution\n elseif strcmp(distribution,'Uniform')\n \n %Set the upper and lower limit of the uniform distribution\n limits = sqrt(3)*ASD;\n \n %Define integrand of (2.23)\n F = @(Delta)exp(1i*2*pi*distance*sin(theta+Delta))/(2*limits);\n \n %Compute the integral in (2.23) over the entire interval\n firstRow(column) = integral(F,-limits,limits);\n \n \n %For Laplace angular distribution\n elseif strcmp(distribution,'Laplace')\n \n %Set the scale parameter of the Laplace distribution\n LaplaceScale = ASD/sqrt(2);\n \n %Define integrand of (2.23)\n F = @(Delta)exp(1i*2*pi*distance*sin(theta+Delta)).*exp(-abs(Delta)/LaplaceScale)/(2*LaplaceScale);\n \n %Compute the integral in (2.23) by including 20 standard deviations\n firstRow(column) = integral(F,-20*ASD,20*ASD);\n \n end\n \nend\n\n%Compute the spatial correlation matrix by utilizing the Toeplitz structure\nR = toeplitz(firstRow);\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/functionRlocalscattering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7861580815502235}} {"text": "function [ fea, out ] = ex_convdiff4( varargin )\n%EX_CONVDIFF4 1D Burgers equation (convection and diffusion) example.\n%\n% [ FEA, OUT ] = EX_CONVDIFF4( VARARGIN ) 1D Burgers equation with steady solution,\n% u_t + (b*u-c)*u_x - nu*u_xx = 0 with exact solution c/b*(1-tanh(c/(2*nu)*(x-x0))).\n% Tests both time dependent and steady solvers. Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% b scalar {1.0} Strength of nonlinearity\n% c scalar {0.13} Convection velocity\n% nu scalar {0.01} Diffusion coefficient\n% x0 scalar {0.5} Posision of smooth shock\n% hmax scalar {1/25} Max grid cell size\n% ischeme scalar {-1} Solver scheme (<0 = stationary)\n% nsolve scalar {2} Nonlinear solver (when ischeme<0)\n% dt scalar {0.1} Time step size\n% sfun string {sflag1} Shape function\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'b', 1.0; ...\n 'c', 0.13; ...\n 'nu', 0.01; ...\n 'x0', 0.5; ...\n 'hmax', 1/20; ...\n 'ischeme' -1; ...\n 'nsolve' 2; ...\n 'dt' 0.1; ...\n 'sfun', 'sflag1'; ...\n 'iplot', 1; ...\n 'tol', 1e-2; ...\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\nb = opt.b;\nc = opt.c;\nnu = opt.nu;\nx0 = opt.x0;\nrefsol = [num2str(c/b),'*(1-tanh(',num2str(c/(2*nu)),'*(x-',num2str(x0),')))'];\nbcd1 = c/b*(1-tanh((c/(2*nu)*(0-x0))));\nbcd2 = c/b*(1-tanh((c/(2*nu)*(1-x0))));\n\n% Grid generation.\nfea.grid = linegrid( 1/opt.hmax, 0, 1 );\n\n\n% Problem definition.\nfea.sdim = { 'x' };\nfea = addphys( fea, @convectiondiffusion );\nfea.phys.cd.sfun = { opt.sfun };\nfea.phys.cd.eqn.coef{2,4} = { opt.nu };\nfea.phys.cd.eqn.coef{3,4} = { [num2str(b),'*c-',num2str(c)] };\nfea = parsephys(fea);\n\n\n% Parse and solve problem.\nfea = parseprob( fea );\nfea.bdr.d{1} = bcd1;\nfea.bdr.d{2} = bcd2;\nfea.bdr.n = cell(1,2);\nx = fea.grid.p';\nif( strcmp( opt.sfun,'sflag2' ) )\n x = [ x; (x(2:end)+x(1:end-1))/2 ];\nend\nif( opt.ischeme<0 )\n init = 0;\n jac.form = {[1;1]};\n jac.coef = {[num2str(b),'*cx']};\n fea.sol.u = solvestat( fea, 'fid', fid, 'init', init, 'maxnit', 1000, 'nsolve', 2, 'jac', jac, 'nsolve', opt.nsolve );\nelse\n init = [num2str(bcd1),'+x*',num2str(bcd2-bcd1)];\n [fea.sol.u,tlist] = solvetime( fea, 'fid', fid, 'init', init, 'ischeme', opt.ischeme, 'tstep', opt.dt, 'tmax', 10 );\nend\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n figure\n i_sol = size(fea.sol.u,2);\n [~,ix] = sort( x );\n postplot( fea, 'surfexpr', 'c', 'solnum', i_sol );\n hold on\n u_r = real( eval( refsol ) );\n plot( sort(x), u_r(ix), 'r--' );\n title( 'Steady solution' )\n xlabel( 'x' )\n drawnow\nend\n\n\n% Error checking.\ni_sol = size(fea.sol.u,2);\nu_i = fea.sol.u(:,i_sol);\nu_r = real( eval( refsol ) );\nerrnm = norm( u_i - u_r )/norm( u_r );\nout.err = errnm;\nout.pass = all( errnm100; % Find all freqs with large power\nPSDclean = PSD.*indices; % Zero out all others\nfhat = indices.*fhat; % Zero out small Fourier coeffs. in Y\nffilt = ifft(fhat); % Inverse FFT for filtered time signal\n\n%% PLOTS\nsubplot(3,1,1)\nplot(t,f,'r','LineWidth',1.2), hold on\nplot(t,f,'k','LineWidth',1.5)\nlegend('Noisy','Clean')\n\nsubplot(3,1,2)\nplot(t,f,'k','LineWidth',1.5), hold on\nplot(t,ffilt,'b','LineWidth',1.2)\nlegend('Clean','Filtered')\n\nsubplot(3,1,3)\nplot(freq(L),PSD(L),'r','LineWidth',1.5), hold on\nplot(freq(L),PSDclean(L),'-b','LineWidth',1.2)\nlegend('Noisy','Filtered')\n\n% \n% %% PLOTS\n% subplot(3,1,1)\n% plot(t,y,'r','LineWidth',1.2)\n% hold on\n% plot(t,x,'k','LineWidth',1.5)\n% axis([0 .25 -5 5])\n% legend('Noisy','Clean')\n% \n% subplot(3,1,2)\n% plot(t,x,'k','LineWidth',1.5)\n% hold on\n% plot(t,yfilt,'b','LineWidth',1.2)\n% axis([0 .25 -5 5])\n% legend('Clean','Filtered')\n% \n% subplot(3,1,3)\n% plot(freq(L),PSD(L),'r','LineWidth',1.5)\n% hold on\n% plot(freq(L),PSDclean(L),'-b','LineWidth',1.2)\n% legend('Noisy','Filtered')", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH02/CH02_SEC02_2_Denoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7860961541722455}} {"text": "clear; close all; clc;\n%% easiest example of curl: a stick on a stream\n\n[x,y]=meshgrid(0:1/10:1.5);\nu=y;\nv=zeros(size(x));\n\nfigure;\nquiver(x,y,u,v);\n% grid on;\naxis([0 1 0 1])\n\n%% easy example for curl: Vortex\nfigure('position',[542, 137, 750, 627]);\nU_i = 10;% free stream velocity\nC = 1000/(2*pi);% vortex strength\nmeshfactor = 10;\n[x,y] = meshgrid(-U_i:U_i/meshfactor:U_i);\n\n\nx1 = 0;\ny1 = 0;\nu1 = U_i - C*(y-y1)./(2*((x-x1).^2 + (y-y1).^2)); %%define the velocity component in the x\nv1 = C*(x-x1)./(2*((x-x1).^2 + (y-y1).^2)); %%define the velocity component in the y\n\nx2 = 4;\ny2 = 5;\nu2 = U_i + C*(y-y2)./(2*((x-x2).^2 + (y-y2).^2)); %%define the velocity component in the x\nv2 = -C*(x-x2)./(2*((x-x2).^2 + (y-y2).^2)); %%define the velocity component in the y\n\nu = u1+u2;\nv = v1+v2;\n\n[r,c]=find(isnan(u));\n\nfor i = 1:2\n u(r(i), c(i))=mean([u(r(i)-1,c(i)),u(r(i)+1,c(i))]);\n v(r(i), c(i))=mean([v(r(i)-1,c(i)),v(r(i)+1,c(i))]);\nend\n\nquiver(x,y,u,v)\nxlim([-U_i, U_i])\nylim([-U_i, U_i])\nset(gcf,'position',[542 137 750 627])\n\n%\nset(gcf,'color','w');\nhold on;\n[verts,averts] = streamslice(x,y,u,v);\nsl = streamline([verts averts]);\n\niverts = interpstreamspeed(x,y,u,v,verts,0.01);\nstreamparticles(iverts,100,'Animate',15,'FrameRate',40,'Markersize',5)\n\n%% Vortex represented with curl\n\nfigure;\nccurl=curl(x,y,u,v);\npcolor(x,y,ccurl);\nhold on\nshading interp\ncolormap(jet);\n\nquiver(x,y,u,v);\nxlim([-U_i, U_i])\nylim([-U_i, U_i])\nset(gcf,'position',[542 137 750 627])\n\n%% ex: wind\nk = 4;\nload wind\nx = x(:,:,k);\ny = y(:,:,k);\nu = u(:,:,k);\nv = v(:,:,k);\nfigure;\ncav = curl(x,y,u,v);\npcolor(x,y,cav);\nshading interp\nhold on\nquiver(x,y,u,v,'y','color','k');\nhold off\ncolormap('jet');", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/미적분학/벡터장의 회전 (curl)/curl_animation_Youtube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7860566471747786}} {"text": "%Author: Moeti Ncube\n\n%Comments: This code calibrates the heston model to any dataset of the form\n%of the marketdata.txt file. It also simulates the heston model given the\n%optimized parameters.\n\n%Marketdata=[strike, maturity,impvol,time till expiry]\n\n%Strike: Strike price of options\n%Maturity: (1=Prompt month, 2=Prompt month+1,...)\n%Impvol: Market Implied vol\n%Time till expiry: Days until option expires\n\nclear all\n\nglobal impvol; global strike; global T; global F0; global r;\n\n%Initial Parameter Guess for Hestion Model\n%V(1), Kappa, Theta, Vol of Volatility (sig), Correlation (rho)\nx0=[.5,.5,.5,.05,.5];\n%Constraints (Lower and Upper bounds on Parameters)\nlb = [0, 0, 0, 0, -.9];\nub = [1, 100, 1, .5, .9];\n%Number of MCMC simulations of Heston Model\nM=50000;\n%Current Asset Price (Prompt Month Price) and Interest rate\nF0=1250; r=0;\n\nload marketdata.txt\n\nT=marketdata(:,4)/365;\nstrike=marketdata(:,1);\nimpvol=marketdata(:,3);\n\n%Optimization\nx = lsqnonlin(@costf2,x0,lb,ub);\n\nfor k=1:length(T);\n%Initial asset price\nshes(1)=F0;\n%Number of Time Steps,time step size\nN=round(T(k)/(1/360));dt=T(k)/N;\n\n%Heston Parameters\nvhes(1)=x(1); kappa=x(2); theta=x(3); vsigma=x(4);rho=x(5); simPath=0;\n\n%Simulation of Heston Model\nfor i = 1:M \nfor j=1:N\n%heston model\nr1 = randn;\nr2 = rho*r1+sqrt(1-rho^2)*randn; \nshes(j+1)=shes(j)*exp((-0.5*vhes(j))*dt+sqrt(vhes(j))*sqrt(dt)*r1);\nvhes(j+1)=vhes(j)*exp(((kappa*(theta - vhes(j))-0.5*vsigma^2)*dt)/vhes(j) + vsigma*(1/sqrt(vhes(j)))*sqrt(dt)*r2);\nend\nsimPath = simPath + exp(-r*T(k)) * max(shes(j+1) - strike(k), 0);\nend\nsimhes(k)=simPath/M;\nsimimpvol(k)=blkimpv(shes(1), strike(k), r, T(k), simhes(k));\nmodhes(k)=HestonCall(shes(1),strike(k),r,T(k),vhes(1),kappa,theta,vsigma,rho,0);\nhesimpvol(k)=blkimpv(shes(1), strike(k), r, T(k), modhes(k));\nend\n\nfor i=1:length(T)\nbsprice(i)=blsprice(F0,strike(i),r,T(i),impvol(i));\nend\n\n%Output optimized Parameters\nx\n\n%Compare blackscholes option price, analytical heston price, and simulated\n%heston prices for a given maturity and strike\npricedata=[T,strike,bsprice',modhes',simhes']\n\n%Compare blackscholes option IV, analytical heston IV, and simulated\n%heston IV for a given maturity and strike\n\nvoldata=[T,strike,impvol,hesimpvol',simimpvol']\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29446-heston-model-calibration-and-simulation/HestonCalibration/hestoncalibrationexample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7860566393697751}} {"text": "function p = hex_grid_points ( nodes_per_layer, layers, n, box )\n\n%*****************************************************************************80\n%\n%% HEX_GRID_POINTS returns coordinate box hex grid points.\n%\n% Discussion:\n%\n% This routine determines the coordinates of the elements of\n% a hexagonal grid in the unit square.\n%\n% A hexagonal grid is defined in the coordinate box [A,B] x [C,D].\n%\n% All nodes of the grid lie on one of LAYERS horizontal lines.\n% The first of these lines is from (A,C) to (B,C), and each\n% successive line is HY units higher.\n%\n% On all the odd numbered lines, there are NODES_PER_LAYER points,\n% equally spaced from A to B, with a spacing of HX.\n%\n% On the even numbered lines, there are NODES_PER_LAYER-1 points,\n% whose values are the midpoints of successive intervals on\n% an odd numbered line. (The grid is staggered).\n%\n% HY = HX * sqrt ( 3 ) / 2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODES_PER_LAYER, the number of grid points on the first\n% horizontal layer of points.\n%\n% Input, integer LAYERS, the number of horizontal layers.\n%\n% Input, integer N, the total number of hex grid points.\n%\n% Input, real BOX(2,2), the values of A, B, C and D\n% that define the coordinate box.\n%\n% Output, real P(2,N), the coordinates of the\n% mesh points, listed one horizontal layer at a time.\n%\n ndim = 2;\n\n if ( nodes_per_layer < 1 )\n p = [];\n return\n end\n\n if ( nodes_per_layer == 1 )\n p(1:ndim,1) = ( box(1:ndim,1) + box(1:ndim,2) ) / 2.0;\n return\n end\n\n [ hx, hy ] = hex_grid_h ( nodes_per_layer, box );\n\n k = 0;\n\n for j = 1 : layers\n\n y = box(2,1) + hy * ( j - 1 );\n\n jmod = mod ( j, 2 );\n\n if ( jmod == 1 )\n\n for i = 1 : nodes_per_layer\n x = box(1,1) + ( box(1,2) - box(1,1) ) * ( i - 1 ) ...\n / ( nodes_per_layer - 1 );\n k = k + 1;\n if ( k <= n )\n p(1,k) = x;\n p(2,k) = y;\n end\n end\n\n else\n\n for i = 1 : nodes_per_layer-1\n x = box(1,1) + ( box(1,2) - box(1,1) ) * ( 2 * i - 1 ) ...\n / ( 2 * nodes_per_layer - 2 );\n k = k + 1;\n if ( k <= n )\n p(1,k) = x;\n p(2,k) = y;\n end\n end\n\n end\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/square_hex_grid/hex_grid_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.9046505447409665, "lm_q1q2_score": 0.7859846225546582}} {"text": "function value = r8_beta_pdf ( alpha, beta, rval )\n\n%*****************************************************************************80\n%\n%% R8_BETA_PDF evaluates the PDF of a beta distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2013\n%\n% Author:\n%\n% Original FORTRAN90 version by Guannan Zhang.\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, real ALPHA, BETA, shape parameters.\n% 0.0 < ALPHA, BETA.\n%\n% Input, real RVAL, the point where the PDF is evaluated.\n%\n% Output, real VALUE, the value of the PDF at RVAL.\n%\n if ( alpha <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BETA_PDF - Fatal error!\\n' );\n fprintf ( 1, ' Parameter ALPHA is not positive.\\n' );\n error ( 'R8_BETA_PDF - Fatal error!' );\n end\n\n if ( beta <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BETA_PDF - Fatal error!\\n' );\n fprintf ( 1, ' Parameter BETA is not positive.\\n' );\n error ( 'R8_BETA_PDF - Fatal error!' );\n end\n\n if ( rval < 0.0 || 1.0 < rval )\n\n value = 0.0;\n\n else\n\n temp = r8_gamma_log ( alpha + beta ) - r8_gamma_log ( alpha ) ...\n - r8_gamma_log ( beta );\n\n value = exp ( temp ) * rval ^ ( alpha - 1.0 ) ...\n * ( 1.0 - rval ) ^ ( beta - 1.0 );\n\n end\n \n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pdflib/r8_beta_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7859846187880368}} {"text": "function a = jacobi ( m, n )\n\n%*****************************************************************************80\n%\n%% JACOBI returns the JACOBI matrix.\n%\n% Formula:\n%\n% if ( J = I - 1 )\n% A(I,J) = 0.5 * sqrt ( ( 4 * J^2 ) / ( 4 * J^2 - 1 ) )\n% else if ( J = I + 1 )\n% A(I,J) = 0.5 * sqrt ( ( 4 * (J-1)^2 ) / ( 4 * (J-1)^2 - 1 ) )\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% M = 4, N = 4\n%\n% 0 0.577350269 0 0\n% 0.577350269 0 0.516397779 0\n% 0 0.516397779 0 0.507092553\n% 0 0 0.507092553 0\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A has a zero diagonal.\n%\n% The eigenvalues of A are the zeros of the Legendre polynomial\n% of degree N. They lie symmetrically in [-1,1], and are also\n% the nodes of Gauss-Legendre quadrature. For the case of N = 4,\n% these eigenvalues are\n%\n% [ -0.861136312, -0.339981044, +0.339981044, +0.861136312 ].\n%\n% It follows that A is singular when N is odd.\n%\n% The J-th Gauss-Legendre weight is twice the square of the first\n% component of the J-th eigenvector of A. For the case of N = 4,\n% the eigenvector matrix is:\n%\n% -0.417046 -0.571028 -0.571028 0.417046\n% 0.622037 0.336258 -0.336258 0.622038\n% -0.571028 0.417046 0.417046 0.571028\n% 0.336258 -0.622037 0.622038 0.336258\n%\n% and the corresponding weights are\n%\n% [ 0.347854845, 0.652145155, 0.652145155, 0.347854845 ]\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Lloyd Trefethen, David Bau,\n% Numerical Linear Algebra,\n% SIAM, 1997, pages 287-292.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of A.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n\n if ( j == i - 1 )\n a(i,j) = 0.5 * sqrt ( ( 4 * j * j ) / ( 4 * j * j - 1 ) );\n elseif ( j == i + 1 )\n a(i,j) = 0.5 * sqrt ( ( 4 * ( j - 1 ) * ( j - 1 ) ) ...\n / ( 4 * ( j - 1 ) * ( j - 1 ) - 1 ) );\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/jacobi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7859620866128086}} {"text": "function [I J] = itriu(sz, k)\n% function [I J] = itriu(sz) % OR\n% I = itriu(sz) OR\n% \n% Return the subindices [I J] (or linear indices I if single output call)\n% in the purpose of extracting an upper triangular part of the matrix of\n% the size SZ. Input k is optional shifting. For k=0, extract from the main\n% diagonal. For k>0 -> above the diagonal, k<0 -> below the diagonal\n%\n% This returnd same as [...] = find(triu(ones(sz),k))\n% - Output is a column and sorted with respect to linear indice\n% - No intermediate matrix is generated, that could be useful for large\n% size problem\n% - Mathematically, A(itriu(size(A)) is called (upper) \"half-vectorization\"\n% of A \n%\n% Example:\n%\n% A = [ 7 5 4\n% 4 2 3\n% 9 1 9\n% 3 5 7 ]\n%\n% I = itriu(size(A)) % gives [1 5 6 9 10 11]'\n% A(I) % gives [7 5 2 4 3 9]' OR A(triu(A)>0)\n%\n% Author: Bruno Luong \n% Date: 21/March/2009\n\nif isscalar(sz)\n sz = [sz sz];\nend\nm=sz(1);\nn=sz(2);\n\n% Main diagonal by default\nif nargin<2\n k=0;\nend\n\nnc = n-max(k,0); % number of columns of the triangular part\nlo = ones(nc,1); % lower row indice for each column\nhi = min((1:nc).'-min(k,0),m); % upper row indice for each column\n\nif isempty(lo)\n I = zeros(0,1);\n J = zeros(0,1);\nelse\n c=cumsum([0; hi-lo]+1); % cumsum of the length\n I = accumarray(c(1:end-1), (lo-[0; hi(1:end-1)]-1), ...\n [c(end)-1 1]);\n I = cumsum(I+1); % row indice\n J = accumarray(c,1);\n J(1) = 1 + max(k,0); % The row indices starts from this value\n J = cumsum(J(1:end-1)); % column indice\nend\n\nif nargout<2\n % convert to linear indices\n I = sub2ind([m n], I, J);\nend\n\nend % itriu\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23391-triangular-and-diagonal-indexing/HalfVectorization/itriu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.7859015165960862}} {"text": "function w = compute(w);\n\n%COMPUTE calculates the fast fourier transform of a waveform object\n% WAVEFORM = COMPUTE(WAVEFORM) calculate frequency spectrum of a waveform.\n% The results of the fast fourier transform is added as new fields\n% in the waveform:\n% FFT_FREQ is a vector of frequencies with N samples\n% FFT_AMP is a vector of spetral amplitudes\n% FFT_PHASE is a vector of phases\n% FFT_DOM is the scalar frequency of the maximum amplitude \n% peak (or dominant frequency. This could change)\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\n% CHECK ARGUMENTS\nif ~strcmpi(class(w),'waveform')\n error('First input must be a waveform object');\nend\n\n\n% STEP THROUGH WAVFORMS ADDING NEW FIELDS\n[N,M] = size(w);\nfor i = 1:N*M\n Fn = get(w(i),'NYQ');\n x = get(w(i),'DATA');\n NFFT=2.^(ceil(log(length(x))/log(2))); % Next highest power of 2\n FFTX=fft(x,NFFT); % Take fft, padding with zeros.\n NumUniquePts = ceil((NFFT+1)/2);\n FFTX=FFTX(1:NumUniquePts); % throw out neg frequencies\n MX=abs(FFTX); % Take magnitude of X\n MX=MX*2; % Multiply by 2 \n MX=MX/length(x); \n PX=phase(FFTX); % Take magnitude of X\n f=(0:NumUniquePts-1)*2/NFFT; \n f=f*Fn;\n w(i) = addfield(w(i),'FFT_FREQ',f');\n w(i) = addfield(w(i),'FFT_AMP',MX);\n w(i) = addfield(w(i),'FFT_PHASE',PX);\n a = find(MX == max(MX));\n w(i) = addfield(w(i),'FFT_DOM',f(a));\nend;\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/deprecated/fft_tools/+wf_fft/compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7857913980931288}} {"text": "function R2 = RodriguesConversion(R1)\n% Rodrigues - converts a Rodrigues rotation vector to rotation matrix or vice versa.\n%\n% Usage:\n% R2 = Rodrigues(R1)\n%\n% Input:\n% R1 : Rodrigues rotation vector (3x1 or 1x3) or rotation matrix (3x3).\n%\n% Output:\n% R2 : rotation matrix (3x3) or Rodrigues rotation vector (3x1 or 1x3).\n%\n% This code follows the algorithm given by\n% [1] R. Hartley and A. Zisserman \"Multiple View Geometry in Computer Vision,\"\n% Cambridge, pp.583-585, 2003.\n%\n% Kim, Daesik\n% Intelligent Systems Research Center\n% Sungkyunkwan Univ. (SKKU), South Korea\n% E-mail : daesik80@skku.edu\n% Homepage: http://www.daesik80.com\n%\n% July 2008 - Original version.\n\n\n[r,c] = size(R1);\n\n%% Rodrigues Rotation Vector to Rotation Matrix\nif ((r == 3) && (c == 1)) || ((r == 1) && (c == 3))\n wx = [ 0 -R1(3) R1(2);\n R1(3) 0 -R1(1);\n -R1(2) R1(1) 0 ];\n \n R1_norm = sqrt(R1(1)^2 + R1(2)^2 + R1(3)^2);\n \n if (R1_norm < eps)\n R2 = eye(3);\n else\n R2 = eye(3) + sin(R1_norm)/R1_norm*wx + (1-cos(R1_norm))/R1_norm^2*wx^2;\n end\n \n %% Rotation Matrix to Rodrigues Rotation Vector\nelseif (r == 3) && (c == 3)\n w_norm = acos((trace(R1)-1)/2);\n if (w_norm < eps)\n R2 = [0 0 0]';\n else\n R2 = 1/(2*sin(w_norm))*[R1(3,2)-R1(2,3);R1(1,3)-R1(3,1);R1(2,1)-R1(1,2)]*w_norm;\n end\nend\n\n\n", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/IPPE_utils/RodriguesConversion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7857860053335803}} {"text": "function [CartPoint,latLong]=randEllipsoidLoc(N,a,f)\n%%RANDELLIPSOIDLOC Generate a random point uniformly distributed on the\n% surface of a reference ellipsoid, such as the WGS-84\n% reference ellipsoid. The point is provided in Cartesian\n% coordinates as well as in terms of latitude and longitude.\n%\n%INPUTS: N The number of random samples on the reference ellipsoid to draw.\n% a The semi-major axis of the reference ellipsoid. If this argument\n% is omitted, the value in Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the reference ellipsoid. If this\n% argument is omitted, the value in Constants.WGS84Flattening is\n% used.\n%\n%OUTPUTS: CartPoint A 3XN matrix of random Cartesian [x;y;z] points on the\n% ellipsoid with the given semi-major axis and flattening\n% factor.\n% latLong A 2XN matrix of ellipsoidal latitude and longitude\n% corresponding to points in CartPoint.\n%\n%The problem of generating a uniformly distributed sample on a reference\n%ellipsoid is number 28 in Chapter 3.4.1 of [1], where the algorithm to do\n%so is given in the back of the book. That algorithm is implemented here,\n%where the general ellipsoid formulation has been modified to support the\n%typical parameterization in terms of a semimajor axis and a flattening\n%factor. The algorithm is a rejection sampling method.\n%\n%Large flattening factor values can make the algorithm slow.\n%\n%REFERENCES:\n%[1] D. Knuth, The Art of Computer Programming: Seminumerical Algorithms,\n% 3rd ed. Reading, MA: Addison-Wesley, 1998, vol. 2.\n%\n%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3)\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<2)\n a=Constants.WGS84SemiMajorAxis;\nend\n\n%The equation for a reference ellipsoid is\n%(x^2+y^2)/a^2+z^2/(a^2*(1-f)^2)=1.\n%The algorithm describe in Knuth's book wants things paramterized in terms\n%of c(1)*x^2+c(2)*y^2+c(3)*z^2=1. Thus, the coefficients are\nc(1,1)=1/a^2;\nc(2,1)=1/a^2;\nc(3,1)=1/(a^2*(1-f)^2);\n\n%The c's have to be sorted. This means that the ordering of the components\n%in x, y, and z will be wrong, so indices to undo the sorting when saving\n%the final result need to be found.\n[c,sortIdx]=sort(c,'descend');\nunsortIdx=1:3;\nunsortIdx=unsortIdx(sortIdx);\n\nn=3;%The number of dimensions.\n\n%Allocate space for the return variables.\nCartPoint=zeros(3,N);\n\nfor curSamp=1:N\n while(1)\n %First, generate a random point on the unit sphere\n y=randDirVec(3);\n rho=sqrt(sum(c.*y.^2));\n\n %Find K\n if(n*c(n)>=c(1))\n K=sqrt(c(n)^(n-1));\n else\n K=sqrt(((n+1)/(c(1)+c(n)))^(n+1)*(c(1)*c(n)/n)^n);\n end\n\n %Generate a uniform random variable U\n U=rand(1);\n\n if(rho^(n+1)*U1)\n point=Cart2Ellipse(CartPoint,[],a,f);\n latLong=point(1: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/Mathematical_Functions/Statistics/randEllipsoidLoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7857860010431152}} {"text": "function a = toeplitz_pds ( m, n, x, y )\n\n%*****************************************************************************80\n%\n%% TOEPLITZ_PDS returns the TOEPLITZ_PDS matrix.\n%\n% Discussion:\n%\n% TOEPLITZ is a Toeplitz matrix that is positive definite symmetric.\n%\n% Formula:\n%\n% A(I,J) = sum ( 1 <= K <= M ) Y(K) * cos ( 2 * PI * X(K) * (I-J) )\n%\n% Example:\n%\n% N = 5, M = 5, \n% X = ( -0.0625, - 0.03125, 0.0, 0.03125, 0.0625 ),\n% Y = ( 0.2, 0.2, 0.2, 0.2, 0.2)\n%\n% 1.000000 0.961866 0.852395 0.685661 0.482843\n% 0.961866 1.000000 0.961866 0.852395 0.685661\n% 0.852395 0.961866 1.000000 0.961866 0.852395\n% 0.685661 0.852395 0.961866 1.000000 0.961866\n% 0.482843 0.685661 0.852395 0.961866 1.000000\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is Toeplitz: constant along diagonals.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A is positive definite or positive semi-definite, depending on\n% the values of X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% George Cybenko, Charles Van Loan,\n% Computing the minimum eigenvalue of a symmetric positive definite\n% Toeplitz matrix,\n% SIAM Journal on Scientific and Statistical Computing,\n% Volume 7, 1986, pages 123-131.\n%\n% Parameters:\n%\n% Input, integer M, the number of terms of W and X.\n%\n% Input, integer N, the order of A.\n%\n% Input, real X(M), used to define the matrix.\n%\n% Input, real Y(M), a set of positive weights used to define the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n a(i,j) = 0.0;\n for k = 1 : m\n angle = 2.0 * pi * x(k) * ( i - j );\n a(i,j) = a(i,j) + y(k) * cos ( angle );\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/toeplitz_pds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7857859988046961}} {"text": "function cg_test ( )\n\n%*****************************************************************************80\n%\n%% CG_TEST tests CG.\n% \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CG_TEST:\\n' );\n fprintf ( 1, ' CG uses the Conjugate Gradient \\n' );\n fprintf ( 1, ' iterative method to approximate the solution \\n' );\n fprintf ( 1, ' of a linear system A * x = b.\\n' );\n\n n = 10;\n\n A = zeros ( n, n );\n\n for i = 1 : n\n A(i,i) = 2.0;\n end\n for i = 1 : n-1\n A(i,i+1) = -1;\n end\n for i = 2 : n\n A(i-1,i) = -1;\n end\n x = [ 1 : n ]';\n b = A * x;\n x = ones ( n, 1 );\n\n M = 0;\n max_it = 10;\n tol = 0.0001;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the order of the system is N = %d\\n', n );\n fprintf ( 1, ' The matrix A is the simple tridiagonal -1, 2, -1.\\n' );\n fprintf ( 1, ' The correct solution is x = [ 1, 2, ..., n].\\n' );\n fprintf ( 1, ' The right hand side b is determined by computing A * x.\\n' );\n fprintf ( 1, ' The exact x is then replaced by a vector of all 1''s for\\n' );\n fprintf ( 1, ' use as a starting guess.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Other parameters are set as follows:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The maximum number of steps is %d.\\n', max_it );\n fprintf ( 1, ' The error tolerance is %f\\n', tol );\n\n [ x, error_norm, iter, flag ] = cg ( A, x, b, M, max_it, tol );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The CG routine has returned with FLAG = %d\\n', flag );\n if ( flag == 0 )\n fprintf ( 1, ' This indicates that the iteration has converged.\\n' );\n elseif ( flag == 1 ) \n fprintf ( 1, ' This indicates that the iteration has NOT converged.\\n' );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of iterations taken was %d\\n', iter );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The L2 norm of the error per iteration:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : iter\n fprintf ( 1, ' %4d %f\\n', i, error_norm(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The computed solution vector X:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %f\\n', i, x(i) );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CG_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/templates/cg_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.7857363106833886}} {"text": "function a = conex3_inverse ( n )\n\n%*****************************************************************************80\n%\n%% CONEX3_INVERSE returns the inverse of the CONEX3 matrix.\n%\n% Example:\n%\n% N = 5\n%\n% 1 0 0 0 0\n% 1 1 0 0 0\n% 2 1 1 0 0\n% 4 2 1 1 0\n% -8 -4 -2 -1 -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Alan Cline, RK Rew,\n% A set of counterexamples to three condition number estimators,\n% SIAM Journal on Scientific and Statistical Computing,\n% Volume 4, 1983, pages 602-611.\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i < n )\n \n if ( j < i )\n a(i,j) = 2.0^(i-j-1);\n elseif ( i == j )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n \n elseif ( i == n )\n \n if ( j < i )\n a(i,j) = - 2.0^(i-j-1);\n else\n a(i,j) = -1.0;\n end\n\n end\n \n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/conex3_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8633916222765629, "lm_q1q2_score": 0.7856060881733375}} {"text": "function [A,U,V] = regutm(m,n,s)\n%REGUTM Test matrix for regularization methods.\n%\n% [A,U,V] = regutm(m,n,s)\n%\n% Generates a random m-times-n matrix A such that A*A' and A'*A\n% are oscillating. Hence, in the SVD of A,\n% A = U*diag(s)*V',\n% the number of sign changes in U(:,i) and V(:,i) is exactly i-1.\n%\n% The third argument s specifies the singular values of A. If not\n% present, then s = logspace(0,round(log10(eps)),n).\n\n% Reference: P. C. Hansen, \"Test matrices for regularization methods\",\n% SIAM J. Sci. Comput. 16 (1995), 506--512.\n\n% Per Christian Hansen, IMM, 07/30/97.\n\n% Initialization.\nif (nargin==1), n = m; end\nif (nargin<3), s = logspace(0,round(log10(eps)),min(m,n)); end\n\n% Special treatment of the case m < n.\nif (m < n), [A,V,U] = regutm(n,m,s); A = A'; return, end\n\n% Generate random bidiagonal matrix with nonnegative elements.\nif (n < 100), mu = .222*n + .0278*n^2; else mu = 3*n; end\nB = abs(diag(randn(n,1)+mu) + diag(randn(n-1,1)+mu,1));\n\n% Compute the SVD of B.\n[U,dummy,V] = svd(B); clear dummy\n\n% Repeat if m > n.\nif (m > n)\n clear U\n B = abs(diag(randn(m,1)+mu) + diag(randn(m-1,1)+mu,1));\n [U,dummy] = svd(B); clear dummy, U = U(:,1:n);\nend\n\n% Compute A.\nA = U*diag(s)*V';", "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/regutm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7855747958843947}} {"text": "function a = hadamard ( m, n )\n\n%*****************************************************************************80\n%\n%% HADAMARD returns a HADAMARD matrix.\n%\n% Definition:\n%\n% A Hadamard matrix is a square matrix A of order N, whose entries are\n% only +1's or -1's, with the property that:\n%\n% A * A' = N * I.\n%\n% Notes:\n%\n% A Hadamard matrix must be of order 1, 2, or else a multiple of 4.\n% It is not known whether a Hadamard matrix exists for every multiple\n% of 4.\n%\n% The method used here allows the user to request a Hadamard matrix\n% of any rectangular order, M by N. The algorithm then essentially\n% finds the largest powers of 2 that are less than or equal to M and\n% N, and produces a Hadamard-like matrix in that space, setting the\n% rest of the matrix to 0. Thus, the matrix returned by this routine\n% is only a Hadamard matrix if M = N = a power of 2.\n%\n% Formula:\n%\n% The following recursive formula is used to produce a series of\n% Hadamard matrices of increasing size.\n%\n% H(0) = [1]\n%\n% H(1) = [ H(0) H(0) ] = [ 1 1]\n% [ H(0) -H(0) ] [ 1 -1]\n%\n% H(2) = [ H(1) H(1) ] = [ 1 1 1 1]\n% [ H(1) -H(1) ] [ 1 -1 1 -1]\n% [ 1 1 -1 -1]\n% [ 1 -1 -1 1]\n%\n% and so on.\n%\n% Properties:\n%\n% All entries of a Hadamard matrix are either +1 or -1. Matrices\n% produced by this routine will be +1 or -1 up to a certain row\n% and column, beyond which the entries will be zero.\n%\n% The Hadamard matrices produced by this routine have the property\n% that the first row and column are entirely 1's, although this\n% is not a requirement for a Hadamard matrix.\n%\n% The matrices produced by this algorithm are (loosely) symmetric,\n% although that is not required for a Hadamard matrix.\n%\n% Hadamard matrices exhibit the maximum possible relative growth of pivot\n% elements during Gaussian elimination with complete pivoting.\n%\n% The inverse of a Hadamard matrix of order N is A itself,\n% scaled by 1.0/N. Thus 1.0/sqrt(N) times a Hadamard matrix\n% yields a symmetric matrix which is its own inverse, or\n% \"involutional\".\n%\n% A is integral: int ( A ) = A.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory and David Karney,\n% Example 3.14,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, New York, 1969, page 42, \n% LC: QA263.G68.\n%\n% William Pratt,\n% Digital Image Processing,\n% John Wiley and Sons, 1978.\n%\n% Herbert Ryser,\n% Combinatorial Mathematics,\n% John Wiley and Sons, 1963.\n%\n% Parameters:\n%\n% Input, integer M, the row order of A.\n%\n% Input, integer N, the column order of A.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HADAMARD - Fatal error!\\n' );\n fprintf ( 1, ' Input value of M = %d\\n', m );\n fprintf ( 1, ' but M must be positive.\\n' );\n error ( 'HADAMARD - Fatal error!' );\n end\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HADAMARD - Fatal error!\\n' );\n fprintf ( 1, ' Input value of N = %d\\n', n );\n fprintf ( 1, ' but N must be positive.\\n' );\n error ( 'HADAMARD - Fatal error!' );\n end\n\n a(1,1) = 1.0;\n\n nn = 1;\n\n while ( nn < n | nn < m )\n\n for i = 1 : nn\n for j = 1 : nn\n\n if ( i <= m & j+nn <= n )\n if ( 2 * nn <= n )\n a(i,j+nn) = a(i,j);\n else\n a(i,j+nn) = 0.0;\n end\n end\n\n if ( i + nn <= m & j <= n )\n if ( 2 * nn <= m )\n a(i+nn,j) = a(i,j);\n else\n a(i+nn,j) = 0.0;\n end\n end\n\n if ( i + nn <= m & j + nn <= n )\n if ( 2 * nn <= m & 2 * nn <= n )\n a(i+nn,j+nn) = - a(i,j);\n else\n a(i+nn,j+nn) = 0.0;\n end\n end\n\n end\n end\n\n nn = 2 * nn;\n\n end\n\n return\nend\n", "meta": {"author": "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/hadamard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7855255707327987}} {"text": "function qwgw_test03 ( )\n\n%*****************************************************************************80\n%\n%% TEST03 tests QWGW for the Gegenbauer weight.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n\n%\n% Set the quadrature interval and number of points.\n%\n a = -1.0;\n b = +1.0;\n n = 5;\n%\n% Set the weight function parameter.\n%\n alpha = 0.25;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST03:\\n' );\n fprintf ( 1, ' Compute points and weights for Gauss quadrature\\n' );\n fprintf ( 1, ' with the Gegenbauer weight w(x) = (1-x^2)^alpha.\\n' );\n fprintf ( 1, ' Order N = %d\\n', n );\n fprintf ( 1, ' ALPHA = %g\\n', alpha );\n fprintf ( 1, ' Interval = [%g,%g]\\n', a, b );\n%\n% Set the recursion coefficients.\n%\n aj = zeros ( n, 1 );\n bj = zeros ( n, 1 );\n\n aj(1:n) = 0.0;\n\n for j = 1 : n - 1\n jr = j;\n bj(j) = ( jr * ( 2.0 * alpha + jr ) ) ...\n / ( 4.0 * ( alpha + jr )^2 - 1.0 );\n end\n bj(n) = 0.0;\n\n bj(1:n) = sqrt ( bj(1:n) );\n\n mu0 = gamma ( alpha + 1.0 ) * gamma ( 0.5 ) / gamma ( alpha + 1.5 );\n%\n% Compute the points and weights.\n%\n [ x, w ] = sgqf ( n, aj, bj, mu0 );\n\n r8vec_print ( n, x, ' Abscissas:' );\n r8vec_print ( n, w, ' Weights:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_golub_welsch/qwgw_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8670357460591569, "lm_q1q2_score": 0.7855255642397947}} {"text": "function [a3,a2,a1,a0] = createTraj3(theta0,thetaf,thetad0,thetadf,tstart,tfinal)\n\t% inputs : initial position, velocity + final position, velocity + initial and final times\n\t% output : a vector specifying the polynomial and can be used with poly functions such as : polyder, polyval, etc.\n\t% create a 3rd order trajectory\n\t% example:\n\t% createTraj3(10,30,0,0,0,1)\n\t%\n\t%\n\t% By: Reza Ahmadzadeh - Matlab/Octave - 2013\n\tT = tfinal - tstart;\n\ta0 = theta0;\n\ta1 = thetad0;\n\ta2 = (-3 * (theta0 - thetaf) - (2 * thetad0+thetadf )*T)/ T ^ 2;\n\ta3 = (2 * (theta0 - thetaf) + (thetad0+thetadf )*T)/ T ^ 3;\n\t\nend\t\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/40278-trajectory-generation-3rd-5th-orders/createTraj3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7854939056500639}} {"text": "function [ d2, p2 ] = poly_power ( d1, p1, n )\n\n%*****************************************************************************80\n%\n%% POLY_POWER computes a power of a polynomial.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/triangle_integrals/poly_power.m\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer D1, the degree of the polynomial.\n%\n% Input, real P1(M1), the polynomial coefficients.\n% M1 = ((D1+1)*(D1+2))/2.\n%\n% Input, integer N, the nonnegative integer power.\n%\n% Output, integer D2, the degree of the power polynomial.\n% D2 = N * D1.\n%\n% Output, real P2(M2), the polynomial power.\n% M2 = ((D2+1)*(D2+2))/2.\n%\n\n%\n% Create P2, a polynomial representation of 1.\n%\n d2 = 0;\n m2 = ( ( d2 + 1 ) * ( d2 + 2 ) ) / 2;\n p2 = zeros ( m2, 1 );\n p2(1) = 1.0;\n%\n% Iterate N times:\n% P2 <= P2 * P1\n%\n for i = 1 : n\n [ d2, p2 ] = poly_product ( d2, p2, d1, p1 );\n end\n\n return\nend\n", "meta": {"author": "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/poly_power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7854939003819046}} {"text": "function geometry_test001 ( )\n\n%*****************************************************************************80\n%\n%% TEST001 tests ANGLE_CONTAINS_POINT_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n ntest = 6;\n n_angle = 12;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST001\\n' );\n fprintf ( 1, ' ANGLE_CONTAINS_POINT_2D sees if a point\\n' );\n fprintf ( 1, ' lies within an angle.\\n' );\n fprintf ( 1, '\\n' );\n%\n% An acute angle (45 degrees)\n%\n for j = 1 : ntest\n\n if ( j == 1 )\n\n p1(1:2,1) = [ 1.0; 0.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ 1.0; 1.0 ];\n\n elseif ( j == 2 )\n\n p1(1:2,1) = [ 1.0; 0.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ 0.0; 1.0 ];\n\n elseif ( j == 3 )\n\n p1(1:2,1) = [ 1.0; -1.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ 0.0; 1.0 ];\n\n elseif ( j == 4 )\n\n p1(1:2,1) = [ 1.0; 0.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ -1.0; 0.0 ];\n\n elseif ( j == 5 )\n\n p1(1:2,1) = [ 1.0; 0.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ 0.0; -1.0 ];\n\n elseif ( j == 6 )\n\n p1(1:2,1) = [ 1.0; 0.0 ];\n p2(1:2,1) = [ 0.0; 0.0 ];\n p3(1:2,1) = [ 1.0; -0.01 ];\n\n end\n\n r8vec_print ( 2, p1, ' Vertex P1' )\n r8vec_print ( 2, p2, ' Vertex P2' )\n r8vec_print ( 2, p3, ' Vertex P3' )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y Inside?\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : n_angle\n\n thetar = i * 2.0 * pi / n_angle;\n%\n% For some bizarre MATLAB peculiarity, I can't say\n% p(1:2) = [ cos ( thetar ), sin ( thetar ) ];\n% MATLAB (Student 6.5) complains that COS has the wrong number\n% of arguments. But write it out like this, and magically, everything\n% is fine. People think I'm crabby for no reason...\n%\n p(1,1) = cos ( thetar );\n p(2,1) = sin ( thetar );\n\n inside = angle_contains_point_2d ( p1, p2, p3, p );\n\n fprintf ( 1, ' %12f %12f %1d\\n', p(1:2,1), inside );\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_test001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7854757100476933}} {"text": "clear all, close all, clc\n\nt = (-3:.01:3)';\n\nUtrue = [cos(17*t).*exp(-t.^2) sin(11*t)];\nStrue = [2 0; 0 .5];\nVtrue = [sin(5*t).*exp(-t.^2) cos(13*t)];\n\nX = Utrue*Strue*Vtrue';\nfigure, imshow(X);\n\n%%\nsigma = 1;\nXnoisy = X+sigma*randn(size(X));\nfigure, imshow(Xnoisy);\n\n%%\n[U,S,V] = svd(Xnoisy);\n\nN = size(Xnoisy,1);\ncutoff = (4/sqrt(3))*sqrt(N)*sigma; % Hard threshold\nr = max(find(diag(S)>cutoff)); % Keep modes w/ sig > cutoff\nXclean = U(:,1:r)*S(1:r,1:r)*V(:,1:r)';\nfigure, imshow(Xclean)\n\n%%\ncdS = cumsum(diag(S))./sum(diag(S)); % Cumulative energy\nr90 = min(find(cdS>0.90)); % Find r to capture 90% energy\n\nX90 = U(:,1:r90)*S(1:r90,1:r90)*V(:,1:r90)';\nfigure, imshow(X90)\n\n%% plot singular values\n\nsemilogy(diag(S),'-ok','LineWidth',1.5), hold on, grid on\nsemilogy(diag(S(1:r,1:r)),'or','LineWidth',1.5)\nplot([-20 N+20],[cutoff cutoff],'r--','LineWidth',2)\naxis([-10 610 .003 300])\nrectangle('Position',[-5,20,100,200],'LineWidth',2,'LineStyle','--')\n \nfigure\nsemilogy(diag(S),'-ok','LineWidth',1.5)\nhold on, grid on\nsemilogy(diag(S(1:r,1:r)),'or','LineWidth',1.5)\nplot([-20 N+20],[cutoff cutoff],'r--','LineWidth',2)\naxis([-5 100 20 200])\n \nfigure\nplot(cdS,'-ok','LineWidth',1.5)\nhold on, grid on\nplot(cdS(1:r90),'ob','LineWidth',1.5)\nplot(cdS(1:r),'or','LineWidth',1.5)\nset(gca,'XTick',[0 300 r90 600],'YTick',[0 .5 0.9 1.0])\nxlim([-10 610])\nplot([r90 r90 -10],[0 0.9 0.9],'b--','LineWidth',1.5)", "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/CH01/CH01_SEC07_1_Truncation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7854756994795361}} {"text": "function diftab = dif_basis ( ntab, xtab )\n\n%*****************************************************************************80\n%\n%% DIF_BASIS computes all Lagrange basis polynomials in divided difference form.\n%\n% Discussion:\n%\n% The I-th Lagrange basis polynomial for a set of NTAB X values XTAB,\n% L(I,NTAB,XTAB)(X) is a polynomial of order NTAB-1 which is zero at\n% XTAB(J) for J not equal to I, and 1 when J is equal to I.\n%\n% The Lagrange basis polynomials have the property that the interpolating\n% polynomial through a set of NTAB data points (XTAB,YTAB) may be\n% represented as\n%\n% P(X) = Sum ( 1 <= I <= N ) YTAB(I) * L(I,NTAB,XTAB)(X)\n%\n% Higher order interpolation at selected points may be accomplished\n% using repeated X values, and scaled derivative values.\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% Reference:\n%\n% Carl deBoor,\n% A Practical Guide to Splines,\n% Springer, 2001,\n% ISBN: 0387953663,\n% LC: QA1.A647.v27.\n%\n% Parameters:\n%\n% Input, integer NTAB, the number of X data points XTAB, and the number of\n% basis polynomials to compute.\n%\n% Input, real XTAB(NTAB), the X values upon which the\n% Lagrange basis polynomials are to be based.\n%\n% Output, real DIFTAB(NTAB,NTAB), the set of divided\n% difference tables. Column I of DIFTAB contains the table for\n% the I-th Lagrange basis polynomial.\n%\n\n%\n% Initialize DIFTAB to the identity matrix.\n%\n diftab(1:ntab,1:ntab) = 0.0;\n for i = 1 : ntab\n diftab(i,i) = 1.0;\n end\n%\n% Compute each Lagrange basis polynomial.\n%\n for i = 1 : ntab\n diftab(1:ntab,i) = ( data_to_dif ( ntab, xtab, diftab(1:ntab,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/divdif/dif_basis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7854545799224523}} {"text": "function c = r8ut_mxm ( n, a, b )\n\n%*****************************************************************************80\n%\n%% R8UT_MXM multiplies two R8UT matrices.\n%\n% Discussion:\n%\n% The R8UT storage format is used for an M by N upper triangular \n% matrix. The format stores all M*N entries, even those which are zero.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrices.\n% N must be positive.\n%\n% Input, real A(N,N), B(N,N), the R8UT factor matrices.\n%\n% Output, real C(N,N), the R8UT product matrix.\n%\n c = zeros ( n, n );\n\n for i = 1 : n\n for j = i : n\n for k = i : j\n c(i,j) = c(i,j) + a(i,k) * b(k,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/linplus/r8ut_mxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.785442249051914}} {"text": "function [X12,x1,x2] = DigitalOscillator(f1,f2,Fs,t1)\n\n% Function to simulate Digital Sinusodial Oscillator\n% Input Variables\n% f1 = first input analog frequency Suggested Range(697-1477)\n% f2 = second input analog frequency Suggested Range(697-1477\n% Fs = Sampling Frequency Default = 8000 cycles/sec\n% t1 = Tone Length Default = .1 sec\n%\n% Output Variables\n% Y = Sine Signal for two given frequencies\n% x1 = Sine Signal for first frequency\n% x2 = Sine Signal for second frequency\n%\n% Rajiv Singla DSP Final Project Fall 2005\n%=====================================================================\n\n% Checking for minimum number of arguments\nif nargin < 2\n error('Not enough input arguments');\nend\n\n% Setting Default values\nif nargin == 2\n Fs = 8000; \n t1 = 0.1;\nend\n\nTs=1/Fs; %Sampling Time \nsamples=t1/Ts; %Number of samples in the tone\n\n\n%% Generating first Signal \nw0=2*3.1416*f1/Fs;\nA=1;\na1=-2*cos(w0);\nY1=0;\nY2=-A*sin(w0);\n\nfor n=1:samples\n x1(n)=-a1*Y1-Y2;\n Y2=Y1;\n Y1=x1(n);\nend\nx1=[0 x1]; %appending zero in the beginning\n\n%% Generating second Signal\nw1=2*3.1416*f2/Fs;\nA=1;\na2=-2*cos(w1);\nP1=0;\nP2=-A*sin(w1);\n\nfor n=1:samples\n x2(n)=-a2*P1-P2;\n P2=P1;\n P1=x2(n);\nend\nx2=[0 x2]; %appending zero in the beginning\n\n%% Combining both signal\nX12 = .5*(x1 + x2);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20552-dtmf-filtering-and-noise-simulator/DTMF/DigitalOscillator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7854422321060996}} {"text": "function value = pyramid_unit_monomial_3d ( alpha, beta, gamma )\n\n%*****************************************************************************80\n%\n%% PYRAMID_UNIT_MONOMIAL_3D: monomial integral in a unit pyramid in 3D.\n%\n% Discussion:\n%\n% This routine returns the integral of X^ALPHA Y^BETA Z^GAMMA over\n% the unit pyramid.\n%\n% The unit pyramid is defined as:\n%\n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer ALPHA, BETA, GAMMA, the exponents of\n% X, Y and Z in the monomial.\n%\n% Output, real PYRAMID_UNIT_MONOMIAL_3D, the volume of the pyramid.\n%\n value = 0.0;\n\n if ( mod ( alpha, 2 ) == 0 & mod ( beta, 2 ) == 0 )\n\n i_hi = 2 + alpha + beta;\n\n for i = 0 : i_hi\n value = value + r8_mop ( i ) * r8_choose ( i_hi, i ) / ( i + gamma + 1 );\n end\n\n value = value * 2.0 / ( alpha + 1 ) * 2.0 / ( beta + 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/stroud/pyramid_unit_monomial_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7854422317437548}} {"text": "function divdif_test20 ( )\n\n%*****************************************************************************80\n%\n%% DIVDIF_TEST20 tests DIF_DERIVK_TABLE;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIVDIF_TEST20\\n' );\n fprintf ( 1, ' For a divided difference polynomial:\\n' );\n fprintf ( 1, ' DIF_DERIVK_TABLE computes the K-th derivative;\\n' );\n%\n% Set the 0 data points.\n%\n n0 = 5;\n x0 = linspace ( -2.0, +2.0, 5 );\n%\n% Set data for x^4/24+x^3/3+x^2/2+x+1\n%\n f0(1:n0) = 1.0;\n for i = 4 : -1 : 1\n f0(1:n0) = f0(1:n0) .* x0(1:n0) / i + 1.0;\n end\n%\n% Compute the difference table.\n%\n d0 = data_to_dif ( n0, x0, f0 );\n dif_print ( n0, x0, d0, ' The divided difference polynomial P0:' );\n\n c0 = dif_to_r8poly ( n0, x0, d0 );\n\n r8poly_print ( n0, c0, ' Using DIF_TO_R8POLY' );\n%\n% Compute the difference table for the K=1 derivative.\n%\n k = 1;\n n1 = n0 - k;\n [ x1, d1 ] = dif_derivk_table ( n0, x0, d0, k );\n%\n% Compute the difference table for the K=2 derivative.\n%\n k = 2;\n n2 = n0 - k;\n [ x2, d2 ] = dif_derivk_table ( n0, x0, d0, k );\n%\n% Compute the difference table for the K=3 derivative.\n%\n k = 3;\n n3 = n0 - k;\n [ x3, d3 ] = dif_derivk_table ( n0, x0, d0, k );\n%\n% Compute the difference table for the K=4 derivative.\n%\n k = 4;\n n4 = n0 - k;\n [ x4, d4 ] = dif_derivk_table ( n0, x0, d0, k );\n%\n% Evaluate all 5 polynomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Evaluate difference tables for the function P0\\n' );\n fprintf ( 1, ' and its first four derivatives, P1...P4.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X P0 P1 P2 P3 P4\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : 10\n x = i / 5.0;\n y0 = dif_val ( n0, x0, d0, x );\n y1 = dif_val ( n1, x1, d1, x );\n y2 = dif_val ( n2, x2, d2, x );\n y3 = dif_val ( n3, x3, d3, x );\n y4 = dif_val ( n4, x4, d4, x );\n fprintf ( 1, ' %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n', ...\n x, y0, y1, y2, y3, y4 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/divdif/divdif_test20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7854338922281596}} {"text": "function varargout = PoissonRatio(C,varargin)\n% computes the Poisson ratio of an elasticity tensor\n%\n% Input\n% C - elastic @stiffnessTensor\n% x - @vector3d\n% y - @vector3d\n%\n% Output\n% nu - Poisson ratio in directions x and y\n%\n% Description\n% \n% $$\\nu = \\frac{-S_{ijkl} x_i x_j y_k y_l}{S_{mnop} x_m x_n x_o x_p}$$ \n%\n\n% take formula using complience\n[varargout{1:nargout}] = PoissonRatio(inv(C),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/@stiffnessTensor/PoissonRatio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7854257894491045}} {"text": "function loc_3d_torus(NumOfSamples)\n\n% Create Localized 3-d data from uniform distribution.\n% Data are bount to the neighborhood near a torus surface.\n% Torus surface equation:\n%\n% (c - sqrt(x^2+y^2))^2 + z^2 = a^2\n%\n% This torus is created by revoloution around z axis of a circle centered\n% at (c,0) with radious a. \n\nclc;\ninput_dims = 3;\n\na = 1;\na1 = .9;\nc = 5;\n% Initialize Data\nData = [];\n\nwhile size(Data,2)=sqrt(a1^2 - (c-sqrt(In1(1,1)^2 + In1(2,1)^2))^2)\n Data = [Data In1];\nend \nend\n\na = randperm(NumOfSamples);\nData = Data(:,a);\n\nsave local_torus Data;\nplot3(Data(1,:),Data(2,:),Data(3,:),'.','MarkerSize',1);\ngrid on;\nclear all;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43572-unsupervised-learning-with-dynamic-cell-structures-dcs-neural-network/Data Generators/loc_3d_torus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7853610951763816}} {"text": "function matreg = Tikhonov_rank_def(mat, rank, lambda)\n\n% Apply Tikhonov regularisation to rank-deficient matrix\n\n% mat: square matrix\n\n% rank: number of singular values to be considered in inversion\n\n% lambda: regularisation parameters\n\n% OH, Sep 2018\n\n\n% SVD of input matrix\n\n[U,S,V] = svd(mat);\n\n\n% get singular values\n\ns = diag(S);\n\n\n% take only relevant values\n\ns2 = s(1:rank);\n\n\nlambda = (lambda/100) * (sum(s2)/rank);\n\n% regularise eigenvalues with Tikhonov and invert\n\ns2 = s2 ./ (s2.^2 + lambda);\n\n\n% reconstitute regularised inverse matrix\n\nmatreg = V(:,1:rank)*diag(s2)*U(:,1:rank)';", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/private/Tikhonov_rank_def.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7853209213823773}} {"text": "function [t,u,v,idx]=raytrace(p0,v0,node,face)\n%\n% [t,u,v,idx]=raytrace(p0,v0,node,face)\n%\n% perform a Havel-styled ray tracing for a triangular surface\n%\n% author: Qianqian Fang, \n%\n% input:\n% p0: starting point coordinate of the ray\n% v0: directional vector of the ray\n% node: a list of node coordinates (nn x 3)\n% face: a surface mesh triangle list (ne x 3)\n%\n% output:\n% t: signed distance from p to the intersection point for each surface\n% triangle, if ray is parallel to the triangle, t is set to Inf\n% u: bary-centric coordinate 1 of all intersection points\n% v: bary-centric coordinate 2 of all intersection points\n% the final bary-centric triplet is [u,v,1-u-v]\n% idx: optional output, if requested, idx lists the IDs of the face\n% elements that intersects the ray; users can manually calc idx by\n%\n% idx=find(u>=0 & v>=0 & u+v<=1.0 & ~isinf(t));\n%\n% Reference: \n% [1] J. Havel and A. Herout, \"Yet faster ray-triangle intersection (using \n% SSE4),\" IEEE Trans. on Visualization and Computer Graphics,\n% 16(3):434-438 (2010)\n% [2] Q. Fang, \"Comment on 'A study on tetrahedron-based inhomogeneous \n% Monte-Carlo optical simulation',\" Biomed. Opt. Express, (in\n% press)\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\np0=p0(:)';\nv0=v0(:)';\n\nAB=node(face(:,2),1:3)-node(face(:,1),1:3);\nAC=node(face(:,3),1:3)-node(face(:,1),1:3);\n\nN=cross(AB',AC')';\nd=-dot(N',node(face(:,1),1:3)')';\n\nRn2=1./sum((N.*N)')';\n\nN1=cross(AC',N')'.*repmat(Rn2,1,3);\nd1=-dot(N1',node(face(:,1),1:3)')';\n\nN2=cross(N',AB')'.*repmat(Rn2,1,3);\nd2=-dot(N2',node(face(:,1),1:3)')';\n\nden=(v0*N')';\nt=-(d+(p0*N')');\nP=(p0'*den'+v0'*t')';\nu=dot(P',N1')'+den.*d1;\nv=dot(P',N2')'+den.*d2;\n\nidx=find(den);\nden(idx)=1./den(idx);\n\nt=t.*den;\nu=u.*den;\nv=v.*den;\n\n % if den==0, ray is parallel to triangle, set t to infinity\nt(find(den==0))=Inf;\n\nif(nargout>=4)\n idx=find(u>=0 & v>=0 & u+v<=1.0 & ~isinf(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/iso2mesh/raytrace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7852944913426346}} {"text": "function mean = discrete_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% DISCRETE_MEAN evaluates the mean of the Discrete PDF.\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 A, the number of probabilities assigned.\n%\n% Input, real B(A), the relative probabilities of\n% outcomes 1 through A. Each entry must be nonnegative.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n b_sum = sum ( b(1:a) );\n\n mean = 0.0;\n for j = 1 : a\n mean = mean + j * b(j);\n end\n\n mean = mean / b_sum;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/discrete_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7852944800587109}} {"text": "% Maximum volume inscribed ellipsoid in a polyhedron \n% Section 8.4.1, Boyd & Vandenberghe \"Convex Optimization\"\n% Original version by Lieven Vandenberghe\n% Updated for CVX by Almir Mutapcic - Jan 2006\n% (a figure is generated)\n%\n% We find the ellipsoid E of maximum volume that lies inside of\n% a polyhedra C described by a set of linear inequalities.\n%\n% C = { x | a_i^T x <= b_i, i = 1,...,m } (polyhedra)\n% E = { Bu + d | || u || <= 1 } (ellipsoid) \n%\n% This problem can be formulated as a log det maximization\n% which can then be computed using the det_rootn function, ie,\n% maximize log det B\n% subject to || B a_i || + a_i^T d <= b, for i = 1,...,m\n\n% problem data\nn = 2;\npx = [0 .5 2 3 1];\npy = [0 1 1.5 .5 -.5];\nm = size(px,2);\npxint = sum(px)/m; pyint = sum(py)/m;\npx = [px px(1)];\npy = [py py(1)];\n\n% generate A,b\nA = zeros(m,n); b = zeros(m,1);\nfor i=1:m\n A(i,:) = null([px(i+1)-px(i) py(i+1)-py(i)])';\n b(i) = A(i,:)*.5*[px(i+1)+px(i); py(i+1)+py(i)];\n if A(i,:)*[pxint; pyint]-b(i)>0\n A(i,:) = -A(i,:);\n b(i) = -b(i);\n end\nend\n\n% formulate and solve the problem\ncvx_begin\n variable B(n,n) symmetric\n variable d(n)\n maximize( det_rootn( B ) )\n subject to\n for i = 1:m\n norm( B*A(i,:)', 2 ) + A(i,:)*d <= b(i); %#ok\n end\ncvx_end\n\n% make the plots\nnoangles = 200;\nangles = linspace( 0, 2 * pi, noangles );\nellipse_inner = B * [ cos(angles) ; sin(angles) ] + d * ones( 1, noangles );\nellipse_outer = 2*B * [ cos(angles) ; sin(angles) ] + d * ones( 1, noangles );\n\nclf\nplot(px,py)\nhold on\nplot( ellipse_inner(1,:), ellipse_inner(2,:), 'r--' );\nplot( ellipse_outer(1,:), ellipse_outer(2,:), 'r--' );\naxis square\naxis off\nhold off\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch08_geometric_probs/max_vol_ellip_in_polyhedra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.785282125345808}} {"text": "function fx = p42_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P42_FUN evaluates the integrand for problem 42.\n%\n% Discussion:\n%\n% The problem has a parameter ALPHA that can be set by calling\n% P42_PARAM_SET.\n%\n% The integrand has a singularity at X = 0 if ALPHA < 1.\n%\n% The suggested range for ALPHA is 0.1 through 2.\n%\n% Interval:\n%\n% 0 <= x <= pi/2\n%\n% Integrand:\n%\n% ( sin(x) )^( alpha - 1 )\n%\n% Exact Integral:\n%\n% 2^( alpha - 2 ) * ( Gamma(alpha/2) )^2 / Gamma(alpha)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Piessens, Elise de Doncker-Kapenga,\n% Christian Ueberhuber, David Kahaner,\n% QUADPACK: A Subroutine Package for Automatic Integration,\n% Springer, 1983, page 84.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n alpha = p42_param_get ( );\n\n fx = sin ( x ).^( alpha - 1.0 );\n\n if ( alpha < 1.0 )\n i = find ( x == 0.0 );\n fx(i) = 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/test_int/p42_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7852096788697981}} {"text": "function c=addlogs(a,b)\n%ADDLOGS Add numbers represented by their logarithms.\n%\n% Description\n% C=ADDLOGS(A,B) computes C=log(exp(A)+exp(B)) in such a fashion\n% that it works even when A and B have large magnitude.\n\n% Copyright (c) 2003 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 a>b\n c = a + log(1+exp(b-a));\nelse\n c = b + log(1+exp(a-b));\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/misc/addlogs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.949669373100424, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7851028752644014}} {"text": "function [Gausspoint,Gaussweight] = GaussQuadrature(ngl)\n%-------------------------------------------------------------------\n% Purpose:\n% determine the integration points and weighting coefficients\n% of Gauss-Legendre quadrature for two-dimensional integration\n%\n% Synopsis:\n% [point,weight]=GaussQuadrature(nglx,ngly) \n%\n% Variable Description:\n% ngl - number of integration points\n% point - vector containing integration points \n% weight - vector containing weighting coefficients \n%-------------------------------------------------------------------\n% initialization\n \n Gausspoint=zeros(ngl,1);\n Gaussweight=zeros(ngl,1);\n \n% corresponding integration points and weights\n % 2-point quadrature rule\n Gausspoint(1)=-0.577350269189626;\n Gausspoint(2)=-Gausspoint(1);\n Gaussweight(1)=1.0;\n Gaussweight(2)=Gaussweight(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/32519-stress-recovery/Stress Recovery/GaussQuadrature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7851028732371125}} {"text": "function [ R ] = R_rpy( roll, pitch, yaw )\n%R_RPY この関数の概要をここに記述\n% Camera rotates (1) yaw (y-axis) (2)pitch (x'-axis) (3)roll (z''-axis)\n\nrrad = -roll * pi / 180.0;\nprad = -pitch * pi / 180.0;\nyrad = -yaw * pi / 180.0;\n\nRr = [cos(rrad), -sin(rrad), 0;...\n sin(rrad), cos(rrad), 0;...\n 0, 0, 1];\n\nRp = [1, 0, 0;...\n 0, cos(prad), -sin(prad);...\n 0, sin(prad), cos(prad)];\n \nRy = [cos(yrad), 0, sin(yrad);...\n 0, 1, 0;...\n -sin(yrad), 0, cos(yrad)];\n \nR = Rr * Rp * Ry;\n\n\nend\n\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/R_rpy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7851028644720123}} {"text": "function s = CubicTimeScaling(Tf, t)\n% *** CHAPTER 9: TRAJECTORY GENERATION ***\n% Takes Tf: Total time of the motion in seconds from rest to rest,\n% t: The current time t satisfying 0 < t < Tf.\n% Returns s: The path parameter s(t) corresponding to a third-order \n% polynomial motion that begins and ends at zero velocity.\n% Example Input: \n% \n% clear; clc;\n% Tf = 2;\n% t = 0.6;\n% s = CubicTimeScaling(Tf,t)\n% \n% Output:\n% s =\n% 0.2160\n\ns = 3 * (t / Tf) ^ 2 - 2 * (t / Tf) ^ 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/CubicTimeScaling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7851028627726951}} {"text": "function transformationMatrix = create_transformation_matrix3d(varargin)\n% CREATE_TRANSFORMATION_MATRIX3D Create a 3D transformation matrix\n%\n% [transformationMatrix rotationMatrix shearMatrix scaleMatrix] = ...\n% create_transformation_matrix3d()\n% \n% INPUT ARGUMENTS\n% N/A\n%\n% Optional input arguments\n% 'phiX' - Rotation angle around x-axis\n% 'phiY' - Rotation angle around y-axis\n% 'phiZ' - Rotation angle around z-axis\n% 'shearXY' - Shear XY\n% 'shearXZ' - Shear XZ\n% 'shearYX' - Shear YX\n% 'shearYZ' - Shear YZ\n% 'shearZX' - Shear ZX\n% 'shearZY' - Shear ZY\n% 'scaleX' - Scale along x-axis\n% 'scaleY' - Scale along y-axis\n% 'scaleZ' - Scale along z-axis\n% 'translationX' - Translation along x-axis\n% 'translationY' - Translation along y-axis\n% 'translationZ' - Translation along z-axis\n%\n% OUTPUT ARGUMENTS\n% transformationMatrix - Total transformation matrix\n% rotationMatrix - Rotation matrix\n% shearMatrix - Shear matrix\n% scaleMatrix - Scale matrix\n\n% Copyright (c) 2012 Daniel Forsberg\n% danne.forsberg@outlook.com\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nphiX = 0;\nphiY = 0;\nphiZ = 0;\nshearXY = 0;\nshearXZ = 0;\nshearYX = 0;\nshearYZ = 0;\nshearZX = 0;\nshearZY = 0;\nscaleX = 1; \nscaleY = 1;\nscaleZ = 1;\ntranslationX = 0;\ntranslationY = 0;\ntranslationZ = 0;\n\nfor k=1:2:length(varargin), % overwrites default parameter\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\nrotationX = [1 0 0; \n 0 cos(phiX) -sin(phiX); \n 0 sin(phiX) cos(phiX)];\nrotationY = [cos(phiY) 0 sin(phiY); \n 0 1 0; \n -sin(phiY) 0 cos(phiY)];\nrotationZ = [cos(phiZ) -sin(phiZ) 0; \n sin(phiZ) cos(phiZ) 0; \n 0 0 1];\n\nshearMatrix = [1 shearXY shearXZ;\n shearYX 1 shearYZ;\n shearZX shearZY 1];\n\nscaleMatrix = [scaleX 0 0;\n 0 scaleY 0;\n 0 0 scaleZ];\n \n\ntransformationMatrix = zeros(3,4);\ntransformationMatrix(1:3,1:3) = rotationX*rotationY*rotationZ*shearMatrix*scaleMatrix;\ntransformationMatrix(:,4) = [translationX translationY translationZ]';\n", "meta": {"author": "fordanic", "repo": "image-registration", "sha": "36c23d5da1f035b07c66a04fe5bac20de1bd1c74", "save_path": "github-repos/MATLAB/fordanic-image-registration", "path": "github-repos/MATLAB/fordanic-image-registration/image-registration-36c23d5da1f035b07c66a04fe5bac20de1bd1c74/registration/transformation/create_transformation_matrix3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.785074527517936}} {"text": "function [p,c,v] = matrixpolynomial(x,n,dmax,dmin)\n%MATRIXPOLYNOMIAL Creates parameterized polynomial\n%\n% [p,c,v] = matrixpolynomial(x,n,dmax,dmin)\n%\n% MATRIXPOLYNOMIAL is a quick way to define a parameterized polynomial \n% p=sum C_i v_i(x) with all monomials of dmin <= degree(p,x) <= dmax. The\n% coefficients in the polynomial are C_i while v is the monomial basis.\n%\n% Example:\n%\n% Paramterized quartic 2x2 matrix\n% x = sdpvar(2,1);\n% p = matrixpolynomial(x,2,4);\n%\n% See also MONOLIST, COEFFICIENTS\n\nif (length(dmax) > 1) && (length(dmax) ~= length(x))\n error('Dimension mismatch: The third argument should be the max degree for each variable, or a sclar');\nend\n\nif nargin > 3\n if (length(dmin) > 1) && (length(dmin) ~= length(x))\n error('Dimension mismatch: The third argument should be the max degree for each variable, or a sclar');\n end\nend\n\nif any(dmax < 0)\n error('Only non-negative polynomial degrees possible')\nend\n\nif nargin<4\n dmin = 0;\nend\n\nif any(dmin > dmax)\n error('Fourth argument (dmin) should not be larger than second argument (dmax)');\nend\n\nif any(dmin < 0)\n error('Only non-negative polynomial degrees possible')\nend\n\nif length(n)==1\n n = [n n];\nend\n\nv = monolist(x,dmax);\n\nif dmin <= dmax & dmin>0\n s = nchoosek(length(x) + dmin-1,dmin-1);\n v = extsubsref(v,s+1:length(v));\nend\n\np = 0;\nc = [];\nfor i = 1:length(v)\n Ci = sdpvar(n(1),n(2));\n c = [c reshape(Ci,[],1)];\nend\np = reshape(c*v,n(1),n(2));\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/matrixpolynomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7850283829602304}} {"text": "%% Example:\n% Compute the tridiagonal matrix used to solve implicitly a laplace (heat)\n% equation.\n\nm = 5; % domain size.\nh = 0.1; % delta x value.\n\nI = eye(m);\ne = ones(1,m);\nx = spdiags([e' -4*e' e'],[-1 0 1],m,m);\n%x = zeros(m);\n%x = x+spdiags([e' -4*e' e'],[-1 0 1],m,m);\ns = spdiags([e',e'],[-1 1],m,m);\ns = zeros(m);\ns = s+spdiags([e',e'],[-1 1],m,m);\n%kron(I,x);\n%kron(s,I);\nA = (kron(I,x)+kron(s,I))/h^2;\n%size(A);", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/NumericalMethods/Example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.785026468553003}} {"text": "% GENERATE BILINEAR TIME-FREQUENCY TRANSFORMATIONS USING THE DIRECT METHOD\n%\n% BILINEAR TRANSFORMATIONS transform the time domain signal (the\n% variable INPUT SIGNAL) to an output time-frequency distribution (the\n% variable OUTPUT TIME-FREQUENCY ARRAY)\n%\n% These functions use a direct implementation rather than using the\n% quadratic time-frequency implementation. This results in a\n% computationally optimised routine.\n% \n% The different types of time-frequency distributions that can be\n% implemented directly are:\n% \n% (i) Wigner-Ville Distribution \n% (ii) Short-Time Fourier Transform\n% (iii) Short-Time Fourier Transform(overlap)\n% (iv) Rihaczek\n% (v) Windowed-Rihaczek\n%\n% The various parameters associated with the distributions are as follows:\n%\n% TIME-FREQUENCY ARRAY (tfd)\n%\n% The computed time-frequency distribution. size(tfd) will\n% return [a, b], where a is the next largest power of two above\n% FFT length, and b is floor(length(signal)/time_res) - 1.\n%\n% INPUT SIGNAL\n%\n% Input one dimensional signal to be analysed. An analytic signal\n% is required for this function, however, if signal is real, a\n% default analytic transformer routine will be called from this\n% function before computing tfd.\n%\n% TIME RESOLUTION\n%\n% The number of time samples to skip between successive time slices.\n%\n% LAG WINDOW LENGTH\n%\n% This is the lag window length and controls the size of the\n% signal kernel (or instantaneous autocorrelation function) used\n% for analysis (lag_window_length must be odd). The kernel used\n% will be defined from -(lag_window_length+1)/2 to\n% +(lag_window_length+1)/2 in both time and lag dimensions.\n%\n% FFT Length:\n%\n% Zero-padding at the FFT stage of the analysis may be specified\n% by giving an FFT length larger than lag window length. If\n% FFT length is not specified, or is smaller than the\n% lag window length, then the next highest power of two above\n% lag window length is used. If FFT length is not a power of\n% two, the next highest power of two is used.\n%\n%\n%\n% See Also: wvd, spec, rihaczek, analyt\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tfsa_7.0/win64_bin/help/direct_method_tfsa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7850264678695041}} {"text": "function [c4,m4,c2] = cum4(X,prewhiten)\n%CUM4 Fourth-order cumulant tensor.\n% [c4,m4,c2] = cum4(X) computes the second-order cumulant (covariance\n% matrix) c2, fourth-order moment m4 and fourth-order cumulant\n% (quadricovariance tensor) c4 of a matrix X in which each row is an\n% observation and each column is a variable. Herein,\n%\n% c2(i,j) = E[xi.*conj(xj)]\n% m4(i,j,k,l) = E[xi.*conj(xj).*conj(xk).*xl]\n% c4(i,j,k,l) = E[xi.*conj(xj).*conj(xk).*xl] ...\n% - E[xi.*conj(xj)]*E[conj(xk).*xl] ...\n% - E[xi.*conj(xk)]*E[conj(xj).*xl] ...\n% - E[xi.*xl]*E[conj(xj).*conj(xk)]\n%\n% where the expectation E is approximated by the arithmetic mean and xi\n% is the i-th mean centered variable, X(:,i)-mean(X(:,i)) (and\n% analogously for xj, xk and xl).\n%\n% [c4,m4,c2] = cum4(X,'prewhiten') applies a linear transformation to the\n% columns of X so that the covariance matrix of the new matrix is the\n% identity matrix before computing its fourth-order cumulant.\n%\n% See also cov, scov.\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] P. McCullagh, \"Tensor Methods in Statistics,\" Chapman and Hall,\n% London, 1987.\n% [2] C. Nikias, A. Petropulu, \"Higher-Order Spectra Analysis: A \n% Nonlinear Signal Processing Framework,\" Prentice Hall, 1993.\n\n% Check the prewhiten option.\nif nargin < 3, prewhiten = false; end\nif ischar(prewhiten), prewhiten = strcmpi(prewhiten,'prewhiten'); end\n\n% Center the variables.\nX = bsxfun(@minus,X,mean(X));\n\n% Apply a prewhitening to X if requested.\nn = size(X,1);\nif prewhiten\n [U,S,~] = svd(X,'econ');\n X = U*(S*pinv(S))*sqrt(n);\nend\n\n% Compute c2 = E[xi*conj(xj)] and r2 = E[xi*xj].\nc2 = conj(X'*X)/n;\nr2 = (X.'*X)/n;\n\n% Compute m4 = E[xi*conj(xj)*conj(xk)*xl].\n% Introduce singleton dimensions 3 and 4.\nm4 = bsxfun(@times,permute(X,[2 3 4 5 1]),permute(conj(X),[3 2 4 5 1]));\nm4 = mean(bsxfun(@times,m4,permute(m4,[3 4 2 1 5])),5);\n\n% Compute c4(i,j,k,l) = m4 - E[xi.*conj(xj)]*E[conj(xk).*xl] - ...\n% E[xi.*conj(xk)]*E[conj(xj).*xl] - E[xi.*xl]*E[conj(xj).*conj(xk)].\nc4 = m4-bsxfun(@times,c2,permute(c2,[3 4 2 1])) ...\n -bsxfun(@times,permute(c2,[1 3 2 4]),permute(c2,[3 2 4 1])) ...\n -bsxfun(@times,permute(r2,[1 3 4 2]),permute(conj(r2),[3 1 2 4]));\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/cum4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8615382023207901, "lm_q1q2_score": 0.785016125198808}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve the following exercises:\n% A) Exercise A: Use the Runge-Kutta 4 algorithm to integrate the\n% differential equation:\n% dy/dt = 2*t\n% Integrate from t0=0, to tfinal = 10 s.\n% Compare the solution with the algebraic integration.\n% B) Exercise B: Use the Runge-Kutta 4 algorithm to integrate the\n% second order differential equation:\n% d2y/dt^2+5*dy/dt + 4*y(t) = 0\n%\n% C) Exercise C: Use the Runge-Kutta 4 algorithm to simulate the movement\n% of a 1 dof robot arm with friction under the effect of gravity and with\n% zero torque applied.\n%\n% D) Exercise D: Use the Runge-Kutta 4 algorithm to simulate the movement\n% of a 2 dof robot arm with friction under the effect of gravity and with\n% zero torques applied.\n%\n% Help: Function prototype\n% [y, t] = runge_kutta(f, y0, [t0 tfinal], timestep)\n% where f is the function being integrated as dy/dt = f(t, y).\n% y0 are the initial conditions\n% t0: initial time\n% tfinal: final time.\n% h: time step for the calculations.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction runge_kutta_exercises()\nclose all;\n\n%uncomment to execute each of the exercises\n% exerciseA()%\nexerciseB()\n%exerciseC()\n%exerciseD()\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Integrate a simple time function. dy/dt = 2*ts\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseA()\nt0 = 0;\ntfinal = 10;\n[t, y] = runge_kutta(@line, 0, [t0 tfinal], 1);\n\n%Compare with the integral of 2*t\nerror = y(:)-t(:).^2;\nmean(error)\nplot(t, y)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Use Runge-Kutta to integrate a second order equation of the form.\n% d2y/dt^2+5*dy/dt + 4*y(t) = 0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseB()\nt0 = 0;\ntfinal = 10;\n% initial values\n[t, y] = runge_kutta(@second_order_system, [10 1]', [t0 tfinal], 0.01);\n\ny = y(:, 1:length(t)); \n%plot results\nplot(t, y(1,:)), hold\nplot(t, y(2,:)), hold\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Now use Runge-kutta to integrate the movement of a 1 dof robot arm\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseC()\n%these variables are shared by the forward_dynamic_robot1 function defined\n%below\nglobal robot tau g\nt0 = 0;\ntfinal = 10;\nrobot = load_robot('example','1dofplanar')\nrobot.dynamics.friction=0\ntau = [0];\ng = [0 -9.81 0]';\n[t, y] = runge_kutta(@forward_dynamic_robot1, [0 0]', [t0 tfinal], 0.01);\n\nfigure, plot(y')\n% Animate the movement. Change speed from 1-30-100-200\nspeed = 5\nanimate(robot,[y(1,1:speed:length(y)); y(2,1:speed:length(y))])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Now use Runge-Kutta to simulate the movement of a 2 DOF robot arm.\nfunction exerciseD()\nglobal robot tau g\nt0 = 0;\ntfinal = 10;\ntau = [0 0];\ng = [0 -9.81 0]';\nrobot = load_robot('example','2dofplanar')\nrobot.dynamics.friction=1\n\n[t, y] = runge_kutta(@forward_dynamic_robot2, [0 0 0 0]', [t0 tfinal], 0.01);\n\n%speed, change to 10, 30, 50, 100\nspeed = 5\nanimate(robot,[y(1,1:speed:length(y)); y(2,1:speed:length(y))])\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function.\n% The function returns dy/dt = 2*t. Function called from exerciseA()\n%\n% Integrate a line in time. dy/dt = 2*t. Obviously, the integration should\n% yield. y(t) = t^2\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction dy = line(t, y)\ndy = 2*t;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to solve a second order differential equation.\n% Called from function exerciseB()\n%\n% In order to solve for d2y/dt^2 + 5*dy/dt + 4*y(t) = 0. We can use:\n% x1 = y\n% x2 = dy/dt\n% thus,\n% dx1/dt = x2\n% dx2/dt = d2y/dt^2=-5*dy/dt-4*y\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = second_order_system(t, y)\n% We must return the solution of\n% [dx1/dt; dx2/dt]\nxd(1) = y(2);\nxd(2) = 0 - 5*y(2)-4*y(1);\nxd = xd(:);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to simulate the movement of a 1 DOF robot\n% Called from function exerciseC()\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = forward_dynamic_robot1(t, y)\nglobal tau g robot\n\nqdd = accel(robot, y(1), y(2), tau, g);\n%return qd, qdd\nxd = [y(2); qdd];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to simulate the movement of a 2 DOF robot\n% Called from function exerciseD()\n% t is only used to plot time on screen during simulation.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = forward_dynamic_robot2(t, y)\nglobal tau g robot\n%we must return the solution of\n% [dx1/dt; dx2/dt]\nt\n% caution, g in the forwarddynamics_2dofplanar takes the opposite sign\nqdd=forwarddynamics_2dofplanar(robot, y(1:2,1), y(3:4,1), tau', -sum(g), [0 0 0 0 0 0]);\nxd = [y(3:4,1); qdd];\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/simulation/solution/runge_kutta_exercises.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7849631091833481}} {"text": "function [phi_g, ip, x_g, w_g] = boundary(i_bnd, x_local, n_gauss)\n\n% Compute values of 2D quadratic bases at 1D Gauss points along a boundary\n% Also return a list of (3) indices for the non-zero basis functions, \n% the co-ords of the Gauss points and the 1D integration weights\n%\n% i_bnd specifies the triangle boundary of interest\n% 1 - along s = 0 boundary - points [1 4 2]\n% 2 - along r+s = 1 boundary - points [2 5 3]\n% 3 - along r = 0 boundary - points [3 6 1]\n% x_local 6 x 2 array of nodal coordinate points (x, y)\n% n_gauss the number of Gauss points for the 1D integration\n \n% phi_g is a n_gauss array x 3 - values of the 3 non-zero quadratic basis\n% functions at the n_gauss 1D integration points\n% ip array of indices for non-zero quadratic functions\n% x_g is an n_gauss x 2 array of coordinates for the 1D Gauss points\n% w_g is an n_gauss array of integration weights\n\n%% extract the Gauss weights and points on [- 1, 1];\n [r, w_g] = oned_gauss(n_gauss); % 1 \\le n_gauss \\le 6\n \n r1 = (1+r)/2; % map to [0, 1]\n r1 = r1(:); % make sure it's a column\n \n%% which boundary is requested \n switch i_bnd\n case {1}\n ip = [ 1 4 2];\n case {2}\n ip = [ 2 5 3];\n case {3}\n ip = [ 3 6 1];\n otherwise\n disp(['Illegal i_bnd = ', int2str(i_bnd)])\n return\n end\n \n%% Coordinates of the Gauss points\n x_g = (1-r1)*x_local(ip(1),:) ...\n + r1 *x_local(ip(3),:);\n\n%% Scale the weights by the (unsigned) length of the interval\n djac = norm(x_local(ip(3), :) - x_local(ip(1), :))/2; \n w_g = w_g*djac;\n \n%% Evaluate the test functions\n \n p1 = 1 -3*r1 + 2*r1.^2; % p1(r = 0) = 1\n p2 = 4*r1 - 4*r1.^2; % p2(r = 1/2)= 1\n p3 = - r1 + 2*r1.^2; % p3(r = 1) = 1\n\n phi_g = [p1(:) p2(:) p3(:) ]; \n\n return\nend\n", "meta": {"author": "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/boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7849630983921426}} {"text": "function [y,exitCode]=geometricMedian(x,eta,AbsTol,RelTol,maxIter,test4Duplicates)\n%%GEOMETRICMEDIAN Compute the weighted geometric median of the (possibly\n% multivariate) points x. This finds the vector y that minimizes\n% sum_i eta(i)*norm(y-x(:,i),1) where all eta(i)>0.\n% The geometric median is also known as the L1-median and the\n% spatial median. \n%\n%INPUTS: x The xDimXN set of N real vectors whose geometric median is\n% desired.\n% eta The NX1 or 1XN set of all positive weights. If this parameter is\n% omitted or an empty matrix is passed, then uniform weights are\n% used.\n% AbsTol, RelTol Absolute and relative tolerances for determining\n% convergence. If diff is the difference between the estimate at\n% the current and the previous iteration, then convergence is\n% declared if diff= 2 )\n if ( nargin >= 5 )\n v = vects;\n else\n v = eye(n);\n end;\nend;\n\nfor its = 1 : Nmax\n\n if ( togo == 1 )\n\t lambda(1) = a(1) + shift;\n\t disp ( its );\n\t return;\n\tend;\n\t\n trace = a(togo-1) + a(togo);\n\tdet = a(togo-1)*a(togo) - b(togo)*b(togo);\n\tdisc = sqrt ( trace*trace - 4*det );\n\tmu1 = (1/2) * ( trace + disc );\n\tmu2 = (1/2) * ( trace - disc );\n\tif ( abs ( mu1 - a(togo) ) < abs ( mu2 - a(togo) ) )\n\t s = mu1;\n\telse\n\t s = mu2;\n\tend;\n\n shift = shift + s;\n\tfor i = 1:togo \n\t a(i) = a(i) - s;\n\tend;\n\t\n\toldb = b(2);\n for i = 2:togo\n j = i-1;\n\t r = sqrt ( a(j)^2 + oldb^2 );\n\t c(i) = a(j) / r;\n\t s(i) = oldb / r;\n\t a(j) = r;\n\t temp1 = c(i)*b(i) + s(i)*a(i);\n\t temp2 = -s(i)*b(i) + c(i)*a(i);\n\t b(i) = temp1;\n\t a(i) = temp2;\n\t if ( i ~= togo ) oldb = b(i+1); b(i+1) = c(i)*b(i+1); end;\n end;\n\n a(1) = c(2)*a(1) + s(2)*b(2);\n b(2) = s(2)*a(2);\n for i = 2:togo-1\n a(i) = s(i+1)*b(i+1) + c(i)*c(i+1)*a(i);\n\t b(i+1) = s(i+1)*a(i+1);\n end;\n a(togo) = c(togo)*a(togo);\n\t\n\tif ( nargout >= 2 )\n\t for i = 2 : togo\n\t col1 = v(:,i-1) * c(i) + v(:,i) * s(i);\n\t\t v(:,i) = -s(i) * v(:,i-1) + c(i) * v(:,i);\n\t\t v(:,i-1) = col1;\n\t end;\n\tend;\n\t\n\tif ( abs(b(togo)) < TOL )\n\t lambda(togo) = a(togo) + shift;\n\t disp([lambda(togo) its]);\n\t togo = togo - 1;\n\tend;\n\nend;\n\ndisp ( 'qrst error: Maximum number of iterations exceeded' );\ndisp ( sprintf ( '%d eigenvalues determined \\n', n-togo ) );", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/QuadratureMethods/trideigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7847035666182693}} {"text": "function [a,b,c,d]=getplanefrom3pt(plane)\n%\n% [a,b,c,d]=getplanefrom3pt(plane)\n% \n% define a plane equation ax+by+cz+d=0 from three 3D points\n%\n% author: Qianqian Fang, \n%\n% input: \n% plane: a 3x3 matrix with each row specifying a 3D point (x,y,z)\n%\n% output:\n% a,b,c,d: the coefficient for plane equation ax+by+cz+d=0\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nx=plane(:,1);\ny=plane(:,2);\nz=plane(:,3);\n\n% compute the plane equation a*x + b*y +c*z +d=0\n\na=y(1)*(z(2)-z(3))+y(2)*(z(3)-z(1))+y(3)*(z(1)-z(2));\nb=z(1)*(x(2)-x(3))+z(2)*(x(3)-x(1))+z(3)*(x(1)-x(2));\nc=x(1)*(y(2)-y(3))+x(2)*(y(3)-y(1))+x(3)*(y(1)-y(2));\nd=-det(plane);\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/getplanefrom3pt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7846433575539723}} {"text": "function euler_m = dcm2euler_m(DCMnb_m)\n% dcm2euler_m: transforms a nav-to-body DCM matrix to an Euler angles matrix.\n%\n% INPUT\n% DCMnb_m: Nx9 matrix with nav-to-body direct cosine matrices (DCM).\n% Each row of DCMnb_m contains the 9 elements of a particular DCMnb\n% matrix ordered as [a11 a21 a31 a12 a22 a32 a13 a23 a33].\n%\n% OUTPUT\n% euler_m: Nx3 Euler angles ordered by column, [roll pitch yaw] (rad, rad, rad).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n% \tTitterton, D.H. and Weston, J.L. (2004). Strapdown\n% Inertial Navigation Technology (2nd Ed.). Institution\n% of Engineering and Technology, USA. Eq. 11.4. Eq. 3.66, p. 46.\n%\n% R. Gonzalez, J. Giribet, and H.D. Patiño,. An approach to\n% benchmarking of loosely coupled low-cost navigation systems,\n% Mathematical and Computer Modelling of Dynamical Systems, vol. 21,\n% issue 2, pp. 272-287. Eq. 15.\n%\n% Version: 001\n% Date: 2020/12/17\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\n[N,~] = size (DCMnb_m);\n\neuler_m = zeros(N,3);\n\nfor i=1:N\n \n DCMnb = reshape(DCMnb_m (i,:), 3, 3);\n DCMbn = DCMnb'; % nav-to-body > body-to-nav\n \n euler_m (i,:) = dcm2euler(DCMbn); % phi theta psi\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/conversions/dcm2euler_m.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7846433522721641}} {"text": "function imchi=kkimbook2(omega,rechi,alpha)\n%The program inputs are the vector of the frequency (or energy)\n%components, the vector of the real part of the susceptibility\n%under examination, and the value of the moment considered.\n%The two vectors must have the same length \n%and the frequency vector omega must be equispaced. \n%If not, apply MATLAB functions such as interp.\n%If rechi is the real part of a linear susceptibility, \n%alpha must be 0. \n%If rechi is the real part of the nth \n%harmonic generation susceptibility, alpha=0,1,..2n. \n%If rechi is the real part of a pump and probe\n%susceptibility, alpha=0 or 1.\n%This files accompanies the book \n%\"Kramers-Kronig Relations in Optical Materials Research\"\n%by Lucarini, V., Saarinen, J.J., Peiponen, K.-E., Vartiainen, E.M. \n%Springer, Heidelberg, 2005\n%where the theory and applications are fully developed.\n%The output is the estimate of the imaginary part as obtained\n%with K-K relations.\n%This software is distributed under the GNU licence agreement\n%by Valerio Lucarini\n%email: lucarini@alum.mit.edu\n%University of Camerino\n%Department of Mathematics and Computer Science\n%Camerino, Italy\n\nif size(omega,1)>size(omega,2);\nomega=omega';\nend; if size(rechi,1)>size(rechi,2);\nrechi=rechi';\nend;\n%Here the program rearranges the two vectors so that,\n%whichever their initial shape, they become row vectors.\n\ng=size(omega,2);\n%Size of the vectors.%\n\nimchi=zeros(size(rechi));\n%The output is initialized.\n\na=zeros(size(rechi));\nb=zeros(size(rechi));\n%Two vectors for intermediate calculations are initialized\n\ndeltaomega=omega(2)-omega(1);\n%Here we compute the frequency (or energy) interval\n\nj=1;\nbeta1=0;\nfor k=2:g;\nb(1)=beta1+rechi(k)*omega(k)^(2*alpha)/(omega(k)^2-omega(1)^2);\nbeta1=b(1);\nend;\nimchi(1)=-2/pi*deltaomega*b(1)*omega(1)^(1-2*alpha);\n%First element of the output: the principal part integration\n%is computed by excluding the first element of the input\n\nj=g;\nalpha1=0;\nfor k=1:g-1;\na(g)=alpha1+rechi(k)*omega(k)^(2*alpha)/(omega(k)^2-omega(g)^2);\nalpha1=a(g);\nend;\nimchi(g)=-2/pi*deltaomega*a(g)*omega(g)^(1-2*alpha);\n%Last element of the output: the principal part integration\n%is computed by excluding the last element of the input.\n\nfor j=2:g-1; ;\n%Loop on the inner components of the output vector.\nalpha1=0;\nbeta1=0;\nfor k=1:j-1;\na(j)=alpha1+rechi(k)*omega(k)^(2*alpha)/(omega(k)^2-omega(j)^2);\nalpha1=a(j);\nend;\nfor k=j+1:g;\nb(j)=beta1+rechi(k)*omega(k)^(2*alpha)/(omega(k)^2-omega(j)^2);\nbeta1=b(j);\nend;\nimchi(j)=-2/pi*deltaomega*(a(j)+b(j))*omega(j)^(1-2*alpha);\n%Last element of the output: the principal part integration\n%is computed by excluding the last element of the input\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/8135-tools-for-data-analysis-in-optics-acoustics-signal-processing/kkimbook2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7846433519324344}} {"text": "function [A,Phi] = inverse_cht(Am,Nphi)\n%INVERSE_CHT inverse circular harmonics transform (ICHT)\n%\n% Usage: [A,Phi] = inverse_cht(Am,[Nphi])\n%\n% Input parameters:\n% Am - circular harmonics coefficients [N x (2*M+1)]\n% Nphi - number of equi-angular distributed angles, for which the ICHT\n% is computed, optional, default: 2*M+1\n%\n% Output parameters:\n% A - inverse circular harmonics transform [N x Nphi]\n% Phi - corresponding angle of the ICHT [1 x Nphi]\n%\n% See also: pwd_imp_circexp\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 1;\nnargmax = 2;\nnarginchk(nargmin,nargmax);\nisargmatrix(Am);\nif nargin == nargmin\n Nphi = size(Am, 2);\nelse\n isargpositivescalar(Nphi);\nend\n\n\n%% ===== Computation ==================================================\nM = (size(Am,2)-1)/2;\nN = size(Am,1);\n\n% Implementation of\n% ___\n% \\\n% A(phi) = /__ A e^(+i*m*n*2*pi/Nphi)\n% m=-M..M m\n\n% Spatial IFFT\nA = zeros(N, Nphi);\n% this handles cases where Nphi < M\nfor l=1:N\n A(l,:) = sum(buffer(Am(l,:),Nphi),2);\nend\nA = circshift(A,[0,-M]); % m = 0, ..., M, ..., -M, ..., -1\nA = ifft(A,[],2) * Nphi; % IFFT includes factor 1/Nphi\n\n% Axis corresponding to ICHT\nif nargout>1\n Phi = 0:2*pi / Nphi:2*pi*(1-1/Nphi);\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_general/inverse_cht.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7845651815280696}} {"text": "function value = lp_value ( n, o, x )\n\n%*****************************************************************************80\n%\n%% LP_VALUE evaluates a Legendre polynomial at several points X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 06 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, integer O, the degree of the polynomial.\n% 0 <= O.\n%\n% Input, real X(N,1), the evaluation points.\n%\n% Output, real VALUE(N,1), the value of the Legendre polynomial\n% of degree O at the points X.\n%\n x = x ( : );\n\n v = zeros ( n, o + 1 );\n\n v(1:n,1) = 1.0;\n\n if ( 1 <= o )\n \n v(1:n,2) = x(1:n,1);\n\n for j = 2 : o\n \n v(1:n,j+1) = ( ( 2 * j - 1 ) * x(1:n,1) .* v(1:n,j) ...\n - ( j - 1 ) * v(1:n,j-1) ) ...\n / ( j );\n \n end\n \n end\n\n value(1:n,1) = v(1:n,o+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/legendre_product_polynomial/lp_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7845651796923995}} {"text": "function [r,varargout]=circfit(x,y)\n%CIRCFIT Least squares fit of X-Y data to a circle.\n% R = CIRCFIT(X,Y) returns scalar radius R of a fitted circle. X and Y are 1-D\n% arrays of position data in a rectilinear coordinate system. X and Y must be\n% the same length and must contain at least three non-colinear points in order\n% for a valid solution to be found.\n%\n% [R,ERR] = CIRCFIT(X,Y) additionally returns the scalar root mean squared\n% error of the fitted circle radius and center relative to the position data.\n%\n% [R,XC,YC] = CIRCFIT(X,Y) additionally returns the scalar positions, XC and\n% YC, of center of the fitted circle.\n%\n% [R,XC,YC,ERR] = CIRCFIT(X,Y) returns both the center positions of the circle\n% as well as the root mean squared error.\n%\n% Examples:\n% % Fit of just five noisy points\n% x1=[1 0 -1 0 1]+0.05*randn(1,5); y1=[0 1 0 -1 0]+0.05*randn(1,5);\n% r1=circfit(x1,y1)\n%\n% % CIRCFIT can sometimes perfom poorly with less than 180-degree arc\n% t=0:0.1:pi; lt=length(t);\n% x2=cos(t)+0.04*randn(1,lt); y2=sin(t)+0.04*randn(1,lt);\n% r2_90deg=circfit(x2(1:floor(lt/2)),y2(1:floor(lt/2)))\n% r2_180deg=circfit(x2,y2)\n\n% Andrew D. Horchler, adh9 @ case . edu, Created 5-12-7\n% Revision: 1.3, 4-6-16\n\n\n% Check inputs\nif nargout > 4\n error('circfit:circfit:TooManyOutputs','Too many output arguments.');\nend\n\nif ~isvector(x) || ~isfloat(x) || ~isreal(x) || ~all(isfinite(x))\n error('circfit:circfit:NonFiniteRealVectorX',...\n 'X must be a finite real vector of floating point numbers.');\nend\nif ~isvector(y) || ~isfloat(y) || ~isreal(y) || ~all(isfinite(y))\n error('circfit:circfit:NonFiniteRealVectory',...\n 'Y must be a finite real vector of floating point numbers.');\nend\n\nlx=length(x);\nif lx ~= length(y)\n error('circfit:circfit:LengthMismatch',...\n 'The vectors X and Y must have the same length.');\nend\nif lx < 3\n error('circfit:circfit:Min3Points',...\n 'The vectors X and Y must contain at least three points.');\nend\nx=x(:);\ny=y(:);\n\n% Check collinearity, assume with sufficient points, some will be non-collinear\nif rank(diff([x([1:min(50,lx) 1]) y([1:min(50,lx) 1])])) == 1\n if lx <= 50 || rank(diff([x y;x(1) y(1)])) == 1\n error('circfit:circfit:Colinearity',...\n ['The points in vectors X and Y must not all be collinear, or '...\n 'nearly collinear, with each other.']);\n end\nend\n\nxx=x.*x;\nyy=y.*y;\nxy=x.*y;\nxxyy=xx+yy;\nsx=sum(x);\nsy=sum(y);\nsxx=sum(xx);\nsyy=sum(yy);\nsxy=sum(xy);\n\n% Solve linear system without inverting\n% a=[sx sy lx;sxy syy sy;sxx sxy sx]\\[sxx+syy;sum(xxyy.*y);sum(xxyy.*x)];\n[L,U]=lu([sx sy lx;sxy syy sy;sxx sxy sx]);\na=U\\(L\\[sxx+syy;sum(xxyy.*y);sum(xxyy.*x)]);\n\nxc=0.5*a(1); \t% X-position of center of fitted circle\nyc=0.5*a(2); \t% Y-position of center of fitted circle\nr=sqrt(xc^2+yc^2+a(3));\t% Radius of fitted circle\n\n% Set variable outputs\nif nargout > 2\n varargout{1}=xc;\n varargout{2}=yc;\nend\nif nargout == 2 || nargout == 4\n varargout{nargout-1}=sqrt(mean((sqrt((x-xc).^2+(y-yc).^2)-r).^2));\t% RMSE\nend\n", "meta": {"author": "andresmendes", "repo": "Vehicle-Dynamics-Lateral", "sha": "a1e9a07da58ef887164bf0046991f0db2ca3b647", "save_path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral", "path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral/Vehicle-Dynamics-Lateral-a1e9a07da58ef887164bf0046991f0db2ca3b647/Examples/SkidPadSimple/circfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7845566943672228}} {"text": "function [H,F] = make_bank_DFT(p,N)\n\n% make_bank_DFT Generate DFT Filter Bank with N Subbands\n%\n% Arguments:\n% p Prototype filter (impulse response)\n% N Number of subbands\n%\n% by Lee, Gan, and Kuo, 2008\n% Subband Adaptive Filtering: Theory and Implementation\n% Publisher: John Wiley and Sons, Ltd\n\n\np = p(:); % Make column\nflen = max(size(p)); % Length of prototype filter\nH = zeros(flen,N/2+1); % Assume N is an even number\nn = (0:flen-1)';\n\nk = 0; H(:,k+1) = p; % i = 0\nk = N/2; H(:,k+1) = p.*((-1).^n); % i = N/2+1 \n\nfor k = 1:(N/2-1)\n H(:,k+1) = p.*exp(j*2*pi/N*k*n); % Complex modulation\nend\n\nD = H(:,2:N/2);\nH = [H, conj(fliplr(D))]; % Complex-conjugate pair\n\n% Synthesis filters are the same as the analysis filters\n\nF = H;\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/make_bank_DFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.784556676509071}} {"text": "function f = bohach2_xy ( x, y )\n\n%*****************************************************************************80\n%\n%% BOHACH2_XY evaluates the Bohachevsky function #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, real X, Y, the argument of the function.\n%\n% Output, real F, the value of the function at X.\n%\n f = x * x ... \n + 2.0 * y * y ...\n - 0.3 * cos ( 3.0 * pi * x ) * cos ( 4.0 * pi * y ) ...\n + 0.3;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/levels/bohach2_xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.784539779739764}} {"text": "function z = nmi(x, y)\n% Compute normalized mutual information I(x,y)/sqrt(H(x)*H(y)) of two discrete variables x and y.\n% Input:\n% x, y: two integer vector of the same length \n% Ouput:\n% z: normalized mutual information z=I(x,y)/sqrt(H(x)*H(y))\n% Written by Mo Chen (sth4nth@gmail.com).\nassert(numel(x) == numel(y));\nn = numel(x);\nx = reshape(x,1,n);\ny = reshape(y,1,n);\n\nl = min(min(x),min(y));\nx = x-l+1;\ny = y-l+1;\nk = max(max(x),max(y));\n\nidx = 1:n;\nMx = sparse(idx,x,1,n,k,n);\nMy = sparse(idx,y,1,n,k,n);\nPxy = nonzeros(Mx'*My/n); %joint distribution of x and y\nHxy = -dot(Pxy,log2(Pxy));\n\n\n% hacking, to elimative the 0log0 issue\nPx = nonzeros(mean(Mx,1));\nPy = nonzeros(mean(My,1));\n\n% entropy of Py and Px\nHx = -dot(Px,log2(Px));\nHy = -dot(Py,log2(Py));\n\n% mutual information\nMI = Hx + Hy - Hxy;\n\n% normalized mutual information\nz = sqrt((MI/Hx)*(MI/Hy));\nz = max(0,z);\n\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter01/nmi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094438, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7845397735394735}} {"text": "function [V]=ellipseCoord(A,t)\n\n% function [V]=ellipseCoord(A,t)\n% ------------------------------------------------------------------------\n% Calculates ellipse coordiantes for the angles in t based on the vector A\n% which defines the centre coordinates, the radii and the angle\n% respectively. \n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% 2013/24/09\n%------------------------------------------------------------------------\n\n%%\nx0=A(1);\ny0=A(2);\nx=A(3).*cos(t);\ny=A(4).*sin(t);\nV=[x(:) y(:) zeros(size(x(:)))];\n[R,~]=euler2DCM([0 0 -A(5)]);\nV=(R*V')';\nV(:,1)=V(:,1)+x0;\nV(:,2)=V(:,2)+y0;\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/ellipseCoord.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7844959647889217}} {"text": "%% RATE OF CONVERGENCE OF CUBIC FINITE ELEMENT METHOD\n%\n% This example is to show the rate of convergence of cubic finite element\n% approximation of the Poisson equation on the regular polygons:\n%\n% $$- \\Delta u = f \\; \\hbox{in } Omega$$\n%\n% for the Dirichlet boundary condition.\n\nclear variables\n%% Set up problem\n% PDE and Boundary condition.\npde = simpledata; % f = 1, g_D = 0\n% FEM\noption.elemType = 'P3';\n\n%% Options\noption.L0 = 0;\noption.maxIt = 4;\noption.printlevel = 1;\noption.plotflag = 1;\n\n%% Case 1: Triangle\n[node,elem] = regpolygon(3,0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nshowmesh(node,elem);\nfemPoisson(mesh,pde,option);\n\n%% Case 2: Square\n[node,elem] = squaremesh([0,1,0,1],0.25); \nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nshowmesh(node,elem);\nfemPoisson(mesh,pde,option);\n\n%% Case 3: Pentagon\n[node,elem] = regpolygon(5,0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nshowmesh(node,elem);\nfemPoisson(mesh,pde,option);\n\n%% Case 4: Hexagon\n[node,elem] = regpolygon(6,0.5);\nshowmesh(node,elem);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nshowmesh(node,elem);\nfemPoisson(mesh,pde,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Poisson/PoissonP3femratepolygons.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.784495961495144}} {"text": "% X = NPAIRSK(N, K)\n%\n% Number of pair combinations for N objects to K pairs.\n%\n% For instance,\n%\n% npairsk(2,1) = 1\n% \n% because two elements can be divided into a pair in one way.\n%\n% npairsk(4,2) = 3\n%\n% because four elements (A,B,C,D) can be divided into two pairs in three\n% ways: [(A,B);(C,D)], [(A,C);(B,D)], [(A,D);(B,C)].\n%\n% npairsk(3,1) = 3\n%\n% because [(A,B)], [(A,C)], [(B,C)].\n\n% Last modified 2011-01-28\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction x = npairsk(n, k)\n\nx = factorial(n) ./ (factorial(2*k) .* factorial(n-2*k)) .* ngroupsk(k,2);", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/discrete/npairsk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7844810936806275}} {"text": "function [L,La,Lb] = points2plucker(A,B)\n\n% POINTS2PLUCKER Plucker line from two homogeneous points\n% L = POINTS2PLUCKER(A,B) is the Plucker line that passes over two points\n% A and B. The points are specified by their homogeneous coordinates\n% [x;y;z;w]. \n%\n% The result is a Plucker line expressed as a 6-vector. This vector can\n% be decomosed as L = [a;b], where the 3-vectors a and b admit the\n% following interpretation:\n%\n% * a - is a vector normal to the plane that contains the line and the\n% origin of coordinates.\n%\n% * b - is a vector director of the line, which lies on the plane\n% above.\n%\n% * a and b are orthogonal, i.e. dot(a,b)=0.\n%\n% * the distance from the line to the origin is given by\n% norm(a)/norm(b).\n%\n% [L,La,Lb] = ... returns the Jacobians wrt A and B.\n%\n% See also PLANES2PLUCKER.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nL = [cross(A(1:3),B(1:3));A(4)*B(1:3)-B(4)*A(1:3)];\n\nif nargout > 1\n\n [a1,a2,a3,a4] = split(A);\n [b1,b2,b3,b4] = split(B);\n\n La = [...\n [ 0, b3, -b2, 0]\n [ -b3, 0, b1, 0]\n [ b2, -b1, 0, 0]\n [ -b4, 0, 0, b1]\n [ 0, -b4, 0, b2]\n [ 0, 0, -b4, b3]];\n\n Lb = [...\n [ 0, -a3, a2, 0]\n [ a3, 0, -a1, 0]\n [ -a2, a1, 0, 0]\n [ a4, 0, 0, -a1]\n [ 0, a4, 0, -a2]\n [ 0, 0, a4, -a3]];\nend\n\n\nreturn\n\n%% jac\n\nsyms a1 a2 a3 a4 b1 b2 b3 b4 p1 p2 p3 p4 q1 q2 q3 q4 real\nA=[a1;a2;a3;a4];\nB=[b1;b2;b3;b4];\nL=points2plucker(A,B)\n\nLa = jacobian(L,A)\nLb = jacobian(L,B)\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Lines/points2plucker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7844693404525701}} {"text": "function x= cauchyinv(p, varargin)\n\n% USAGE: x= cauchyinv(p, a, b)\n% \n% Inverse of the Cauchy cumulative distribution function (cdf), x= a + b*tan(pi*(p-0.5)).\n% \n% ARGUMENTS:\n% p (0<=p<=1) might be of any dimension.\n% a (default value: 0.0) must be scalars or size(p).\n% b (b>0, default value: 1.0) must be scalars or size(p).\n% \n% EXAMPLE:\n% p= 0:0.01:1;\n% plot(cauchyinv(p), p);\n% \n% SEE ALSO: cauchycdf, cauchyfit, cauchypdf, cauchyrnd.\n% \n% Copyright (C) Peder Axensten \n% \n% HISTORY:\n% Version 1.0, 2006-07-10.\n% Version 1.1, 2006-07-26.\n% - Added cauchyfit to the cauchy package. \n% Version 1.2, 2006-07-31:\n% - cauchyinv(0, ...) returned a large negative number but should be -Inf. \n% - Size comparison in argument check didn't work. \n% - Various other improvements to check list. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\t% Default values\n\ta=\t0.0;\n\tb=\t1.0;\n\t\n\t\n\t% Check the arguments\n\tif(nargin >= 2)\n\t\ta=\tvarargin{1};\n\t\tif(nargin == 3)\n\t\t\tb=\t\t\tvarargin{2};\n\t\t\tb(b <= 0)=\tNaN;\t% Make NaN of out of range values.\n\t\tend\n\tend\n\tif((nargin < 1) || (nargin > 3))\n\t\terror('At least one argument, at most three!');\n\tend\n\t\n\tp(p < 0 | 1 < p)=\tNaN;\n\t\n\t\n\t% Calculate\n\tx=\t\t\ta + b.*tan(pi*(p-0.5));\n\t\n\t% Extreme values. \n\tif(numel(p) == 1), \tp= repmat(p, size(x));\t\tend\n\tx(p == 0)=\t-Inf;\n\tx(p == 1)=\tInf;\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/11749-cauchy/cauchyinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7844693388432326}} {"text": "function P = agm_pi ( d )\n\n%*****************************************************************************80\n%\n%% AGM_PI Arithmetic-geometric mean for pi.\n%\n% Discussion:\n%\n% The Brent-Salamin algorithm is used to compute PI to D decimal digits.\n%\n% Licensing:\n%\n% Copyright (c) 2011, The MathWorks, Inc.\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% * Neither the name of the The MathWorks, Inc. nor the names \n% of its contributors may be used to endorse or promote products derived \n% from this software without specific prior written permission.\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% Modified:\n%\n% 27 February 2012\n%\n% Author:\n%\n% Cleve Moler\n%\n% Reference:\n%\n% Cleve Moler,\n% Cleve's Corner, \"Computing Pi\",\n% http://www.mathworks.com/company/newsletters/news_notes/2011/ \n%\n% Parameters:\n%\n% Input, integer D, the number of decimal digits desired.\n%\n% Output, symbolic P, the value of pi to D digits.\n% \n digits ( d )\n\n a = vpa(1,d);\n b = 1/sqrt(vpa(2,d));\n s = 1/vpa(4,d);\n p = 1;\n n = ceil(log2(d));\n\n for k = 1:n\n c = (a+b)/2;\n b = sqrt(a*b);\n s = s - p*(c-a)^2;\n p = 2*p;\n a = c;\n end\n\n P = a^2 / 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/vpa/agm_pi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7844693355032963}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters. \n% You should set p to a vector of 0's and 1's\n%\n\ntemp = sigmoid(X * theta);\np = (temp >= 0.5)\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/matlab吴恩达机器学习/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7843461881383655}} {"text": "function fx = p03_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P03_FUN evaluates the integrand 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% Reference:\n%\n% Gwynne Evans,\n% Practical Numerical Integration,\n% Wiley, 1993,\n% ISBN: 047193898X,\n% LC: QA299.3E93.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(2,N), the evaluation points.\n%\n% Output, real FX(N,1), the integrand values.\n%\n fx(1:n,1) = 1.0 ./ sqrt ( 2.0 - x(1,1:n) - x(2,1:n) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int_2d/p03_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7843461712462703}} {"text": "%% Example 2.7: Hyperbolic Conservation Laws in 2D\n%\n% In this example we will solve the 2D scalar conservation law \n%\n% $$ u_t + f(u)_x + g(u)_y = 0, \\qquad u(x,y,0) = u_0(x,y) $$\n%\n% by dimensional splitting. To this end, we use two substeps,\n%\n% $$ S_x(t): \\quad v_t + f(v)_x = 0, \\qquad v(x,0)=v_0(x)$$\n%\n% $$ S_y(t): \\quad w_t + g(w)_y = 0, \\qquad w(y,0)=w_0(y)$$\n%\n% and construct the approximate solution from the formula\n%\n% $$u(x,t)\\approx [S_y(\\Delta t)\\circ S_x(\\Delta t) ]^n u_0(x)$$\n%\n% The 1-D hyperbolic steps will be solved using the Lax-Friedrichs scheme\n\n\n%% Initial setup\nN = 256;\nh = 2*pi/N;\nx =-pi+(0:N)*h; x=0.5*(x(1:end-1)+x(2:end)); \ny = x;\n[X,Y] = ndgrid(x,y);\nu0 = exp( -4*sin(X/2).^2 - 4*sin(Y/2).^2 );\nh=path; path(h,'../Example2_5');\n\n%% Flux functions\n% As a concrete example, we choose the Buckley-Leverett flux in the\n% x-direction and a convex flux in the y-direction\n%\n% $$f(u) = u^2 / (u^2 + (1-u)^2), \\qquad g(u) = u(1-u)$$\n%\n% This system can be seen as a simplified model of two-phase flow in a\n% periodic porous medium under the influence of convective and gravity\n% forces (convective in the x-direction and gravity in the y-direction).\n% The two fluxes are shown in the plot below\nu = linspace(0,1,101);\nplot(u, fflux(u), u, gflux(u)), axis tight, legend('f(u)','g(u)',2)\n\n%% Evolution of the solution\nT = 1.5;\nnsplit = 50;\nu = dimsplit('fflux','gflux', u0, x, y, T, nsplit);\nI = 1:10:nsplit+1; \nt = linspace(0,T,nsplit+1);\nc = linspace(0,1,11);\nfor i=1:6\n subplot(2,3,i),\n contourf(x,y,u(:,:,I(i))',c), caxis([0 1]) %, colorbar('horiz')\n %surf(x,y,u(:,:,I(i))'), shading interp, view(3)\n title(['Time: t=' num2str(t(I(i)))]);\nend\n%%\n% To understand the evolution of the initial blob, we discuss the movement\n% in the two spatial directions separately. In the x-direction, the\n% nonconvex Buckley-Leverett flux will turn the right-hand side of the\n% symmetric blob into a leading shock, followed by a rarefaction. Likewise,\n% the left-hand side of the blob turns into a shock followed by a\n% rarefaction wave. In the y-direction, the convex flux gives a shock along\n% the upper part of the blob and a rarefaction wave along the lower part.\n\n%% Compare different time steps\n% Having established the dynamics of the problem, we can investigate the\n% performance of our numerical method for different choices of the\n% splitting step. To this end, we increase time interval to [0,8].\nT = 8;\nc = linspace(0,.25,11);\nfor n=1:4,\n\tnsplit=4*2.^(n-1);\n\tu=dimsplit('fflux','gflux',u0,x,y,T,nsplit);\n\tsubplot(2,2,n)\n\tcontourf(x,y,u(:,:,nsplit+1)',c), caxis([0 .25]);\n\txlabel('x'), ylabel('y','Rotation',0), colorbar\n\ttitle([num2str(nsplit) ' steps']);\nend;\npath(h);\n%%\n% It is quite amazing how accurate one can capture the dynamics of this\n% flow with only four splitting steps. Increasing the number of steps,\n% improves small-scale features of the solution, but does not change the\n% qualitative behavior of the approximate solution.", "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/Example2_7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.7843461659042752}} {"text": "function value = composite_abscissa ( order, i )\n\n%*****************************************************************************80\n%\n%% COMPOSITE_ABSCISSA returns the I-th abscissa of a composite rule.\n%\n% Discussion:\n%\n% Our convention is that the abscissas are numbered from left to\n% right, that the interval is [-1,1], and the the abscissas are\n% evenly spaced, and that, except for the order 1 rule, the\n% endpoints are included.\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, integer ORDER, the order of the rule.\n%\n% Input, integer I, the index of the desired abscissa. \n% 1 <= I <= ORDER.\n%\n% Output, real VALUE, the value of the I-th abscissa in the \n% rule of order ORDER.\n%\n a = -1.0;\n b = +1.0;\n\n if ( order < 1 )\n value = - Inf;\n elseif ( i < 1 | order < i )\n value = - Inf;\n elseif ( order == 1 )\n value = 0.5 * ( a + b );\n else\n value = ( ( order - i ) * a ...\n + ( i - 1 ) * b ) ...\n / ( order - 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/sparse_grid_composite/composite_abscissa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.7843461650381647}} {"text": "function Z = projectData(X, U, K)\n%PROJECTDATA Computes the reduced data representation when projecting only\n%on to the top k eigenvectors\n% Z = projectData(X, U, K) computes the projection of\n% the normalized inputs X into the reduced dimensional space spanned by\n% the first K columns of U. It returns the projected examples in Z.\n%\n\n% You need to return the following variables correctly.\nZ = zeros(size(X, 1), K);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the projection of the data using only the top K\n% eigenvectors in U (first K columns).\n% For the i-th example X(i,:), the projection on to the k-th\n% eigenvector is given as follows:\n% x = X(i, :)';\n% projection_k = x' * U(:, k);\n%\n\nZ = X * U(:, 1:K);\n\n\n% =============================================================\n\nend\n", "meta": {"author": "fewtime", "repo": "ML", "sha": "fd9679e9d6648d01e36047e97434f38c8d2d6168", "save_path": "github-repos/MATLAB/fewtime-ML", "path": "github-repos/MATLAB/fewtime-ML/ML-fd9679e9d6648d01e36047e97434f38c8d2d6168/coursera-machine-learning/machine-learning-ex7/ex7/projectData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8856314647623015, "lm_q1q2_score": 0.7843430993971973}} {"text": "function node_xy = grid_nodes_01 ( x_num, y_num )\n\n%*****************************************************************************80\n%\n%% GRID_NODES_01 returns an equally spaced rectangular grid of nodes in the unit square.\n%\n% Example:\n%\n% X_NUM = 5\n% Y_NUM = 3\n%\n% NODE_XY = \n% ( 0, 0.25, 0.5, 0.75, 1, 0, 0.25, 0.5, 0.75, 1, 0, 0.25, 0.5, 0.75, 1;\n% 0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1.0, 1.0, 1.0, 1 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X_NUM, Y_NUM, the number of nodes in the X and Y directions.\n%\n% Output, real NODE_XY(2,X_NUM*Y_NUM), the coordinates of the nodes.\n%\n node_num = x_num * y_num;\n\n node_xy(1:2,1:node_num) = 0.0;\n\n if ( x_num == 1 )\n node_xy(1,1:node_num) = 0.5;\n else\n for i = 1 : x_num\n node_xy(1,i:x_num:i+(y_num-1)*x_num) = ( i - 1 ) / ( x_num - 1 );\n end\n end\n\n if ( y_num == 1 )\n node_xy(2,1:node_num) = 0.5;\n else\n for j = 1 : y_num\n node_xy(2,1+(j-1)*x_num:j*x_num) = ( j - 1 ) / ( y_num - 1 );\n end\n end\n\n return\nend\n", "meta": {"author": "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_nodes_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7843430873669308}} {"text": "function gt = gtom(adj,numSteps)\n%GTOM Generalized topological overlap measure\n%\n% gt = gtom(adj,numSteps);\n%\n% The m-th step generalized topological overlap measure (GTOM) quantifies\n% the extent to which a pair of nodes have similar m-th step neighbors.\n% Mth-step neighbors are nodes that are reachable by a path of at most\n% length m.\n%\n% This function computes the the M x M generalized topological overlap\n% measure (GTOM) matrix for number of steps, numSteps. \n%\n% Inputs: adj, adjacency matrix (binary,undirected)\n% numSteps, number of steps\n%\n% Outputs: gt, GTOM matrix\n%\n% NOTE: When numSteps is equal to 1, GTOM is identical to the topological\n% overlap measure (TOM) from reference [2]. In that case the 'gt' matrix\n% records, for each pair of nodes, the fraction of neighbors the two\n% nodes share in common, where \"neighbors\" are one step removed. As\n% 'numSteps' is increased, neighbors that are furter out are considered.\n% Elements of 'gt' are bounded between 0 and 1. The 'gt' matrix can be\n% converted from a similarity to a distance matrix by taking 1-gt.\n%\n% References: [1] Yip & Horvath (2007) BMC Bioinformatics 2007, 8:22\n% [2] Ravasz et al (2002) Science 297 (5586), 1551.\n%\n% J Goni, University of Navarra and Indiana University, 2009/2011\n\n%#ok<*ASGLU>\n\n%initial state for bm matrix;\nbm = adj;\nbmAux = bm;\nnumNodes = size(adj,1);\n\nif (numSteps > numNodes)\n disp('warning, reached maximum value for numSteps. numSteps reduced to adj-size')\n numSteps = numNodes;\nend\n\nif (numSteps == 0)\n %GTOM0\n gt = adj;\nelse\n \n for steps = 2:numSteps\n for i = 1:numNodes\n \n %neighbours of node i\n [neighRow,neighColumn] = find(bm(i,:)==1); \n \n %neighbours of neighbours of node i\n [neighNeighRow,neighNeighColumn] = find(bm(neighColumn,:)==1);\n newNeigh = setdiff(unique(neighNeighColumn),i);\n \n %neighbours of neighbours of node i become considered node i neighbours\n bmAux(i,newNeigh) = 1;\n \n %keep symmetry of matrix\n bmAux(newNeigh,i) = 1;\n end\n %bm is updated with new step all at once\n bm = bmAux;\n \n end\n \n clear bmAux newNeigh;\n \n %numerators of GTOM formula\n numeratorMatrix = bm*bm + adj + speye(numNodes,numNodes);\n \n %vector containing degree of each node\n bmSum=sum(bm); \n clear bm;\n \n denominatorMatrix = -adj + min(repmat(bmSum,numNodes,1),repmat(bmSum',1,numNodes)) + 1;\n gt = numeratorMatrix ./ denominatorMatrix;\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/gtom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.7843236917583293}} {"text": "% Figure 6.60 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n% \n\nclear all\nclose all\n\nnum=10;\nden=conv([1 0],[1/2.5 1]);\nden=conv(den,[1/6 1]);\nw=logspace(-1,2,100);\n[mag,phas]=bode(num,den,w);\n[OLgm,OLpm,OLwcg,OLwcp]=margin(mag,phas,w)\n%Lead compensator\nnuml=10*[1 2];\ndenl=[1 20];\nnum1=conv(num,numl);\nden1=conv(den,denl);\n[magcl,phascl]=bode(num1,den1,w);\n[D1gm,D1pm,D1wcg,D1wcp]=margin(magcl,phascl,w)\nnumll=10*conv(numl,[1 4]);\ndenll=conv(denl,[1 40]);\nnum2=conv(num,numll);\nden2=conv(den,denll);\n[magcll,phascll]=bode(num2,den2,w);\n[D2gm,D2pm,D2wcg,D2wcp]=margin(magcll,phascll,w)\nsubplot(2,1,1)\nloglog(w,mag,'-',w,magcl,'--',w,magcll,'-.',w,ones(100,1),'-');\naxis([.1 100 .01 10])\ngrid;\nylabel('Magnitude');\ntitle('Fig. 6.60 Bode plot for Example 6.16. (a) magnitude');\nsubplot(2,1,2)\nsemilogx(w,phas,'-',w,phascl,'--',w,phascll,'-.',w,-180*ones(100,1),'-');\naxis([.1 100 -250 -50])\ngrid;\nxlabel('\\omega (rad/sec)');\nylabel('phase (deg)');\ntitle('Fig. 6.60 (b) phase.');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig6_60.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7843019916038151}} {"text": "function Q = randrot(n, N)\n% Generates uniformly random rotation matrices.\n%\n% function Q = randrot(n, N)\n%\n% Q is an n-by-n-by-N array such that each slice Q(:, :, i) is a random\n% orthogonal matrix of size n of determinant +1 (i.e., a matrix in SO(n)),\n% sampled from the Haar measure (uniform distribution).\n%\n% By default, N = 1.\n%\n% Complexity: N times O(n^3).\n% Theory in Diaconis and Shahshahani 1987 for the uniformity on O(n);\n% With details in Mezzadri 2007,\n% \"How to generate random matrices from the classical compact groups.\"\n%\n% To ensure matrices in SO(n), we permute the two first columns when\n% the determinant is -1.\n%\n% See also: randskew qr_unique randunitary\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sept. 25, 2012.\n% Contributors: \n% Change log:\n% June 18, 2019 (NB)\n% Now generating all initial random matrices in one shot (which\n% should be more efficient) and calling qr_unique.\n\n\n if nargin < 2\n N = 1;\n end\n \n if n == 1\n Q = ones(1, 1, N);\n return;\n end\n \n % Generated as such, Q is uniformly distributed over O(n): the group\n % of orthogonal matrices; see Mezzadri 2007.\n Q = qr_unique(randn(n, n, N));\n \n for k = 1 : N\n \n % If a slice of Q is in O(n) but not in SO(n), we permute its two\n % first columns to negate its determinant. This ensures the new\n % slice is in SO(n), uniformly distributed.\n if det(Q(:, :, k)) < 0\n Q(:, [1 2], k) = Q(:, [2 1], k);\n end\n \n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/rotations/randrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7843019864818456}} {"text": "\n% Copyright (C) 1993-2014, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n%%begin\n\n% Frequently we want to define a smooth sequence of positions (or poses) from\n% one point to another. First consider the 1-dimensional case.\n%\n% We define the start and end position\n\np0 = -1;\np1 = 2;\n\n% and a smooth path from p0 to p1 in 50 time steps is given by\n\np = tpoly(p0, p1, 50);\nabout p\n% which we see has 50 rows. We can plot this \n\nplot(p)\n\n% and see that it does indeed move smoothly from p0 to p1 and that the initial\n% and final derivative (and second derivative) is zero.\n\n% We can also get the velocity and acceleration\n\n[p,pd,pdd] = tpoly(p0, p1, 50);\nsubplot(3,1,1); plot(p); xlabel('Time'); ylabel('p');\nsubplot(3,1,2); plot(pd); xlabel('Time'); ylabel('pd');\nsubplot(3,1,3); plot(pdd); xlabel('Time'); ylabel('pdd');\n\n% This path is a 5th order polynomial and it suffers from the disadvantage that\n% the velocity is mostly below the maximum possible value. An alternative is\n\n[p,pd,pdd] = lspb(p0, p1, 50);\nsubplot(3,1,1); plot(p); xlabel('Time'); ylabel('p');\nsubplot(3,1,2); plot(pd); xlabel('Time'); ylabel('pd');\nsubplot(3,1,3); plot(pdd); xlabel('Time'); ylabel('pdd');\n% which we see has a trapezoidal velocity profile.\n\n% Frequently the start and end values are vectors, not scalars, perhaps a 3D\n% position or Euler angles. In this case we apply the scalar trajectory function\n% to a vector with\n\np = mtraj(@tpoly, [0 1 2], [2 1 0], 50);\nabout p\n% and p again has one row per time step, and one column per vector dimension\n\nclf; plot(p)\n\n%---\n% Finally, we may wish to interpolate poses. We will define a start and end pose\n\nT0 = transl(0.4, 0.2, 0) * trotx(pi);\nT1 = transl(-0.4, -0.2, 0.3) * troty(pi/2) * trotz(-pi/2);\n\n% and a smooth sequence between them in 50 steps is\n\nT = ctraj(T0, T1, 50);\nabout T\n% which is a 4x4x50 matrix. The first pose is\n\nT(:,:,1)\n\n% and the 10th pose is\n\nT(:,:,10)\n\n% We can plot the motion of this coordinate frame by\n\nclf; tranimate(T)\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/demos/traj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7842655257862441}} {"text": "function [ x, fx ] = local_min ( a, b, epsi, t, f, x )\n\n%*****************************************************************************80\n%\n%% LOCAL_MIN seeks a local minimum of a function F(X) in an interval [A,B].\n%\n% Discussion:\n%\n% The method used is a combination of golden section search and\n% successive parabolic interpolation. Convergence is never much slower\n% than that for a Fibonacci search. If F has a continuous second\n% derivative which is positive at the minimum (which is not at A or\n% B), then convergence is superlinear, and usually of the order of\n% about 1.324....\n%\n% The values EPSI and T define a tolerance TOL = EPSI * abs ( X ) + T.\n% F is never evaluated at two points closer than TOL.\n%\n% If F is a unimodal function and the computed values of F are always\n% unimodal when separated by at least SQEPS * abs ( X ) + (T/3), then\n% LOCAL_MIN approximates the abscissa of the global minimum of F on the\n% interval [A,B] with an error less than 3*SQEPS*abs(LOCAL_MIN)+T.\n%\n% If F is not unimodal, then LOCAL_MIN may approximate a local, but\n% perhaps non-global, minimum to the same accuracy.\n%\n% Thanks to Jonathan Eggleston for pointing out a correction to the \n% golden section step, 01 July 2013.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 April 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Richard Brent.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Richard Brent,\n% Algorithms for Minimization Without Derivatives,\n% Dover, 2002,\n% ISBN: 0-486-41998-3,\n% LC: QA402.5.B74.\n%\n% Parameters:\n%\n% Input, real A, B, the endpoints of the interval.\n%\n% Input, real EPSI, a positive relative error tolerance.\n% EPSI should be no smaller than twice the relative machine precision,\n% and preferably not much less than the square root of the relative\n% machine precision.\n%\n% Input, real T, a positive absolute error tolerance.\n%\n% Input, function value = F ( x ), the name of a user-supplied\n% function whose local minimum is being sought.\n%\n% Output, real X, the estimated value of an abscissa\n% for which F attains a local minimum value in [A,B].\n%\n% Output, real FX, the value F(X).\n%\n\n%\n% C is the square of the inverse of the golden ratio.\n%\n c = 0.5 * ( 3.0 - sqrt ( 5.0 ) );\n\n sa = a;\n sb = b;\n x = sa + c * ( b - a );\n w = x;\n v = w;\n e = 0.0;\n fx = f ( x );\n fw = fx;\n fv = fw;\n\n while ( 1 )\n\n m = 0.5 * ( sa + sb );\n tol = epsi * abs ( x ) + t;\n t2 = 2.0 * tol;\n%\n% Check the stopping criterion.\n%\n if ( abs ( x - m ) <= t2 - 0.5 * ( sb - sa ) )\n break\n end\n%\n% Fit a parabola.\n%\n r = 0.0;\n q = r;\n p = q;\n\n if ( tol < abs ( e ) )\n\n r = ( x - w ) * ( fx - fv );\n q = ( x - v ) * ( fx - fw );\n p = ( x - v ) * q - ( x - w ) * r;\n q = 2.0 * ( q - r );\n\n if ( 0.0 < q )\n p = - p;\n end\n\n q = abs ( q );\n\n r = e;\n e = d;\n\n end\n\n if ( abs ( p ) < abs ( 0.5 * q * r ) & ...\n q * ( sa - x ) < p & ...\n p < q * ( sb - x ) )\n%\n% Take the parabolic interpolation step.\n%\n d = p / q;\n u = x + d;\n%\n% F must not be evaluated too close to A or B.\n%\n if ( ( u - sa ) < t2 | ( sb - u ) < t2 )\n\n if ( x < m )\n d = tol;\n else\n d = - tol;\n end\n\n end\n%\n% A golden-section step.\n%\n else\n\n if ( x < m )\n e = sb - x;\n else\n e = sa - x;\n end\n\n d = c * e;\n\n end\n%\n% F must not be evaluated too close to X.\n%\n if ( tol <= abs ( d ) )\n u = x + d;\n elseif ( 0.0 < d )\n u = x + tol;\n else\n u = x - tol;\n end\n\n fu = f ( u );\n%\n% Update A, B, V, W, and X.\n%\n if ( fu <= fx )\n\n if ( u < x )\n sb = x;\n else\n sa = x;\n end\n\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n\n else\n\n if ( u < x )\n sa = u;\n else\n sb = u;\n end\n\n if ( fu <= fw | w == x )\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n elseif ( fu <= fv | v == x | v == w )\n v = u;\n fv = fu;\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/brent/local_min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8824278556326344, "lm_q1q2_score": 0.7842655085160958}} {"text": "function S = AccSign(p)\n%ACCSIGN Computes sign(sum(p))\n%\n% S = AccSign(p)\n%\n%On return, S is the sign of sum(p), also in the presence\n% of underflow. Input vector p may be single or double precision.\n%\n%Implements Algorithm 8.2 from\n% S.M. Rump, T. Ogita, S. Oishi: Accurate Floating-point Summation II: \n% Sign, K-fold Faithful and Rounding to Nearest, Siam J. Sci. Comput., \n% 31(2):1269-1302, 2008. \n%Requires (4m+2)n flops for m executions of repeat-until loop in Transform.\n%\n%Reference implementation! Slow due to interpretation!\n%\n\n% written 03/03/07 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest, complex input\n%\n\n if ~isreal(p)\n error('AccSign for real input only')\n end\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n if isa(p,'double')\n nmax = 2^52; % nmax = 450,359,962,737,0496\n else\n nmax = 2^23; % nmax = 8,388,608\n end\n if length(p)>nmax\n error(['maximum length of input vector for AccSign ' int2str(nmax) '.'])\n end\n\n kPhi = 1;\n [tau1,tau2,p] = Transform(p,0,kPhi);\n S = sign(tau1);\n\n if rndold\n setround(rndold)\n end\n ", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/accsumdot/AccSign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7842510223445548}} {"text": "function [yi, ypi, yppi] = cubiconv(x, y, xi)\n\n% CUBICONV Cubic convolution interpolation\n% CUBICONV(X,Y,XI) interpolates to find YI, the value of\n% the underlying function Y at the points in the uniform array\n% XI, using cubic convolution interpolation. X and Y must be\n% vectors of length N.\n%\n% [YI,YPI,YPPI] = CUBICONV() also returns the interpolated\n% quartic derivative and cubic second derivative of the underlying\n% function Y at points XI.\n\n% Joe Henning - Fall 2011\n\n% Cubic Convolution Interpolation for Digital Image Processing\n% Robert G. Keys\n% IEEE Transactions on Acoustics, Speech, and Signal Processing, Vol. ASSP-29, No. 6\n% December, 1981\n\nn = length(x);\n%h = (x(n) - x(1))/n;\n\nfor i = 1:length(xi)\n if (xi(i) < x(1) || xi(i) > x(n))\n fprintf('??? Bad x input to cubiconv ==> x(1) <= x <= x(n)\\n');\n yi(i) = NaN;\n continue;\n end\n\n % Find the right place in the table by means of a bisection.\n klo = 1;\n khi = n;\n while (khi-klo > 1)\n k = fix((khi+klo)/2.0);\n if (x(k) > xi(i))\n khi = k;\n else\n klo = k;\n end\n end\n \n h = x(khi) - x(klo);\n if (h == 0.0)\n fprintf('??? Bad x input to cubiconv ==> x values must be distinct\\n');\n yi(i) = NaN;\n ypi(i) = NaN;\n yppi(i) = NaN;\n continue;\n end\n\n km1 = klo - 1;\n kp1 = khi + 1;\n if (km1 < 1)\n a = 3*y(klo) - 3*y(khi) + y(khi+1);\n else\n a = y(km1);\n end\n if (kp1 > n)\n d = 3*y(khi) - 3*y(klo) + y(klo-1);\n else\n d = y(kp1);\n end\n b = y(klo);\n c = y(khi);\n\n % Evaluate cubic polynomial\n t = (xi(i) - x(klo))/h;\n t2 = t*t;\n t3 = t2*t;\n h2 = h*h;\n c00 = (-t3 + 2*t2 - t)/2.0;\n c10 = (3*t3 - 5*t2 + 2)/2.0;\n c20 = (-3*t3 + 4*t2 + t)/2.0;\n c30 = (t3 - t2)/2.0;\n\n yi(i) = a*c00 + b*c10 + c*c20 + d*c30;\n\n % Differentiate to find the second-order interpolant\n c00 = (-3*t2 + 4*t - 1)/2.0;\n c10 = (9*t2 - 10*t)/2.0;\n c20 = (-9*t2 + 8*t + 1)/2.0;\n c30 = (3*t2 - 2*t)/2.0;\n\n ypi(i) = a*c00/h + b*c10/h + c*c20/h + d*c30/h;\n\n % Differentiate to find the first-order interpolant\n c00 = (-6*t + 4)/2.0;\n c10 = (18*t - 10)/2.0;\n c20 = (-18*t + 8)/2.0;\n c30 = (6*t - 2)/2.0;\n\n yppi(i) = a*c00/h2 + b*c10/h2 + c*c20/h2 + d*c30/h2;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36800-interpolation-utilities/cubiconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7842510197746323}} {"text": "function [cart] = Polar2Cart(polar)\n %% Cnverts polar coordinats [alpha;r] to cartesian [x;y]\n\n alpha = polar(1,:);\n r = polar(2,:);\n x = zeros(1,size(polar,2));\n y = zeros(1,size(polar,2));\n\n for i = 1:size(polar,2)\n x(i) = r(i)*cos(alpha(i));\n y(i) = r(i)*sin(alpha(i));\n end\n\n cart = [x;y];\nend\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/Polar2Cart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7842510083889495}} {"text": "%% 1D Heat Transfer FDM\n% by Manuel Diaz\nclc; clear; close all;\n\n%% Parameters\nalpha = 0.25; % difusion speed\niter = 400; % iteration time steps\n\n%% Domain Grid\nL = 30; % Length\nn = 30; % Nodes\ndx = L/n; dt = 0.5;\nx = 1:dx:L;\nt = zeros(1,n); % temperature of the nodes in our Domain\n\n%% Wall Temperatura at x = 0\ntwall = 1;\n\n%% Initial Condition\nt_0 = zeros(1,n); % @time = 0\nt_0(1) = twall; %Dirichlet BC\nt_0(n) = t_0(n-1); %Neumann BC\n\n%% Main Loop\nt_next = zeros(1,n); %Next time step\nt = t_0;\t\t\t %Load I.C.\nfor k = 1:iter;\n for i = 2:n-1;\n t_next(i) = t(i) + (dt/dx^2)*alpha*(t(i+1)-2*t(i)+t(i-1));\n end\n % BC\n t_next(1) = twall;\n\tt_next(n) = t_next(n-1); \n\t% Update info\n\tt = t_next;\nend\n\n%% Make pretty figures\nplot(x,t,'.'); xlabel 'x cell'; ylabel 'Temperature'; title '1D Heat Equation using FDM';\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/heat_eq_fdm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7841800663992304}} {"text": "% Compute the center frequency of the mel filterbank\n% Inputs:\n% start_freq: the lowerest linear frequency included in the calculation\n% linear_samp: sampling frequency\n% N_mel: number of mel banks used\n% Output: \n% mel_center_freq: the center linear frequency of each mel bank\n% bin_upper_edge: \n\nfunction [mel_center_freq, bin_upper_edge] = mel_center_FE(start_freq, linear_samp, N_mel)\n\n% get the mel version of start frequency and linear sampling rate\nstart_mel = linear2mel(start_freq);\nsamp_mel = linear2mel(linear_samp/2);\n\nfor i=1:N_mel\n tmp_mel = (i-1)*(samp_mel-start_mel) / (N_mel+1);\n mel_center_freq(i) = mel2linear(tmp_mel+start_mel);\n tmp_mel = (i+1)*(samp_mel-start_mel) / (N_mel+1);\n bin_upper_edge(i) = mel2linear(tmp_mel+start_mel);\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/feature/mel_center_FE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065792, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7840567698532718}} {"text": "function [alpha,beta]=moments23TermRecur(mu)\n%%MOMENTS23TERMRECUR Given 2*N+1 moments of a scalar weighting function\n% from 0 to 2*N, the kth moment is\n% mu(k+1)=integral_a^b w(x)*x^k dx where w(x) is a weighting\n% function and a and b need not be finite, obtain the three term\n% recusion for orthogonal polynomials that share the same moments.\n% The three term recursion coefficients cna be used with the\n% orthoPolyZerosFromRecur to obtain quadrature points and weights\n% when using the same weighting function. The three-term recursion\n% has the form:\n% x*p_{k-1}(x)=beta_{k-1}*p_{k-2}(x)+alpha_k*p_{k-1}+beta_kp_k(x)\n% for k=1,...,N starting with p_{-1}(x)=0. This can be useful for\n% obtaining cubature points for integration over continuous\n% probability distributions with easy-to-express noncentral\n% moments (e.g. from the moment generting function of the\n% distribution.\n%\n%INPUTS: mu A length (2*N+1) array holding the moments from orders 0 to 2*N\n% of the desired weighting function (which could be, but needn't\n% be, a continuous probability distribution).\n%\n%OUTPUTS: alpha A length N vector of coefficients.\n% beta A length N-1 vector of coefficients.S\n%\n%The algorithm is taken from Section 4 of [1]. To use these with the\n%orthoPolyZerosFromRecur function, one must pass alpha, beta, and mu(1).\n%See the example below.\n%\n%EXAMPLE:\n%In this example, we get the values for a three-term recursion of the\n%standard normal distribution. We then plus the values into\n%orthoPolyZerosFromRecur and get cubature points for integration voer the\n%distribution. We then show that these points are identical tot he ones\n%obtained from the quadraturePoints1D function (differences are within\n%finite precision limits).\n% meanVal=0;\n% variance=1;\n% N=5;\n% mu=zeros(2*N+1,1);\n% for k=0:2*N\n% mu(k+1)=GaussianD.momentGenFun(meanVal,variance,k);\n% end\n% [alpha,beta]=moments23TermRecur(mu);\n% [xi,w]=orthoPolyZerosFromRecur(N,alpha,beta,[],mu(1));\n% [xiGauss,wGauss]=quadraturePoints1D(N,0);\n% max(abs((xi-xiGauss)))\n% max(abs(w-wGauss))\n%\n%REFERENCES:\n%[1] G. H. Golub and J. H. Welsh, \"Calculation of Gauss quadrature rules,\"\n% Mathematics of Computation, vol. 23, pp. 221-230, 1969.\n%\n%January 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=(length(mu)-1)/2;\n\nif(fix(N)~=N)\n error('This function requires an odd number of moments.')\nend\n\n%The Gram Matrix in Section 4.\nM=zeros(N+1,N+1);\nfor i1=1:(N+1)\n for i2=1:(N+1)\n M(i1,i2)=mu(i1+i2-1);\n end\nend\n\n%Using cholSemiDef instead of chol, it is more robust to semidefinite\n%matrices.\nR=cholSemiDef(M,'upper');\n\n%Equation 4.3 in [1] for both alpha and beta.\nalpha=zeros(N,1);\nalpha(1)=R(1,2)/R(1,1);\nfor i=2:N\n alpha(i)=R(i,i+1)/R(i,i)-R(i-1,i)/R(i-1,i-1);\nend\n\nbeta=zeros(N-1,1);\nfor i=1:(N-1)\n beta(i)=R(i+1,i+1)/R(i,i);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/moments23TermRecur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7840534624063004}} {"text": "function [dist, pos] = distancePointLine(point, line)\n%DISTANCEPOINTLINE Minimum distance between a point and a line\n%\n% D = distancePointLine(POINT, LINE)\n% Return the euclidean distance between line LINE and point POINT. \n%\n% LINE has the form: [x0 y0 dx dy], and POINT is [x y].\n%\n% If LINE is N-by-4 array, result is N-by-1 array computes for each line.\n%\n% If POINT is N-by-2, then result is computed for each point.\n%\n% If both POINT and LINE are array, result is computed for each couple of\n% point and line, and is returned in a NP-by-NL array, where NP is the\n% number of points, and NL is the number of lines.\n%\n%\n% See also:\n% lines2d, points2d, distancePoints, distancePointEdge\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2005-06-24\n% Copyright 2016 INRA - BIA-BIBS.\n\n% HISTORY:\n% 2012-10-24 rewrite using bsxfun\n\n% direction vector of each line (row vectors)\nvx = line(:, 3)';\nvy = line(:, 4)';\n\n% squared norm of direction vectors, with a check of validity\ndelta = (vx .* vx + vy .* vy);\ninvalidEdges = delta < eps;\ndelta(invalidEdges) = 1; \n\n% difference of coordinates between point and line origins\n% (NP-by-NE arrays)\ndx = bsxfun(@minus, point(:, 1), line(:, 1)');\ndy = bsxfun(@minus, point(:, 2), line(:, 2)');\n\n% compute position of points projected on the line, by using normalised dot\n% product \n% (result is a NP-by-NL array) \npos = bsxfun(@rdivide, bsxfun(@times, dx, vx) + bsxfun(@times, dy, vy), delta);\n\n% ensure degenerated lines are correclty processed (consider the line\n% origin as closest point)\npos(:, invalidEdges) = 0;\n\n% compute distance between point and its projection on the line\ndist = hypot(bsxfun(@times, pos, vx) - dx, bsxfun(@times, pos, vy) - dy);\n\n\n% if size(line, 1)==1 && size(point, 1)>1\n% line = repmat(line, [size(point, 1) 1]);\n% end\n% \n% if size(point, 1)==1 && size(line, 1)>1\n% point = repmat(point, [size(line, 1) 1]);\n% end\n% \n% dx = line(:, 3);\n% dy = line(:, 4);\n% \n% % compute position of points projected on line\n% tp = ((point(:, 2) - line(:, 2)).*dy + (point(:, 1) - line(:, 1)).*dx) ./ (dx.*dx+dy.*dy);\n% p0 = line(:, 1:2) + [tp tp].*[dx dy];\n% \n% \n% % compute distances between points and their projections\n% dx = point - p0;\n% dist = sqrt(sum(dx.*dx, 2));\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/functions/matGeom/geom2d/distancePointLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.7840327893544804}} {"text": "function quad_error = simplex_unit_monomial_quadrature ( dim_num, expon, ...\n point_num, x, w )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_UNIT_MONOMIAL_QUADRATURE: quadrature of monomials in a unit simplex.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Input, integer POINT_NUM, the number of points in the rule.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the quadrature points.\n%\n% Input, real W(POINT_NUM), the quadrature weights.\n%\n% Output, real QUAD_ERROR, the quadrature error.\n%\n\n%\n% Get the exact value of the integral of the unscaled monomial.\n%\n scale = simplex_unit_monomial_int ( dim_num, expon );\n%\n% Evaluate the monomial at the quadrature points.\n%\n value = monomial_value ( dim_num, point_num, x, expon );\n%\n% Compute the weighted sum and divide by the exact value.\n%\n volume = simplex_unit_volume ( dim_num );\n quad = volume * ( w * value' ) / scale;\n%\n% Error:\n%\n exact = 1.0;\n quad_error = abs ( quad - exact );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/simplex_gm_rule/simplex_unit_monomial_quadrature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7840113712795976}} {"text": "function point = projPointOnLine3d(point, line)\n%PROJPOINTONLINE3D Project a 3D point orthogonally onto a 3D line.\n%\n% PT2 = projPointOnLine3d(PT, LINE).\n% Computes the (orthogonal) projection of 3D point PT onto the 3D line\n% LINE. \n% \n% Function works also for multiple points and lines. In this case, it\n% returns multiple points.\n% Point PT1 is a N-by-3 array, and LINE is a N-by-6 array.\n% Result PT2 is a N-by-3 array, containing coordinates of orthogonal\n% projections of PT1 onto lines LINE. \n%\n%\n% See also:\n% projPointOnLine, distancePointLine3d\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 2012-08-23.\n%\n\n% HISTORY\n\n% direction vector of the line\nvx = line(:, 4);\nvy = line(:, 5);\nvz = line(:, 6);\n\n% difference of point with line origin\ndx = point(:,1) - line(:,1);\ndy = point(:,2) - line(:,2);\ndz = point(:,3) - line(:,3);\n\n% Position of projection on line, using dot product\ndelta = vx .* vx + vy .* vy + vz .* vz;\ntp = (dx .* vx + dy .* vy + dz .* vz) ./ delta;\n\n% convert position on line to cartesian coordinates\npoint = [line(:,1) + tp .* vx, line(:,2) + tp .* vy, line(:,3) + tp .* vz];\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/projPointOnLine3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.78398323292446}} {"text": "function diceC = ellipseDice(E1,E2,varargin)\n% Compute the percentage overlap of a pair of ellipses\n%\n% Syntax\n% diceC = ellipseDice(E1,E2,varargin)\n%\n% Input\n% E1, E2 - Two structs that contain the ellipse parameters\n% .center\n% .sigma\n% .theta\n% \n% Optional key/value pairs\n% spatial samples - vector of the sample points in deg (default -10:0.1:10);\n% show - Create an image showing the overlap\n%\n% Outputs\n% diceC - Dice coefficient = 2*areaOfE1E2Intersection / eArea1 + eArea2 ;\n%\n% Author, Wandell January 17, 2020 \n%\n% See also\n% ellipseInterior, ellipsePoints, ...\n\n\n% Examples:\n%{\n E1.center = [0,0]; E1.sigma = [3,1]; E1.theta = pi;\n E2.center = [-1,0]; E2.sigma = [3,1]; E2.theta = pi/2;\n diceC = ellipseDice(E1,E2,'show',true);\n%}\n%{\n E1.center = [0,0]; E1.sigma = [1,1]; E1.theta = pi;\n E2.center = [-1,0]; E2.sigma = [3,3]; E2.theta = pi/2;\n diceC = ellipseDice(E1,E2,'show',true);\n%}\n%{\n E1.center = [0,0]; E1.sigma = [1,1]; E1.theta = pi;\n E2.center = [0,0]; E2.sigma = [1,1]; E2.theta = pi/2;\n diceC = ellipseDice(E1,E2,'show',true);\n%}\n\n%% Input parameters\n\n% Remove spaces and force lower case\nvarargin = mrvParamFormat(varargin);\n\np = inputParser;\n\n% Validation function\nvFunc = @(x)(isstruct(x) && isfield(x,'center') && isfield(x,'sigma') && isfield(x,'theta'));\np.addRequired('E1',vFunc);\np.addRequired('E2',vFunc);\n\np.addParameter('spatialsamples',(-10:0.05:10),@isvector);\np.addParameter('show',false,@islogical);\n\np.parse(E1,E2,varargin{:});\n\nsamples = p.Results.spatialsamples;\nshow = p.Results.show;\n\n%% Compute\n\n% 1 inside, 0 outside.\n[img1, nSamples] = ellipseInterior('center',E1.center, ...\n 'sigma',E1.sigma, ...\n 'theta',E1.theta',...\n 'spatial samples',samples);\nimg2 = ellipseInterior('center',E2.center,...\n 'sigma',E2.sigma,...\n 'theta',E2.theta,...\n 'spatial samples',samples);\n\n%%\noverlapArea = sum(img1(:) .* img2(:));\ndiceC = 2*overlapArea/ (sum(img1(:)) + sum(img2(:)));\n\nif show\n img = img1 + img2;\n mrvNewGraphWin; colormap([0.2 0.3 0.4; 0.6 0.6 0.6; 1 1 1]);\n image(samples,samples,img + 1); axis image;\n xlabel('Deg'); ylabel('Deg'); grid on\nend\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/mrBOLD/Stats/ellipse/ellipseDice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.783919651268594}} {"text": "function fx = p02_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P02_FUN evaluates the integrand for problem 2.\n%\n% Discussion:\n%\n% The integrand is discontinuous at X = 0.3.\n%\n% Interval:\n%\n% 0 <= x <= 1\n%\n% Integrand:\n%\n% if ( x < 0.3 )\n% f(x) = 0\n% else\n% f(x) = 1\n%\n% Antiderivative:\n%\n% if ( x < 0.3 )\n% g(x) = 0\n% else\n% g(x) = X - 0.3\n%\n% Exact Integral:\n%\n% 0.7\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% John Burkardt\n%\n% Reference:\n%\n% David Kahaner,\n% Comparison of Numerical Quadrature Formulas,\n% in Mathematical Software, edited by John R Rice,\n% Academic Press, 1971.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n fx = ( 0.3 <= 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_int/p02_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8933094010836643, "lm_q1q2_score": 0.7838582634902209}} {"text": "function y = entr( x )\n\n%ENTR Scalar entropy.\n% ENTR(X) returns an array of the same size as X with the unnormalized\n% entropy function applied to each element:\n% { -X.*LOG(X) if X > 0,\n% ENTR(X) = { 0 if X == 0,\n% { -Inf otherwise.\n% If X is a vector representing a discrete probability distribution, then\n% SUM(ENTR(X)) returns its entropy.\n%\n% Disciplined convex programming information:\n% ENTR(X) is concave and nonmonotonic in X. Thus when used in CVX\n% expressions, X must be real and affine. Its use will effectively \n% constrain X to be nonnegative: there is no need to add an\n% additional X >= 0 to your model in order to enforce this.\n\nnarginchk(1,1);\ncvx_expert_check( 'entr', x );\ny = -rel_entr( x, 1 );\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/entr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7838335578596131}} {"text": "function p = equivalentPerimeter(grains)\n% returns the equivalent perimeter of grain-polygon\n%\n% Description\n% The equivalent perimeter of grain-polygon is defined as\n%\n% $$ p = 2 \\pi ER $$,\n%\n% where $ER$ is the of a\n% grain\n%\n% Input\n% grains - @grain2d\n%\n% Output\n% p - equivalent perimeter in measurement units\n%\n% See also\n% grain2d/deltaarea grain2d/paris grain2d/equivalentRadius\n\np = 2*pi*equivalentRadius(grains);\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/equivalentPerimeter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7837871706585248}} {"text": "function n2 = dist2(x, c)\n%DIST2\tCalculates squared distance between two sets of points.\n%\n%\tDescription\n%\tD = DIST2(X, C) takes two matrices of vectors and calculates the\n%\tsquared Euclidean distance between them. Both matrices must be of\n%\tthe same column dimension. If X has M rows and N columns, and C has\n%\tL rows and N columns, then the result has M rows and L columns. The\n%\tI, Jth entry is the squared distance from the Ith row of X to the\n%\tJth row of C.\n%\n%\tSee also\n%\tGMMACTIV, KMEANS, RBFFWD\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nif nargin<2\n c = x;\nend\n[ndata, dimx] = size(x);\n[ncentres, dimc] = size(c);\nif dimx ~= dimc\n\terror('Data dimension does not match dimension of centres')\nend\n\nn2 = (ones(ncentres, 1) * sum((x.^2)', 1))' + ...\n ones(ndata, 1) * sum((c.^2)',1) - ...\n 2.*(x*(c'));\n\n% Rounding errors occasionally cause negative entries in n2\nif any(any(n2<0))\n n2(n2<0) = 0;\nend", "meta": {"author": "BatzoglouLabSU", "repo": "SIMLR", "sha": "bf44967cd40d9d4c789ecf866b3aae15ae6190f5", "save_path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR", "path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR/SIMLR-bf44967cd40d9d4c789ecf866b3aae15ae6190f5/MATLAB/src/dist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7837871668156375}} {"text": "% Polynomial discrimination\n% Section 8.6.2, Boyd & Vandenberghe \"Convex Optimization\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX by Joelle Skaf - 10/23/05\n% (a figure is generated)\n%\n% The goal is to find the polynomial of degree 4 on R^n that separates\n% two sets of points {x_1,...,x_N} and {y_1,...,y_N}. We are trying to find\n% the coefficients of an order-4-polynomial P(x) that would satisfy:\n% minimize t\n% s.t. P(x_i) <= t for i = 1,...,N\n% P(y_i) >= t for i = 1,...,M\n\n% Data generation\nrand('state',0);\nN = 100;\nM = 120;\n\n% The points X lie within a circle of radius 0.9, with a wedge of points\n% near [1.1,0] removed. The points Y lie outside a circle of radius 1.1,\n% with a wedge of points near [1.1,0] added. The wedges are precisely what\n% makes the separation difficult and interesting.\nX = 2 * rand(2,N) - 1;\nX = X * diag(0.9*rand(1,N)./sqrt(sum(X.^2)));\nY = 2 * rand(2,M) - 1;\nY = Y * diag((1.1+rand(1,M))./sqrt(sum(Y.^2)));\nd = sqrt(sum((X-[1.1;0]*ones(1,N)).^2));\nY = [ Y, X(:,d<0.9) ];\nX = X(:,d>1);\nN = size(X,2);\nM = size(Y,2);\n\n% Construct Vandermonde-style monomial matrices\np1 = [0,0,1,0,1,2,0,1,2,3,0,1,2,3,4]';\np2 = [0,1,1,2,2,2,3,3,3,3,4,4,4,4,4]'-p1;\nnp = length(p1);\nop = ones(np,1);\nmonX = X(op,:) .^ p1(:,ones(1,N)) .* X(2*op,:) .^ p2(:,ones(1,N));\nmonY = Y(op,:) .^ p1(:,ones(1,M)) .* Y(2*op,:) .^ p2(:,ones(1,M));\n\n% Solution via CVX\nfprintf(1,'Finding the optimal polynomial of order 4 that separates the 2 classes...');\n\ncvx_begin\n variables a(np) t(1)\n minimize ( t )\n a'*monX <= t;\n a'*monY >= -t;\n % For normalization purposes only\n norm(a) <= 1;\ncvx_end\n\nfprintf(1,'Done! \\n');\n\n% Displaying results\nnopts = 2000;\nangles = linspace(0,2*pi,nopts);\ncont = zeros(2,nopts);\nfor i=1:nopts\n v = [cos(angles(i)); sin(angles(i))];\n l = 0; u = 1;\n while ( u - l > 1e-3 )\n s = (u+l)/2;\n x = s * v;\n if a' * ( x(op,:) .^ p1 .* x(2*op) .^ p2 ) > 0, \n u = s; \n else\n l = s;\n end\n end;\n s = (u+l)/2;\n cont(:,i) = s*v;\nend;\n\ngraph = plot(X(1,:),X(2,:),'o', Y(1,:), Y(2,:),'o', cont(1,:), cont(2,:), '-');\nset(graph(2),'MarkerFaceColor',[0 0.5 0]);\ntitle('Optimal order-4 polynomial that separates the 2 classes')\n% print -deps min-deg-discr.eps\n\n%%%% Dual infeasible ?????\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/Ch08_geometric_probs/poly4_discr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7837225846904551}} {"text": "function len = polygonLength(poly, varargin)\n%POLYGONLENGTH Perimeter of a polygon.\n%\n% L = polygonLength(POLYGON);\n% Computes the boundary length of a polygon. POLYGON is given by a N-by-2\n% array of vertices. \n%\n% Example\n% % Perimeter of a circle approximation\n% poly = circleToPolygon([0 0 1], 200);\n% polygonLength(poly)\n% ans =\n% 6.2829\n%\n% See also \n% polygons2d, polygonCentroid, polygonArea, drawPolygon, polylineLength\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-05-11\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\n% If first argument is a cell array, this is a multi-polygon, and we simply\n% add the lengths of individual polygons\nif iscell(poly)\n len = 0;\n for i = 1:length(poly)\n len = len + polygonLength(poly{i});\n end\n return;\nend\n\n% case of a polygon given as two coordinate arrays\nif nargin == 2\n poly = [poly varargin{1}];\nend\n\n% check there are enough points\nif size(poly, 1) < 2\n len = 0;\n return;\nend\n\n% compute length\nif size(poly, 2) == 2\n % polygon in dimension 2 (classical case)\n dp = diff(poly([1:end 1], :), 1, 1);\n len = sum(hypot(dp(:, 1), dp(:, 2)));\nelse\n % polygon of larger dimension\n len = sum(sqrt(sum(diff(poly([2:end 1], :), 1, 1).^2, 2)));\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/polygons2d/polygonLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7837225710469558}} {"text": "function qr = plane_normal_xyz_to_qr ( pp, normal, pq, pr, n, xyz )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_XYZ_TO_QR: XYZ to QR coordinates for a normal form plane.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% NORMAL is a normal vector to the plane.\n%\n% Two vectors PQ and PR can be computed with the properties that\n% * NORMAL, PQ and PR are pairwise orthogonal;\n% * PQ and PR have unit length;\n% * every point P in the plane has a \"QR\" representation\n% as P = PP + q * PQ + r * PR.\n%\n% This function is given the XYZ coordinates of a set of points on the\n% plane, and returns the QR coordinates.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane.\n%\n% Input, real NORMAL(3), a normal vector N to the plane. The\n% vector must not have zero length, but it is not necessary for N\n% to have unit length.\n%\n% Input, real PQ(3), a vector of unit length,\n% perpendicular to the vector N and the vector PR.\n%\n% Input, real PR(3), a vector of unit length,\n% perpendicular to the vector N and the vector PQ.\n%\n% Input, integer N, the number of points on the plane.\n%\n% Input, real XYZ(3,N), the XYZ coordinates of the points.\n%\n% Output, real QR(2,N), the QR coordinates of the points.\n%\n qr = [ pq'; pr' ] * ( xyz(1:3,1:n) - repmat ( pp, 1, n ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_normal_xyz_to_qr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7837225693859181}} {"text": "function C = ttimes(A,B)\n% TTIMES Tropical multiplication (max-plus algebra)\n%\n% C = TTIMES(A,B) Computes the tropical multiplication of the matrices A\n% and B, AB(i,j) = max(A(i,:) + B(:,j)');\n%\n% See also tplus\n\nn = size(A,1);\nm = size(B,2);\nC = reshape(max(kron(ones(m,1),A)+kron(B',ones(n,1)),[],2),n,m);\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/ttimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7836759824301222}} {"text": "% Weighted analytic center of a set of linear inequalities\n% Joëlle Skaf - 04/29/08 \n%\n% The weighted analytic center of a set of linear inequalities:\n% a_i^Tx <= b_i i=1,...,m,\n% is the solution of the unconstrained minimization problem \n% minimize -sum_{i=1}^m w_i*log(b_i-a_i^Tx),\n% where w_i>0\n\n% Input data \nrandn('state', 0);\nrand('state', 0);\nn = 10;\nm = 50; \ntmp = randn(n,1);\nA = randn(m,n); \nb = A*tmp + 2*rand(m,1); \nw = rand(m,1); \n\n% Analytic center \ncvx_begin\n variable x(n)\n minimize -sum(w.*log(b-A*x))\ncvx_end\n\ndisp('The weighted analytic center of the set of linear inequalities is: ');\ndisp(x);\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/weighted_analytic_center.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854094395751, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7836518025150064}} {"text": "function lambda = gk316_eigenvalues ( n )\n\n%*****************************************************************************80\n%\n%% GK316_EIGENVALUES returns the eigenvalues of GK316.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n if ( n == 1 )\n\n lambda(1,1) = 1.0;\n\n else\n\n lambda(1:n-2,1) = 1.0;\n\n a = 1.0;\n b = - ( n + 1 );\n c = - ( n * ( n + 1 ) * ( 2 * n - 5 ) ) / 6.0;\n\n lambda(n-1,1) = ( - b + sqrt ( b * b - 4.0 * a * c ) ) / ( 2.0 * a );\n lambda(n,1) = ( - b - sqrt ( b * b - 4.0 * a * c ) ) / ( 2.0 * a );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/gk316_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7836424604167345}} {"text": "function [a,t,tLength,k]=BSplineInterpIntMultiDim(t,tLength,a,k,intDims)\n%%BSPLINEINTERPINTMULTIDIM Given a hypermatrix of multivariate b-spline\n% interpolation weights a and a set of knots t,compute the\n% modified weights and knots to interpolate the integral of the\n% a given point using b-spline interpolation. If all knots at\n% the ith boundary are repeated k(i) times, then an integral\n% over the ith dimension will start from the beginning of the\n% interpolation region. Otherwise, this can be considered an\n% indefinite integral with a particular additive constant and\n% differencing and be used to get a definite integral.\n%\n%INPUTS: t The maxNumKnotsXnumDims set of knots fo r the interpolation\n% function. These are actually the values in each coordinate\n% dimension given in ascending order. The full knots are implied\n% [t1,t2,etc.]=ndgrid(t(1:tLengths(1),1),t(1:tLengths(2),2),...)\n% and the dimensions can be put together into the full set of\n% numDimsXtotalNumPoints points as tTotal=[t1(:).';t2(:).';...].\n% The first and last k(curDim)-1 knots in each dimension are\n% outside of the ends of the region with data or mark the ends of\n% the region with data. The number of rows is the maximum number\n% needed for all of the dimensions. tLength says how many items\n% in each column are actually used. These values must be real.\n% tLength A numDimX1 vector where tLength(i) says the number of elements\n% in t(:,i).\n% a A hypermatrix with numDim+1 indices containing the set of\n% coefficients for the b-splines covering all of the interpolation\n% intervals for all of the sets of interpolation values. If there\n% is only one set, the final dimension is unitary meaning that\n% there are effectively only numDim dimensions. The derivatives\n% will be applied to all sets present. These values can be real or\n% complex.\n% k A numDimsX1 or 1XnumDims set of the order of the b-splines in\n% each dimension. The value k-1 is the polynomial order of the\n% approximation being performed. If the order is the same in all\n% dimensions, then a single scalar can be passed.\n% intDims This is a numDimsX1 or a 1XnumDims boolean vector indicating\n% over which dimensions the integrals should be taken.\n%\n%OUTPUTS: a The modified coefficient matrix. This is one larger in each\n% dimensions where an integral was taken.\n% t The modified knots.\n% tLength The modified vector indicating how many knows are present.\n% k The modified set of orders.\n%\n%Equation 22 in Chapter X of [1] has 1D integration. Chapter XVII describes\n%the use of tensor product splines for more than one dimension. The\n%generalization to more than one dimension comes from just evaluating the\n%integrals across each dimension one at a time, if they are taken.\n%\n%EXAMPLE 1:\n% f=@(x,y,z)(x.^4-2*x.^2+x).*(y.^4-2*y.^2+y).*(z.^4-3*z.^2+z);\n% %The definite integral of f with respect to x and z starting at -1.5 is\n% fIntXZ=@(x,y,z)((-891+240*x.^2-320*x.^3+96*x.^5).*y.*(1-2*y+y.^3).*(-477+80*z.^2-160*z.^3+32*z.^5))/76800;\n% \n% numDims=3;\n% numPointsX=10;\n% numPointsY=11;\n% numPointsZ=9;\n% tauLengths=[numPointsX;numPointsY;numPointsZ];\n% tau=zeros(max(tauLengths),numDims);\n% tau(1:tauLengths(1),1)=linspace(-1.5,1.5,numPointsX);\n% tau(1:tauLengths(2),2)=linspace(-1.5,1.5,numPointsY);\n% tau(1:tauLengths(3),3)=linspace(-1.5,1.5,numPointsZ);\n% %Note that using meshgrid would have put the elements in the wong order.\n% %ndgrid must be used.\n% [tau1,tau2,tau3]=ndgrid(tau(1:tauLengths(1),1),tau(1:tauLengths(2),2),tau(1:tauLengths(3),3));\n% y=f(tau1,tau2,tau3);\n% \n% k=[5;5;5];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,y(:),k);\n% intDims=[1;0;1];\n% [a,t,tLength,k]=BSplineInterpIntMultiDim(t,tLength,a,k,intDims);\n% \n% numPointsY=21;\n% numPointsZ=19;\n% pointsX=linspace(-1.5,1.5,numPointsX);\n% pointsY=linspace(-1.5,1.5,numPointsY);\n% pointsZ=linspace(-1.5,1.5,numPointsZ);\n% [X,Y,Z]=ndgrid(pointsX,pointsY,pointsZ);\n% x=[X(:).';Y(:).';Z(:).'];\n% \n% zIntTrue=fIntXZ(X,Y,Z);\n% z=BSplineInterpValMultiDim(x,t,tLength,a,k);\n% max(abs(z(:)-zIntTrue(:)))\n%\n%EXAMPLE 2:\n%This is similar to example 1, except two sets of values are fitted,\n%integrated, and interpolated at once.\n% f1=@(x,y,z)(x.^4-2*x.^2+x).*(y.^4-2*y.^2+y).*(z.^4-3*z.^2+z);\n% f2=@(x,y,z)(x.^3-2*x.^2+x).*(y.^4-2*y.^2+y).*(2*z.^3-2*z.^2+1);\n% %The definite integral of f with respect to x and z starting at -1.5 is\n% fIntXZ1=@(x,y,z)((-891+240*x.^2-320*x.^3+96*x.^5).*y.*(1-2*y+y.^3).*(-477+80*z.^2-160*z.^3+32*z.^5))/76800;\n% fIntXZ2=@(x,y,z)(((-891+16*x.^2.*(6+x.*(-8+3*x))).*y.*(1-2*y+y.^3).*(-315+16*z.*(6+z.^2.*(-4+3*z))))/18432);\n% \n% numDims=3;\n% numPointsX=10;\n% numPointsY=11;\n% numPointsZ=9;\n% tauLengths=[numPointsX;numPointsY;numPointsZ];\n% tau=zeros(max(tauLengths),numDims);\n% tau(1:tauLengths(1),1)=linspace(-1.5,1.5,numPointsX);\n% tau(1:tauLengths(2),2)=linspace(-1.5,1.5,numPointsY);\n% tau(1:tauLengths(3),3)=linspace(-1.5,1.5,numPointsZ);\n% %Note that using meshgrid would have put the elements in the wong order.\n% %ndgrid must be used.\n% [tau1,tau2,tau3]=ndgrid(tau(1:tauLengths(1),1),tau(1:tauLengths(2),2),tau(1:tauLengths(3),3));\n% y1=f1(tau1,tau2,tau3);\n% y2=f2(tau1,tau2,tau3);\n% y=[y1(:),y2(:)];\n% \n% k=[5;5;5];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,y,k);\n% intDims=[1;0;1];\n% [a,t,tLength,k]=BSplineInterpIntMultiDim(t,tLength,a,k,intDims);\n% \n% numPointsY=21;\n% numPointsZ=19;\n% pointsX=linspace(-1.5,1.5,numPointsX);\n% pointsY=linspace(-1.5,1.5,numPointsY);\n% pointsZ=linspace(-1.5,1.5,numPointsZ);\n% [X,Y,Z]=ndgrid(pointsX,pointsY,pointsZ);\n% x=[X(:).';Y(:).';Z(:).'];\n% \n% zIntTrue1=fIntXZ1(X,Y,Z);\n% zIntTrue2=fIntXZ2(X,Y,Z);\n% z=BSplineInterpValMultiDim(x,t,tLength,a,k);\n% max(abs(z(:,1)-zIntTrue1(:)))\n% max(abs(z(:,2)-zIntTrue2(:)))\n%\n%EXAMPLE 3:\n%This is an example of a bivariate complex function whose integral over the\n%first dimension is interpolated.numPoints=80;\n% xMin=0;\n% xMax=3;\n% yMin=0;\n% yMax=3;\n% x=linspace(xMin,xMax,numPoints);\n% y=linspace(yMin,yMax,numPoints);\n% [X,Y]=ndgrid(x,y);\n% f=@(x,y)(sin(5*y)+1j*cos(10*x));\n% %The integral from 0 in the x dimension.\n% fIntx=@(x,y)((1/10)*1j*sin(10*x)+x.*sin(5*y));\n% \n% fxy=f(X(:),Y(:));\n% k=[5;5];\n% tau=[x(:),y(:)];\n% tauLengths=[numPoints,numPoints];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,fxy,k);\n% intDims=[1;0];\n% [a,t,tLength,k]=BSplineInterpIntMultiDim(t,tLength,a,k,intDims);\n% \n% %Interpolate the derivative\n% numPoints=100;\n% x=linspace(xMin,xMax,numPoints);\n% y=linspace(xMin,xMax,numPoints);\n% [X,Y]=ndgrid(x,y);\n% \n% fxy=fIntx(X(:),Y(:));\n% pts=[X(:).';Y(:).'];\n% fxyInterp=reshape(BSplineInterpValMultiDim(pts,t,tLength,a,k),[numPoints,numPoints]);\n% fxy=reshape(fxy,[numPoints,numPoints]);\n% \n% figure(1)\n% clf\n% hold on\n% surface(X,Y,real(fxy),'EdgeColor','none')\n% title('Real Integral Values')\n% colorbar()\n% \n% figure(2)\n% clf\n% hold on\n% surface(X,Y,imag(fxy),'EdgeColor','none')\n% title('Imaginary Integral Values')\n% colorbar()\n% \n% figure(3)\n% clf\n% hold on\n% surface(X,Y,abs(real(fxyInterp)-real(fxy)),'EdgeColor','none')\n% title('Real Interpolation Error')\n% colorbar()\n% \n% figure(4)\n% clf\n% hold on\n% surface(X,Y,abs(imag(fxyInterp)-imag(fxy)),'EdgeColor','none')\n% title('Imaginary Interpolation Error')\n% colorbar()\n%\n%REFERENCES:\n%[1] C. de Boor, A Practical Guide to Splines. New York: Springer-Verlag,\n% 1978.\n%\n%April 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDims=length(tLength);\nnumA=size(a);\n\nif(length(numA)==numDims)\n numSets=1;\n numA=[numA,1];\nelse\n numSets=numA(end);\nend\n\ntNew=zeros(max(tLength)+2,numDims);\nfor curDim=1:numDims\n if(intDims(curDim)==0)\n tNew(1:tLength(curDim),curDim)=t(1:tLength(curDim),curDim);\n continue;\n end\n\n temp=zeros(1,numDims);\n temp(curDim)=1;\n aNew=zeros(numA+[temp,0]);\n \n %Next, we go through all tuples of values for the dimensions other than\n %this one. In each instance, we must take the integral of the a terms\n %that are present. These indices select all of the dimensions that are\n %not the current one across which derivatives are being taken.\n for curSet=1:numSets\n idxList=[1:(curDim-1),(curDim+1):numDims];\n\n maxVals=numA(idxList)-1;\n numACur=numA(curDim);\n curTuple=getNextTuple(numDims-1);\n idxCell=cell(1,numDims+1);\n idxCell{numDims+1}=curSet;\n tCur=t(1:tLength(curDim),curDim);\n kCur=k(curDim);\n\n outputIdx=1:(numACur+1);\n while(~isempty(curTuple))\n idxCell{curDim}=1:numA(curDim);%Mark the free dimension.\n\n %We have to select the elements in a to work on based on the\n %current tuple.\n for curIdx=1:(numDims-1)\n idxCell{idxList(curIdx)}=curTuple(curIdx)+1;\n end\n\n aCur=reshape(a(idxCell{:}),[numACur,1]);\n\n [~,aCur]=BSplineInterpInt(tCur,aCur,kCur);\n idxCell{curDim}=outputIdx;\n aNew(idxCell{:})=aCur;\n\n curTuple=getNextTuple(curTuple,maxVals);\n end\n end\n numA(curDim)=numA(curDim)+1;\n a=aNew;\n k(curDim)=k(curDim)+1;\n tNew(1:(tLength(curDim)+2),curDim)=[t(1,curDim);t(1:tLength(curDim),curDim);t(tLength(curDim),curDim)];\n tLength(curDim)=tLength(curDim)+2;\nend\na=aNew;\nt=tNew;\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/Interpolation/B-Splines/BSplineInterpIntMultiDim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7836069822609164}} {"text": "function value = beta_inc ( a, b, x )\n\n%*****************************************************************************80\n%\n%% BETA_INC returns the value of the incomplete Beta function.\n%\n% Discussion:\n%\n% This calculation requires an iteration. In some cases, the iteration\n% may not converge rapidly, or may become inaccurate.\n%\n% BETA_INC(A,B,X)\n%\n% = Integral ( 0 <= T <= X ) T^(A-1) (1-T)^(B-1) dT\n% / Integral ( 0 <= T <= 1 ) T^(A-1) (1-T)^(B-1) dT\n%\n% = Integral ( 0 <= T <= X ) T^(A-1) (1-T)^(B-1) dT\n% / BETA(A,B)\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% Original FORTRAN77 version by Majumder, Bhattacharjee.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Majumder and Bhattacharjee,\n% Algorithm AS63,\n% Applied Statistics,\n% 1973, volume 22, number 3.\n%\n% Parameters:\n%\n% Input, A, B, the parameters of the function.\n% 0.0D+00 < A,\n% 0.0D+00 < B.\n%\n% Input, real X, the argument of the function.\n% Normally, 0.0D+00 <= X <= 1.0.\n%\n% Output, BETA_INC, the value of the function.\n%\n it_max = 1000;\n tol = 1.0E-07;\n\n if ( a <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BETA_INC - Fatal error!\\n' );\n fprintf ( 1, ' A <= 0.\\n' );\n error ( 'BETA_INC - Fatal error!' );\n end\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BETA_INC - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n error ( 'BETA_INC - Fatal error!' );\n end\n\n if ( x <= 0.0 )\n value = 0.0;\n return\n elseif ( 1.0 <= x )\n value = 1.0;\n return\n end\n%\n% Change tail if necessary and determine S.\n%\n psq = a + b;\n\n if ( a < ( a + b ) * x )\n xx = 1.0 - x;\n cx = x;\n pp = b;\n qq = a;\n indx = 1;\n else\n xx = x;\n cx = 1.0 - x;\n pp = a;\n qq = b;\n indx = 0;\n end\n\n term = 1.0;\n i = 1;\n value = 1.0;\n\n ns = floor ( qq + cx * ( a + b ) );\n%\n% Use Soper's reduction formulas.\n%\n rx = xx / cx;\n\n temp = qq - i;\n if ( ns == 0 )\n rx = xx;\n end\n\n it = 0;\n\n while ( 1 )\n\n it = it + 1;\n\n if ( it_max < it )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BETA_INC - Fatal error!\\n' );\n fprintf ( 1, ' Maximum number of iterations exceeded!\\n' );\n fprintf ( 1, ' IT_MAX = %d\\n', it_max );\n error ( 'BETA_INC - Fatal error!' );\n end\n\n term = term * temp * rx / ( pp + i );\n value = value + term;\n temp = abs ( term );\n\n if ( temp <= tol & temp <= tol * value )\n break\n end\n\n i = i + 1;\n ns = ns - 1;\n\n if ( 0 <= ns )\n temp = qq - i;\n if ( ns == 0 )\n rx = xx;\n end\n else\n temp = psq;\n psq = psq + 1.0;\n end\n\n end\n%\n% Finish calculation.\n%\n value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) ) ...\n / ( beta ( a, b ) * pp );\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/prob/beta_inc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7835996406115898}} {"text": "%% Pendulum example\n% This example applies energy-preserving piDMD to reconstruct the trajectory of\n% a double pendulum from noisy measurements.\naddpath('../src')\nrng(1); % Set random seed\n\n% Define parameters of problem\nl1=1; l2=1.5; % Lengths of rods\nm1=1 ; m2=1.5; g=9.81; % Masses and gravity\nparams = [l1, l2, m1, m2, g]; % Concatenate parameters\n\n% Construct linearised energy inner product\nW(1,1) = (m1/2+m2/2)*g*l1;\nW(2,2) = m2/2*g*l2;\nW(3,3) = (m1/2+m2/2)*l1^2;\nW(4,3) = m2/2*l1*l2;\nW(3,4) = W(4,3);\nW(4,4) = m2/2*l2^2;\nC = chol(W); % Calculate inner product\n\n% Set number of samples and span\ntend = 30; nt = 1000;\ntspan= linspace(0,tend,nt);\n\n% Set initial conditions\ntheta1= 0.4; theta1_prime=0;\ntheta2= 0.7; theta2_prime=0;\ny0=[theta1 theta1_prime theta2 theta2_prime];\n\n% Solve ODE\n[t,y]=ode45(@(t,y) pendulum(t,y,params), tspan,y0);\n\n% Extract data\nth1 = y(:,1); th2 = y(:,3); th1dt = y(:,2); th2dt = y(:,4);\nx = [th1'; th2'; th1dt'; th2dt'];\nxn = x + 1e-1*std(x,[],2).*randn(size(x)); % Add noise\ndata = C*xn; % Rescale measurements into energy norm\nnTrain = nt-1;\nX = data(:,1:nTrain); Y = data(:,2:nTrain+1);\n\n% Train models\n[piA,piVals] = piDMD(X,Y,'orthogonal');\n[exA,exVals] = piDMD(X,Y,'exact');\n\n% Perform reconstructions\npiRec = zeros(4,nt); piRec(:,1) = data(:,1);\nexRec = zeros(4,nt); exRec(:,1) = data(:,1);\nfor j = 2:nt\npiRec(:,j) = piA(piRec(:,j-1));\nexRec(:,j) = exA(exRec(:,j-1));\nend\n\n% Rescale reconstructions back into physical norm\nfpiRec = C\\piRec; fexRec = C\\exRec;\n\n%% Plot results\nfigure(1); LW = 'LineWidth'; IN = 'Interpreter'; LT = 'Latex'; FS = 'FontSize';\nsubplot(3,1,1)\nc1 = .8*[1 1 1]; c2 = .8*[1 1 1];\nplot(tspan,xn(1,:),LW,2,'Color',c1)\nhold on\nplot(tspan,xn(2,:),LW,2,'Color',c2)\nhold off; trajPlot('measurements'); xticklabels([])\nsubplot(3,1,2)\nplot(tspan,x(1,:),LW,3,'Color', c1)\nhold on\nplot(tspan,fpiRec(1,:),'b--',LW,2)\nplot(tspan,fexRec(1,:),'r--',LW,2)\nylabel('$\\theta_1$',IN,LT)\nhold off; trajPlot('$\\theta_1$'); xticklabels([])\nsubplot(3,1,3)\nl1=plot(t,x(2,:),LW,3,'Color', c2);\nhold on\nl2=plot(t,fpiRec(2,:),'b--',LW,2);\nl3=plot(t,fexRec(2,:),'r--',LW,2);\nhold off; xlabel('time',FS,20,IN,LT)\ntrajPlot('$\\theta_2$')\nlegend([l1,l2,l3],{'truth','piDMD','exact DMD'},IN,LT)\nfunction yp = pendulum(~, y, params)\n\nl1=params(1); l2=params(2); \nm1=params(3); m2=params(4); \ng=params(5);\n\na = (m1+m2)*l1 ;\nb = m2*l2*cos(y(1)-y(3)) ;\nc = m2*l1*cos(y(1)-y(3)) ;\nd = m2*l2 ;\ne = -m2*l2*y(4)* y(4)*sin(y(1)-y(3))-g*(m1+m2)*sin(y(1)) ;\nf = m2*l1*y(2)*y(2)*sin(y(1)-y(3))-m2*g*sin(y(3)) ;\nyp=zeros(4,1);\nyp(1) = y(2);\nyp(3)= y(4) ;\nyp(2)= (e*d-b*f)/(a*d-c*b) ;\nyp(4)= (a*f-c*e)/(a*d-c*b) ;\nend\n\nfunction trajPlot(j) % Nice plot of trajectories\nyticks([-pi/4,0,pi/4]); yticklabels([{'$-\\pi/4$'},{'0'},{'$\\pi/4$'}])\nset(gca,'TickLabelInterpreter','Latex','FontSize',20);grid on\nylim([-1,1])\nylabel(j,'Interpreter','latex','FontSize',20)\nend", "meta": {"author": "baddoo", "repo": "piDMD", "sha": "743d8cbc5267799ed9f32145e2b5854f07960a20", "save_path": "github-repos/MATLAB/baddoo-piDMD", "path": "github-repos/MATLAB/baddoo-piDMD/piDMD-743d8cbc5267799ed9f32145e2b5854f07960a20/examples/pendulumExample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7835996334939742}} {"text": "%\n% This code calculates the interevent distances and the correlation integral\n% of a given earthquake distribution.\n% Francesco Pacchiani 3/2000\n%\n%\n% Calculation of the 3D distances between all possible pairs\n% (combination of n epicenters taken 2 at a time) of earthquakes of\n% the given dataset.\n%\n%\n% Variables\n%\nN = size(E,1);\t\t\t\t% N= # of events in the catalogue; E= Earthquake catalogue\npairdist = []; \t\t\t% pairdist= Vector of interevent distances\nj = nchoosek(N,2);\t\t\t% j= # of interevent distances calculated\npairdist = zeros(j,1);\nk = 0;\n%E.Latitude= (max(Da(:,2))+min(Da(:,2)))/2;\n%\n%\n% Calculation of the interevent distances in 2D plus the depths differences.\n%\n%\nfor i = 1:(N-1)\n\n lon1 = repmat(E(i,1), [(N-i),1]);\n lat1 = repmat(E(i,2), [(N-i),1]);\n\n lon2 = E((i+1):end, 1);\n lat2 = E((i+1):end, 2);\n\n pairdist(k+1:k + size(lon1, 1)) = distance(lat1,lon1,lat2,lon2);\n\n k = k + size(lon1,1);\n\nend\n\nclear i j k;\n%\n%\n% Conversion of the interevent distances from degrees to kilometers and calculates\n% the interevent distances in three dimensions.\n%\n%\nif dtokm == 1\n pairdist = pairdist.*111;\nend\n%\n%\n% Calculation of the correlation integral using as input the\n% pair distances computed above.\n%\n%\n% Variables\n%\nd = 2;\t\t\t\t\t\t%d = the dimension of the embedding volume.\nrmax = max(pairdist);\nrmin = min(pairdist);\n\nif rmin == 0\n rmin = 0.01;\nend\n\nlrmin = log10(rmin);\nlrmax = log10(max(pairdist));\n\n%u = (log10(rmin):0.15:log10(rmax))';\n%\n% Defining the distance vector r in order that on the\n% log-log graph all the points plot at equal distances from one another.\n%\nr = (logspace(lrmin, lrmax, 50))';\n%r = zeros(size(u,1),1);\n%r = 10.^u;\n%\n%\ncorint = [];\t\t\t\t\t\t% corint= Vector of ?cumulative? correlation integral values for increasing interevent radius\ncorint = zeros(size(r,1),1);\nk = 1;\n\nfor i = 1:size(r,1)\n\n j = [];\n j = pairdist < r(i);\n corint (k,1) = (2/(N*(N-1)))*sum(j);\n k = k + 1;\n\nend\n\nclear i j k;\n%\n%\n% Plotting of the correlation integral in function of the interevent\n% distance r.\n%\n%\ndofdnofig;\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/fractal/pdc2nofig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7835996317729388}} {"text": "function [label, model, llh] = mixGaussEm(X, init)\n% Perform EM algorithm for fitting the Gaussian mixture model.\n% Input: \n% X: d x n data matrix\n% init: k (1 x 1) number of components or label (1 x n, 1<=label(i)<=k) or model structure\n% Output:\n% label: 1 x n cluster label\n% model: trained model structure\n% llh: loglikelihood\n% Written by Mo Chen (sth4nth@gmail.com).\n%% init\nfprintf('EM for Gaussian mixture: running ... \\n');\ntol = 1e-6;\nmaxiter = 500;\nllh = -inf(1,maxiter);\nR = initialization(X,init);\nfor iter = 2:maxiter\n [~,label(1,:)] = max(R,[],2);\n R = R(:,unique(label)); % remove empty clusters\n model = maximization(X,R);\n [R, llh(iter)] = expectation(X,model);\n if abs(llh(iter)-llh(iter-1)) < tol*abs(llh(iter)); break; end;\nend\nllh = llh(2:iter);\n\nfunction R = initialization(X, init)\nn = size(X,2);\nif isstruct(init) % init with a model\n R = expectation(X,init);\nelseif numel(init) == 1 % random init k\n k = init;\n label = ceil(k*rand(1,n));\n R = full(sparse(1:n,label,1,n,k,n));\nelseif all(size(init)==[1,n]) % init with labels\n label = init;\n k = max(label);\n R = full(sparse(1:n,label,1,n,k,n));\nelse\n error('ERROR: init is not valid.');\nend\n\nfunction [R, llh] = expectation(X, model)\nmu = model.mu;\nSigma = model.Sigma;\nw = model.w;\n\nn = size(X,2);\nk = size(mu,2);\nR = zeros(n,k);\nfor i = 1:k\n R(:,i) = loggausspdf(X,mu(:,i),Sigma(:,:,i));\nend\nR = bsxfun(@plus,R,log(w));\nT = logsumexp(R,2);\nllh = sum(T)/n; % loglikelihood\nR = exp(bsxfun(@minus,R,T));\n\nfunction model = maximization(X, R)\n[d,n] = size(X);\nk = size(R,2);\nnk = sum(R,1);\nw = nk/n;\nmu = bsxfun(@times, X*R, 1./nk);\n\nSigma = zeros(d,d,k);\nr = sqrt(R);\nfor i = 1:k\n Xo = bsxfun(@minus,X,mu(:,i));\n Xo = bsxfun(@times,Xo,r(:,i)');\n Sigma(:,:,i) = Xo*Xo'/nk(i)+eye(d)*(1e-6);\nend\n\nmodel.mu = mu;\nmodel.Sigma = Sigma;\nmodel.w = w;\n\nfunction y = loggausspdf(X, mu, Sigma)\nd = size(X,1);\nX = bsxfun(@minus,X,mu);\n[U,p]= chol(Sigma);\nif p ~= 0\n error('ERROR: Sigma is not PD.');\nend\nQ = U'\\X;\nq = dot(Q,Q,1); % quadratic term (M distance)\nc = d*log(2*pi)+2*sum(log(diag(U))); % normalization constant\ny = -(c+q)/2;", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter09/mixGaussEm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7834920335661724}} {"text": "function value = r8_cotd ( degrees )\n\n%*****************************************************************************80\n%\n%% R8_COTD returns the cotangent of an angle given in degrees.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real DEGREES, the angle in degrees.\n%\n% Output, real VALUE, the cotangent of the angle.\n%\n radians = pi * ( degrees / 180.0 );\n\n value = cos ( radians ) / sin ( radians );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_cotd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7834920313940452}} {"text": "function [h mu ul ll] = circ_mtest(alpha, dir, xi, w, d)\n%\n% [pval, z] = circ_mtest(alpha, dir, w, d)\n% One-Sample test for the mean angle.\n% H0: the population has mean dir.\n% HA: the population has not mean dir.\n%\n% Note: This is the equvivalent to a one-sample t-test with specified\n% mean direction.\n%\n% Input:\n% alpha\tsample of angles in radians\n% dir assumed mean direction\n% [xi alpha level of the test]\n% [w\t\tnumber of incidences in case of binned angle data]\n% [d spacing of bin centers for binned data, if supplied \n% correction factor is used to correct for bias in \n% estimation of r, in radians (!)]\n%\n% Output:\n% h 0 if H0 can not be rejected, 1 otherwise\n% mu mean\n% ul upper (1-xi) confidence level\n% ll lower (1-xi) confidence level\n%\n% PHB 7/6/2008\n%\n% References:\n% Biostatistical Analysis, J. H. Zar\n%\n% Circular Statistics Toolbox for Matlab\n\n% By Philipp Berens, 2009\n% berens@tuebingen.mpg.de - www.kyb.mpg.de/~berens/circStat.html\n\nif size(alpha,2) > size(alpha,1)\n\talpha = alpha';\nend\n\nif nargin<3\n xi = 0.05;\nend\n\nif nargin<4\n % if no specific weighting has been specified\n % assume no binning has taken place\n\tw = ones(size(alpha));\nelse\n if size(w,2) > size(w,1)\n w = w';\n end \n if length(alpha)~=length(w)\n error('Input dimensions do not match.')\n end\nend\n\nif nargin<5\n % per default do not apply correct for binned data\n d = 0;\nend\n\n% compute ingredients\nmu = circ_mean(alpha,w);\nt = circ_confmean(alpha,xi,w,d);\nul = mu + t;\nll = mu - t;\n\n% compute test via confidence limits (example 27.3)\nh = abs(circ_dist2(dir,mu)) > t;\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_mtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7834920221602529}} {"text": "function [z,pv1,pv2,pv3]=compare_bino_prob(X,Y)\n% [z,pv1,pv2,pv3]=compare_bino_prob(X,Y)\n% Compares probabilities of two binomial samples X, Y\n% Let X and Y be sets of 0 or 1, results from a Bernoully experiments\n% with probability p1 for set X and p2 for set Y.\n% Test the null hypothesis\n% H_0: p1 = p2\n% vs alternatives\n% H_1: p1 > p2\n% H_2: p1 < p2\n% H_3: p1 != p2\n%\n% Input:\n% X - row of 0 or 1\n% Y - row of 0 or 1\n%\n% Output:\n% z - normal statistics N(0,1) for H_0\n% pv1 - p-value for H_1\n% pv2 - p-value for H_2\n% pv3 - p-value for H_3\n\n% Dimiar Atanasov (2008)\n% datanasov@nbu.bg\n\nif size(X,1) > 1 || size(Y,1) > 1\n error('Sets should be rows');\nend;\n\nn_x1 = size( find(X == 1), 1 );\nn_x0 = size( find(X == 0), 1 );\n\nn_y1 = size( find(Y == 1), 2);\nn_y0 = size( find(Y == 0), 2);\n\nn_x = n_x1 + n_x0;\nn_y = n_y1 + n_y0;\n\nn_1 = n_x1 + n_y1;\nn_0 = n_x0 + n_y0;\n\nn = n_0 + n_1;\n\nh_x = n_x1 / n_x;\nh_y = n_y1 / n_y;\n\nh = (n_x1 + n_y1)/(n_x + n_y);\n\nif (n_1^2 / n < 5) || (n_0^2 / n < 5) || ( n_1*n_0 / n < 5)\n disp('Missing asymptotic behaviour!!!');\nend;\n\ns = h*(1-h)*(1/n_x + 1/n_y);\n\nz = (h_x - h_y) / sqrt(s);\n\npv1 = 1 - normcdf(z);\npv2 = normcdf(z);\npv3 = (1 - normcdf( abs(z) ))/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/26788-compares-probabilities-of-two-binomial-samples/compare_bino_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746092, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7834796401081462}} {"text": "function coeff = eq_dist_coeff(dim,N,varargin)\n%EQ_DIST_COEFF Coefficient of minimum distance of an EQ point set\n%\n%Syntax\n% coeff = eq_dist_coeff(dim,N,options);\n%\n%Description\n% COEFF = EQ_DIST_COEFF(dim,N) does the following:\n% 1) uses the recursive zonal equal area sphere partitioning algorithm to \n% partition the unit sphere S^dim into N regions,\n% 2) finds the EQ point set, the set of center points of each region,\n% 3) finds the minimum Euclidean distance between points of the EQ point set,\n% 4) sets COEFF to be the coefficient in the expression for the lower bound on\n% the minimum distance of a minimum energy point set:\n%\n% DIST >= COEFF N^(-1/dim).\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The result COEFF will be an array of the same size as N.\n%\n% COEFF = EQ_DIST_COEFF(dim,N,'offset','extra'), for dim == 2 or dim == 3, uses\n% experimental extra rotation offsets to try to maximize the minimum distance. \n% For dim > 3, extra offsets are not used.\n%\n%Notes\n% The expression for the lower bound on minimum distance of a minimum r^(-s)\n% energy point set on S^dim was given by [RakSZ95] for s == 0 and dim = 2, \n% [Dahl78] for s == dim-1, [KuiSS04 Theorem 8] for dim-1 <= s < dim and\n% [KuiS98 (1.12) p. 525] for s > dim.\n%\n% Ideally eq_dist_coeff(dim,N) should tend to area_of_sphere(dim)^(1/dim) as \n% N goes to infinity.\n%\n%Examples\n% > coeff=eq_dist_coeff(2,10)\n% coeff =\n% 3.3250\n% \n% > coeff=eq_dist_coeff(3,1:6)\n% coeff =\n% 2.0000 2.5198 2.0396 2.2449 2.4183 2.5698\n%\n%See also\n% PARTITION_OPTIONS, EQ_MIN_DIST\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Check number of arguments\n%\nerror(nargchk(2,4,nargin));\n%\n% dim is the number of dimensions\n% N is the number of regions\n%\ndist = eq_min_dist(dim,N,varargin{:});\ncoeff = dist .* N.^(1/dim);\n%\n% end function\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/eq_sphere_partitions/eq_point_set_props/eq_dist_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.783479631297447}} {"text": "function u = ref_to_koorn ( r )\n\n%*****************************************************************************80\n%\n%% REF_TO_KOORN maps points from the reference to Koornwinder's triangle.\n%\n% Discussion:\n%\n% The reference triangle has vertices:\n%\n% ( -1, -1/sqrt(3) )\n% ( +1, -1/sqrt(3) )\n% ( 0, +2/sqrt(3) )\n%\n% Koornwinder's triangle has vertices:\n%\n% ( -1, -1 )\n% ( +1, -1 )\n% ( -1, +1 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R(2), the coordinates of a point in the\n% reference triangle.\n%\n% Output, real U(2), the coordinates of the point in\n% the Koornwinder triangle.\n%\n a10 = -1.0 / 3.0;\n a11 = 1.0;\n a12 = -1.0 / sqrt ( 3.0 );\n\n a20 = - 1.0 / 3.0;\n a21 = 0.0;\n a22 = 2.0 * sqrt ( 3.0 ) / 3.0;\n\n u(1) = a10 + r(1) + a12 * r(2);\n u(2) = a20 + a22 * r(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/triangle_symq_rule/ref_to_koorn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7834649145784031}} {"text": "function [A, B] = reflexKronApprox( K, m, n )\n%\n% [A, B] = reflexKronApprox( K, m, n );\n%\n% computes a kronecker sum approximation to the blurring matrix K\n% that arises from the input PSF under reflexive boundary conditions.\n% This approximation is done a-la Nagy-Ng-Perrone (see paper for details).\n%\n% Input:\n% K - psfMatrix object\n% m - size of matrix A (assumed square)\n% n - size of matrix B (assumed square)\n%\n% Output:\n% Matrices A and B such that K \\aprrox A \\otimes B.\n%\n\n% L. Perrone, 4/28/02\n\n% Modifications: \n% 5/25/02, J. Nagy \n% Cosmetic changes to incorporate into RestoreTools \n%\n%\n% 11/17/02, J. Nagy\n% This was designed for image processing problems, where\n% it is common to use lexicographical (row) ordering.\n% But @kronMatrix functions where designed using vec (column)\n% ordering. This inconsistency has been fixed.\n\n \nP1 = K.psf;\nP2 = P1.image;\nPSF = P2{1};\nc1 = P1.center;\ncenter = c1{1};\n\n[mp, np] = size(PSF);\n\nif ( mp ~= np )\n error('For now, we expect PSF to be square')\nend\n\n%\n% Compute weighted PSF.\n%\nc = zeros(mp,1);\nc(1) = mp;\nc(2:2:end) = 1;\nR = chol( toeplitz(c) );\n\nPhat = R*PSF*R';\n\n%\n% Compute SVD of weighted PSF, which is then used to construct\n% the separable approximation.\n%\n[U,S,V] = svd( Phat );\n\n%\n% check to make sure first column looks like\n% a Gaussian, and is not inverted.\n%\nminU = abs(min(min(U(:,1))));\nmaxU = max(max(abs(U(:,1))));\nif minU == maxU\n U = -U;\n V = -V;\nend\n\n%\n% Construct approximation.\n%\na = R \\ ( U(:,1) * sqrt(S(1,1)) );\nb = R \\ ( V(:,1) * sqrt(S(1,1)) );\n\n%\n% This construction corresponds to lexicographical ordering,\n% but kronMatrix does everything corresponding to vec ordering.\n% Thus, these two do not work together.\n%%\n%%A = build_toep(a, center(1), n) + buildHank(a, center(1), n);\n%%B = build_toep(b, center(2), m) + buildHank(b, center(2), m);\n\nA = build_toep(b, center(2), m) + buildHank(b, center(2), m);\nB = build_toep(a, center(1), n) + buildHank(a, center(1), 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/oldReflexKronApprox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7834649016945335}} {"text": "function h=plotgauss2d(mu, Sigma, plot_cross)\n% PLOTGAUSS2D Plot a 2D Gaussian as an ellipse with optional cross hairs\n% h=plotgauss2(mu, Sigma)\n% \n% h=plotgauss2(mu, Sigma, 1) also plots the major and minor axes\n%\n% Example\n% clf; S=[2 1; 1 2]; plotgauss2d([0;0], S, 1); axis equal\n\nh = plotcov2(mu, Sigma);\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%\nfunction old\n\nif nargin < 3, plot_cross = 0; end\n[V,D]=eig(Sigma);\nlam1 = D(1,1);\nlam2 = D(2,2);\nv1 = V(:,1);\nv2 = V(:,2);\n%assert(approxeq(v1' * v2, 0))\nif v1(1)==0\n theta = 0; % horizontal\nelse\n theta = atan(v1(2)/v1(1));\nend\na = sqrt(lam1);\nb = sqrt(lam2);\nh=plot_ellipse(mu(1), mu(2), theta, a,b);\n\nif plot_cross\n mu = mu(:);\n held = ishold;\n hold on\n minor1 = mu-a*v1; minor2 = mu+a*v1;\n hminor = line([minor1(1) minor2(1)], [minor1(2) minor2(2)]);\n \n major1 = mu-b*v2; major2 = mu+b*v2;\n hmajor = line([major1(1) major2(1)], [major1(2) major2(2)]);\n %set(hmajor,'color','r')\n if ~held\n hold off\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/murphy/KPMtools/plotgauss2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.7833929247467015}} {"text": "function determ = skew_circulant_determinant ( n, x )\n\n%*****************************************************************************80\n%\n%% SKEW_CIRCULANT_DETERMINANT returns the determinant of the SKEW_CIRCULANT matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real X(N), the values in the first row of A.\n%\n% Output, real DETERM, the determinant.\n%\n determ = 1.0;\n\n j_hi = floor ( ( n + 1 ) / 2 );\n\n for j = 1 : j_hi\n\n lambda = 0.0;\n\n for k = 1 : n\n angle = ( 2 * j - 1 ) * ( k - 1 ) * pi / n;\n lambda = lambda + x(k) * complex ( cos ( angle ), sin ( angle ) );\n end\n\n if ( 2 * j <= n )\n determ = determ * ( abs ( lambda ) )^2;\n else\n determ = determ * real ( lambda );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/skew_circulant_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7833657531708849}} {"text": "% Gives the spectrum of a derivative effect (i.e. a zero at zero frequency)\n%\n% Input\n% dftlen : the number of bin in spectrum (full DFT length).\n% fs : [Hz] The sampling frequency\n%\n% Output\n% S : The spectrum of the derivative effect\n%\n% Copyright (c) 2011 University of Crete - Computer Science Department\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction S = spec_derivative(dftlen, fs)\n\n % The half-spectrum of a zero at frequency zero is:\n hS = fs*(2i*pi/dftlen)*(0:dftlen/2).';\n \n if mod(dftlen,2)==1\n % If DFT length is odd\n S = [hS; hS(end:-1:2)];\n else\n % If DFT length is even\n hS(end) = 0;\n S = hspec2spec(hS);\n end \n\nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/misc/spec_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7833427909046904}} {"text": "%KMEANS Finds centers of clusters and groups input samples around the clusters\n%\n% labels = cv.kmeans(data, K)\n% [labels, centers, compactness] = cv.kmeans(...)\n% [...] = cv.kmeans(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __data__ Data for clustering. An array of D-dimensional points with\n% floating-point coordinates is needed. Examples of this matrix can be: NxD\n% numeric matrix (one row per sample), or Nx1xD/1xNxD array (with dimensions\n% across slices).\n% * __K__ Number of clusters to split the set by.\n%\n% ## Output\n% * __labels__ Integer array that stores the cluster indices for every sample.\n% * __centers__ Output matrix of the cluster centers, one row per each cluster\n% center.\n% * __compactness__ Measure of compactness. See below.\n%\n% ## Options\n% * __Criteria__ The algorithm termination criteria, that is, the maximum\n% number of iterations and/or the desired accuracy. The accuracy is\n% specified as `criteria.epsilon`. As soon as each of the cluster centers\n% moves by less than `criteria.epsilon` on some iteration, the algorithm\n% stops. default\n% `struct('type','Count+EPS', 'maxCount',100, 'epsilon',eps('float'))`\n% * __Attempts__ The number of times the algorithm is executed using different\n% initial labelings. The algorithm returns the labels that yield the best\n% compactness (see the last function parameter). default 10.\n% * __Initialization__ Method to initialize seeds. One of the followings:\n% * __Random__ Select random initial centers in each attempt. (default)\n% * __PP__ Use kmeans++ center initialization by Arthur and Vassilvitskii\n% [Arthur2007].\n% * __InitialLabels__ Integer array that stores the initial cluster indices\n% for every sample. During the first (and possibly the only) attempt, kmeans\n% uses the user-supplied labels instead of computing them from the initial\n% centers. For the second and further attempts, it uses the random or\n% semi-random centers. Use one of the `Initialization` methods to specify\n% the exact method. Not set by default.\n%\n% The function cv.kmeans implements a k-means algorithm that finds the centers\n% of `K` clusters and groups the input samples around the clusters. As an\n% output, `labels(i)` contains a 0-based cluster index for the sample stored\n% in the i-th row of the samples matrix.\n%\n% The function returns the compactness measure that is computed as:\n%\n% sum_{i} (|| samples_i - centers_{labels_i} ||^2)\n%\n% after every attempt. The best (minimum) value is chosen and the\n% corresponding labels and the compactness value are returned by the\n% function. Basically, you can use only the core of the function, set the\n% number of attempts to 1, initialize labels each time using a custom\n% algorithm, pass them with the `InitialLabels` option, and then choose the\n% best (most-compact) clustering.\n%\n% ## References\n% [Arthur2007]:\n% > D. Arthur, S. Vassilvitskii: \"k-means++: The Advantages of Careful Seeding\".\n% > In Proceedings of the eighteenth annual ACM-SIAM symposium\n% > on Discrete algorithms, 1027-1035, 2007.\n%\n% See also: kmeans\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/kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7833081738848562}} {"text": "function area = area_quad ( quad_xy )\n\n%*****************************************************************************80\n%\n%% AREA_QUAD returns the area of a quadrilateral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real QUAD_XY(2,4), the coordinates of the nodes.\n%\n% Output, real AREA, the area of the quadrilateral.\n%\n t1(1:2,1) = quad_xy(1:2,1);\n t1(1:2,2) = quad_xy(1:2,2);\n t1(1:2,3) = quad_xy(1:2,3);\n\n area1 = triangle_area ( t1 );\n\n t2(1:2,1) = quad_xy(1:2,3);\n t2(1:2,2) = quad_xy(1:2,4);\n t2(1:2,3) = quad_xy(1:2,1);\n\n area2 = triangle_area ( t2 );\n\n if ( area1 < 0.0 | area2 < 0.0 )\n\n t1(1:2,1) = quad_xy(1:2,2);\n t1(1:2,2) = quad_xy(1:2,3);\n t1(1:2,3) = quad_xy(1:2,4);\n\n area1 = triangle_area ( t1 );\n\n t2(1:2,1) = quad_xy(1:2,4);\n t2(1:2,2) = quad_xy(1:2,1);\n t2(1:2,3) = quad_xy(1:2,2);\n\n area2 = triangle_area ( t2 );\n\n if ( area1 < 0.0 | area2 < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'AREA_QUAD - Fatal error!\\n' );\n fprintf ( 1, ' The quadrilateral nodes seem to be listed in\\n' );\n fprintf ( 1, ' the wrong order, or the quadrilateral is\\n' );\n fprintf ( 1, ' degenerate.\\n' );\n error ( 'AREA_QUAD - Fatal error!' );\n end\n\n end\n\n area = area1 + area2;\n\n return\nend\n", "meta": {"author": "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/area_quad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7833081676644862}} {"text": "function [ Tree,Cost ] = UndirectedMaximumSpanningTree (CostMatrix)\n% The function takes CostMatrix as input and returns the maximum spanning tree T\n% Uses Kruskal's Algorithm\n% Extract the edge weights from the cost matrix\n% Sort the edges in a non decreasing order of weights \n% This algorithm is revised by Lowell Guangdi at 2009/06/11.\n\nn = size (CostMatrix,1); %Number of vertices\nEdgeWeights = 0; %Edges and corresponding weights\nEdgeWeightsCounter = 0;\nfor i = 1:n\n for j = (i+1):n\n if ((CostMatrix(i,j))~=0)\n EdgeWeightsCounter = EdgeWeightsCounter + 1;\n EdgeWeights(EdgeWeightsCounter,1) = CostMatrix(i,j);\n EdgeWeights(EdgeWeightsCounter,2) = i;\n EdgeWeights(EdgeWeightsCounter,3) = j;\n end\n end\nend\n\nSortedEdgeWeights = 0;\nSortedEdgeWeights = sortrows(EdgeWeights);\n% First column of SortedEdgeWeights are the weights\n% Second and third column are the vertices that the edges connect\nm = size(SortedEdgeWeights,1); % number of edges \n\n% We use the Disjoint sets data structures to detect cycle while adding new\n% edges. Union by Rank with path compression is implemented here.\n\n% Assign parent pointers to each vertex. Initially each vertex points to \n% itself. Now we have a conceptual forest of n trees representing n disjoint \n% sets \nglobal ParentPointer ;\nParentPointer = 0;\nParentPointer(1:n) = 1:n;\n\n% Assign a rank to each vertex (root of each tree). Initially all vertices \n% have the rank zero.\nTreeRank = 0;\nTreeRank(1:n) = 0;\n\n% Visit each edge in the sorted edges array\n% If the two end vertices of the edge are in different sets (no cycle), add\n% the edge to the set of edges in maximum spanning tree\nMSTreeEdges = 0;\nMSTreeEdgesCounter = 0; i = m;\nwhile ((MSTreeEdgesCounter < (n-1)) && (i>=1))\n%Find the roots of the trees that the selected edge's two vertices\n%belong to. Also perform path compression.\n root1=0; root2=0; temproot=0;\n temproot = SortedEdgeWeights(i,2);\n root1 = FIND_PathCompression(temproot);\n \n temproot = SortedEdgeWeights(i,3);\n root2 = FIND_PathCompression(temproot);\n \n if (root1 ~= root2)\n MSTreeEdgesCounter = MSTreeEdgesCounter + 1;\n MSTreeEdges(MSTreeEdgesCounter,1:3) = SortedEdgeWeights(i,:);\n if (TreeRank(root1)>TreeRank(root2))\n ParentPointer(root2)=root1;\n else\n if (TreeRank(root1)==TreeRank(root2))\n TreeRank(root2)=TreeRank(root2) + 1;\n end\n ParentPointer(root1)=root2;\n end\n end\n i = i - 1;\nend\n\nMSTreeEdgesCounter = 0;\nTree = 0;\nTree(1:n,1:n)=0;\nwhile (MSTreeEdgesCounter < (n-1))\n MSTreeEdgesCounter = MSTreeEdgesCounter + 1;\n Tree(MSTreeEdges(MSTreeEdgesCounter,2),MSTreeEdges(MSTreeEdgesCounter,3))=1;\n Tree(MSTreeEdges(MSTreeEdgesCounter,3),MSTreeEdges(MSTreeEdgesCounter,2))=1;\nend\n%T\n\nCost = 0;\nfor p = 1:n\n for q = p+1:n\n if Tree( p,q ) == 1 \n Cost = Cost + CostMatrix( p,q );\n end\n end\nend\n\nend\n\nfunction [parent] = FIND_PathCompression(temproot)\n\nglobal ParentPointer;\nParentPointer(temproot);\nif (ParentPointer(temproot)~=temproot)\n ParentPointer(temproot) = FIND_PathCompression(ParentPointer(temproot));\nend\nparent = ParentPointer(temproot);\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/23276-maximum-weight-spanning-tree-undirected/MaximumSpanningTree/UndirectedMaximumSpanningTree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7833081636212348}} {"text": "function value = tetrahedron_unit_monomial ( expon )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_UNIT_MONOMIAL integrates a monomial over the unit tetrahedron.\n%\n% Discussion:\n%\n% This routine integrates a monomial of the form\n%\n% product ( 1 <= dim <= 3 ) x(dim)^expon(dim)\n%\n% where the exponents are nonnegative integers. Note that\n% if the combination 0^0 is encountered, it should be treated\n% as 1.\n%\n% Integral ( over unit tetrahedron ) x^l y^m z^n dx dy =\n% l% * m% * n% / ( m + n + 3 )%\n%\n% The integration region is defined as:\n%\n% 0 <= X\n% 0 <= Y\n% 0 <= Z\n% 0 <= X + Y + Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer EXPON(3), the exponents.\n%\n% Output, real VALUE, the integral of the monomial.\n%\n\n%\n% The first computation ends with VALUE = 1.0;\n%\n value = 1.0;\n%\n% The first loop simply calculates 1, so we short circuit it.\n%\n% k = 0;\n%\n% for i = 1 : expon(1)\n% k = k + 1;\n% value = value * i / k;\n% end\n\n k = expon(1);\n for i = 1 : expon(2)\n k = k + 1;\n value = value * i / k;\n end\n\n for i = 1 : expon(3)\n k = k + 1;\n value = value * i / k;\n end\n\n k = k + 1;\n value = value / k;\n\n k = k + 1;\n value = value / k;\n\n k = k + 1;\n value = value / k;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tetrahedron_felippa_rule/tetrahedron_unit_monomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.783283628042025}} {"text": "function H = ent_g(x, biascorrect)\n% ENT_G Entropy of a Gaussian variable in bits\n% H = ent_g(x) returns the entropy of a (possibly \n% multidimensional) Gaussian variable x with bias correction.\n% Rows of x correspond to samples, columns to dimensions/variables. \n% (Samples first axis)\n%\n% biascorrect : true / false option (default true) which specifies\n% whether bias correction should be applied to the estimated entropy.\n\nif isvector(x)\n x = x(:);\nend\nif ndims(x)~=2\n error('ent_g: input arrays should be 2d')\nend\n[Ntrl, Nvarx] = size(x);\n\nif nargin < 2\n % default is to apply bias correction\n biascorrect = true;\nend\n\n% demean data\ngx.m = sum(x,1)/Ntrl;\nx = bsxfun(@minus,x,gx.m);\n\n% covariance\nC = (x'*x) / (Ntrl - 1);\nchC = chol(C);\n\n% entropy in nats\nHX = sum(log(diag(chC))) + 0.5*Nvarx*(log(2*pi)+1);\n\nln2 = log(2);\nif biascorrect\n psiterms = psi((Ntrl - (1:Nvarx))/2) / 2;\n dterm = (ln2 - log(Ntrl-1)) / 2;\n HX = (HX - Nvarx*dterm - sum(psiterms));\nend\n\n% convert to bits\nH = HX / ln2;\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/ent_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922389, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7832529146772893}} {"text": "function [J, grad] = lrCostFunction(theta, X, y, lambda)\n %% LRCOSTFUNCTION Compute cost and gradient for logistic regression with \n %regularization\n % J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using\n % theta as the parameter for regularized logistic regression and the\n % gradient of the cost w.r.t. to the parameters. \n \n n = length(y); % number of training examples\n \n % cost: J, this time with the penalty for the magnitude of theta\n J = -1/n * sum(...\n y .* log(sigmoid(X * theta)) + ...\n (1 - y) .* log(1 - sigmoid(X * theta)) ...\n ) + lambda / (2 * n) * sum(theta(2:end) .* theta(2:end));\n\n % gradient: compute as the derivative of the cost function\n grad = 1/n * X' * ((sigmoid(X * theta)) - y) + theta * lambda / n;\n \n % we do not regularize the constant offset term, \n % undo the gradient penalization for the constant x_0 term\n grad(1) = grad(1) - lambda / n * theta(1);\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/1-multiclass/lrCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7832110859746696}} {"text": "function e = imEntropy(img, varargin)\n%IMENTROPY Compute entropy of an image\n%\n% H = imEntropy(IMG)\n% Computes the entropy of the image IMG.\n% The entropy is computed as:\n% H = -sum(P .* log2(P));\n% where P is the density probability that image takes a given value.\n%\n% Note that the computation of the entropy depends on the way the\n% histogram is computed. This should not be a concern for uint8 images,\n% but can give results inconsistent with imMutualInformation for double\n% images.\n%\n% H = imEntropy(IMG, N)\n% H = imEntropy(IMG, BINS)\n% Computes the histogram using N bins, or the bins specified by BINS. \n%\n%\n% Example\n% % compute entropy on a sample image\n% img = imread('rice.png');\n% H = imEntropy(img)\n% H =\n% 7.0115\n% \n% % entropy is independent of pixel ordering\n% img2 = circshift(img, [30 40]);\n% H = imEntropy(img2)\n% H =\n% 7.0115\n%\n% % entropy computed on an histogram with fewer bins\n% imEntropy(img, 16)\n% ans =\n% 3.1158\n%\n% See also\n% imJointEntropy, imMutualInformation, imHistogram\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-08-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% first compute histogram\nh = imHistogram(img, varargin{:});\n\n% keep only positive values, and normalize by 1 to have density\nh(h==0) = [];\nh = h / sum(h);\n\n% compute entropy\ne = -sum(h .* log2(h));\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7831883874394382}} {"text": "function [d, xd, bw] = kernelDensity(x, bins, h, kernel)\n%KERNELDENSITY Calculate the kernel density of a data set\n% \n% [D, XD] = IOSR.STATISTICS.KERNELDENSITY(X) calculate the kernel density\n% D of a dataset X for query points XD. The kernel density is calculated\n% for 100 query points equally spaced between the minimum and maximum of\n% the data X. The density is estimated using a gaussian kernel with a\n% width that is optimal for normal data. X may be a vector, matrix, or\n% multi-dimensional array; the entire array is treated as the sample. D\n% and XD are 100-point column vectors. NaN are excluded from the\n% calculations.\n% \n% ... = IOSR.STATISTICS.KERNELDENSITY(X, BINS) calculates the density for\n% the query points specified by BINS. If BINS is a scalar, then BINS\n% points are queried between MIN(X(:)) and MAX(X(:)); if BINS is a\n% vector, then the values are used as the query points directly. D and XD\n% are column vectors.\n% \n% ... = IOSR.STATISTICS.KERNELDENSITY(X, BINS, H) uses the bandwidth H to\n% calculate the kernel density. H must be a scalar. BINS may be an empty\n% array in order to use the default described above.\n% \n% ... = IOSR.STATISTICS.KERNELDENSITY(X, BINS, [], KERNEL) uses the\n% kernel function specified by KERNEL to calculate the density. The\n% kernel may be:\n% - 'normal' (default),\n% - 'uniform',\n% - 'triangular',\n% - 'epanechnikov',\n% - 'quartic',\n% - 'triweight',\n% - 'tricube',\n% - 'cosine',\n% - 'logistic',\n% - 'sigmoid', or\n% - 'silverman'.\n% For the uniform case the bandwidth is set to 15% of the range of the\n% data [1]. Otherwise the bandwidth is chosen to be optimal for normal\n% data assuming a gaussian kernel.\n% \n% ... = IOSR.STATISTICS.KERNELDENSITY(X, BINS, H, KERNEL) allows the\n% bins BINS and bandwidth H to be specified directly.\n% \n% [D, XD, BW] = IOSR.STATISTICS.KERNELDENSITY(...) returns the badwidth\n% BW.\n% \n% Examples\n% \n% Example 1: Plot the kernel density of gaussian data\n% figure\n% % gaussian random numbers\n% y = randn(100000, 1);\n% % density\n% [d, xd] = iosr.statistics.kernelDensity(y);\n% % plot\n% plot(xd, d);\n% \n% Example 2: Density trace with 200 bins of width of 10% of data range\n% figure\n% % random numbers\n% y = randn(100000, 1);\n% % y range\n% range = max(y(:)) - min(y(:));\n% % density trace\n% [d, xd] = iosr.statistics.kernelDensity(y, 200, 0.1*range, 'uniform');\n% % plot\n% plot(xd, d);\n% \n% References\n% \n% [1] Hintze, Jerry L.; Nelson, Ray D. (1998). \"Violin Plots: A Box\n% Plot-Density Trace Synergism\". The American Statistician. 52 (2):\n% 181?4. \n\n %% input check\n\n x = x(:);\n x = x(~isnan(x));\n assert(numel(x) > 1, 'X must be a vector, matrix, or array.')\n \n % x bins\n if nargin < 2\n bins = [];\n end\n if isempty(bins)\n bins = 100;\n end\n if isscalar(bins)\n bins = linspace(min(x), max(x), round(bins));\n end\n bins = bins(:);\n \n % bin width\n if nargin < 3\n h = [];\n end\n \n % kernel\n if nargin < 4\n kernel = [];\n end\n if isempty(kernel)\n kernel = 'normal';\n end\n % return kernel function\n switch lower(kernel)\n case 'uniform'\n K = @(u) 0.5*(abs(u) <= 1);\n if isempty(h)\n h = 0.15 * (max(x) - min(x));\n end\n case 'normal'\n K = @(u) ((1/sqrt(2*pi)) * exp(-0.5*(u.^2)));\n case 'triangular'\n K = @(u) ((1-abs(u)) .* (abs(u) <= 1));\n case 'epanechnikov'\n K = @(u) ((0.75*(1-(u.^2))) .* (abs(u) <= 1));\n case 'quartic'\n K = @(u) (((15/16)*(1-(u.^2)).^2) .* (abs(u) <= 1));\n case 'triweight'\n K = @(u) (((35/32)*(1-(u.^2)).^3) .* (abs(u) <= 1));\n case 'tricube'\n K = @(u) (((70/81)*(1-(abs(u).^3)).^3) .* (abs(u) <= 1));\n case 'cosine'\n K = @(u) (((pi/4)*cos((pi/2)*u)) .* (abs(u) <= 1));\n case 'logistic'\n K = @(u) (1 / (exp(u) + 2 + exp(-u)));\n case 'sigmoid'\n K = @(u) ((2/pi) * (1 / (exp(u) + exp(-u))));\n case 'silverman'\n K = @(u) (0.5 * exp((-abs(u))/(sqrt(2))) .* sin((abs(u))/(sqrt(2)) + (pi/4)));\n otherwise\n error('Unknown kernel specified');\n end\n if isempty(h)\n h = ((4*(std(x).^5))/(3*numel(x))).^(1/5);\n end\n \n assert(isscalar(h), 'h must be a scalar')\n \n %% calculate kernel density\n\n xd = sort(bins);\n d = zeros(size(xd));\n \n for i = 1:numel(xd)\n d(i) = sum(K((x-xd(i))/h))./(numel(x)*h);\n end\n d(isnan(d)) = 0;\n bw = h;\n\nend", "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/+statistics/kernelDensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.7831883817970355}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters. \n% You should set p to a vector of 0's and 1's\n%\n\nh_theta = sigmoid(X*theta);\np = ceil(2*h_theta)-1;\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7831883801044303}} {"text": "function y = sinc(x, c)\n%SINC The function SIN(PI*X)/(PI*X).\n%\n% SINC(X) returns the SIN(PI*X)/(PI*X) function which is defined as\n%\n% 1 if x = 0\n% sin(pi*x)/(pi*x) if 0 < |x| < infinity\n% 0 if |x| = infinity\n%\n% SINC(X, C) returns the SIN(C*X)/(C*X) function, where C > 0, which is a\n% generalization of the above and is defined as\n%\n% 1 if x = 0\n% sin(c*x)/(c*x) if 0 < |x| < infinity\n% 0 if |x| = infinity\n%\n% See also SIN.\n\n% Author: Peter J. Acklam\n% Time-stamp: 2003-10-20 08:45:14 +0200\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n nargsin = nargin;\n\n % check number of input arguments\n error(nargchk(1, 2, narsgin));\n\n if nargsin < 2\n c = pi;\n else\n if any(size(c) ~= 0) | (c <= 0)\n error('Second argument must be a positive scalar.');\n end\n end\n\n y = ones(size(x)); % initialize output\n i = x ~= 0; % find non-zero elements\n t = c * x(i); % precompute C*X\n y(i) = sin(t) ./ t; % compute SIN(C*X)/(C*X)\n y(isinf(x)) = 0; % 0 not NaN when X = +/-Inf\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/sinc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7831883751663108}} {"text": "function line_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% LINE_MONTE_CARLO_TEST01 estimates integrals in 1D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_MONTE_CARLO_TEST01\\n' );\n fprintf ( 1, ' Use LINE01_SAMPLE to estimate integrals\\n' );\n fprintf ( 1, ' along the length of the unit line in 1D.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N' );\n fprintf ( 1, ' 1' );\n fprintf ( 1, ' X' ); \n fprintf ( 1, ' X^2' );\n fprintf ( 1, ' X^3' ); \n fprintf ( 1, ' X^4' ); \n fprintf ( 1, ' X^5' );\n fprintf ( 1, ' X^6\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = line01_sample ( n, seed );\n\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e = j - 1;\n\n value = monomial_value_1d ( n, e, x );\n\n result = line01_length ( ) * sum ( value(1:n) ) / n;\n\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * n;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact' );\n\n for j = 1 : 7\n\n e = j - 1;\n\n result = line01_monomial_integral ( e );\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/line_monte_carlo/line_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.7831883696647646}} {"text": "function b = isPointInEllipse(point, ellipse, varargin)\n%ISPOINTINELLIPSE Check if a point is located inside a given ellipse\n%\n% B = isPointInEllipse(POINT, ELLIPSE) \n% Returns true if point is located inside the given ellipse.\n%\n% B = isPointInEllipse(POINT, ELLIPSE, TOL) \n% Specifies the tolerance value\n%\n% Example:\n% isPointInEllipse([1 0], [0 0 2 1 0])\n% ans =\n% 1\n% isPointInEllipse([0 0], [0 0 2 1 0])\n% ans =\n% 1\n% isPointInEllipse([1 1], [0 0 2 1 0])\n% ans =\n% 0\n% isPointInEllipse([1 1], [0 0 2 1 30])\n% ans =\n% 1\n%\n% See also:\n% ellipses2d, isPointInCircle\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 11/03/2011\n%\n\n% HISTORY\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% compute ellipse to unit circle transform\nrot = createRotation(-deg2rad(ellipse(5)));\nsca = createScaling(1./ellipse(3:4));\ntrans = sca * rot;\n\n% transform points to unit circle basis\npTrans = bsxfun(@minus, point, ellipse(:,1:2));\npTrans = transformPoint(pTrans, trans);\n\n% test if distance to origin smaller than 1\nb = sqrt(sum(power(pTrans, 2), 2)) - 1 <= tol;\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/isPointInEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.7831883674075708}} {"text": "function [ area, radin, side ] = polygon_outrad_data_2d ( n, radout )\n\n%*****************************************************************************80\n%\n%% POLYGON_OUTRAD_DATA_2D determines polygonal data from its outer radius in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sides of the polygon.\n% N must be at least 3.\n%\n% Input, real RADOUT, the outer radius of the polygon, that is,\n% the radius of the smallest circle that can be described\n% around the polygon.\n%\n% Output, real AREA, the area of the regular polygon.\n%\n% Output, real RADIN, the inner radius of the polygon, that is,\n% the radius of the largest circle that can be inscribed\n% within the polygon.\n%\n% Output, real SIDE, the length of one side of the polygon.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_OUTRAD_DATA_2D - Fatal error!\\n' );\n fprintf ( 1, ' Input value of N must be at least 3.\\n' );\n fprintf ( 1, ' but your input value was N = %d\\n', n );\n error ( 'POLYGON_OUTRAD_DATA_2D - Fatal error!' );\n end\n\n angle = pi / n;\n area = 0.5 * n * radout * radout * sin ( 2.0 * angle );\n side = 2.0 * radout * sin ( angle );\n radin = 0.5 * side / tan ( angle );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_outrad_data_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8723473647220787, "lm_q1q2_score": 0.7831021128428041}} {"text": "function [v] = spm_mar_gen (w,A,C,n,ndisc)\n% Generate data from MAR model\n% FORMAT [v] = spm_mar_gen (w,A,C,n,ndisc)\n%\n% Generates n time steps of the MAR(p) process\n%\n% v(k,:)' = w' + A1*v(k-1,:)' +...+ Ap*v(k-p,:)' + eta(k,:)', \n%\n% where A=[A1 ... Ap] is the coefficient matrix, and w is a vector of\n% intercept terms that is included to allow for a nonzero mean of the\n% process. The vectors eta(k,:) are independent Gaussian noise\n% vectors with mean zero and covariance matrix C.\n%\n% This function is adapted from the ARFIT toolbox by Neumaier and\n% Schneider\n%___________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_mar_gen.m 1143 2008-02-07 19:33:33Z spm $\n\nm = size(C,1); % dimension of state vectors \np = size(A,2)/m; % order of process\n\nif (p ~= round(p)) \n error('Bad arguments.'); \nend\n\nif (length(w) ~= m | min(size(w)) ~= 1)\n error('Dimensions of arguments are mutually incompatible.')\nend \nw = w(:)'; % force w to be row vector\n\n% Discard the first ndisc time steps; if ndisc is not given as input\n% argument, use default\nif (nargin < 5) \n ndisc = 10^3; \nend\n\n% Compute Cholesky factor of covariance matrix C\nR = chol(C); % R is upper triangular\n\n% Get ndisc+n independent Gaussian pseudo-random vectors with \n% covariance matrix C=R'*R\nrandvec = randn([ndisc+n,m])*R;\n\n% Add intercept vector to random vectors\nrandvec = randvec + ones(ndisc+n,1)*w;\n\n% Get transpose of system matrix A (use transpose in simulation because \n% we want to obtain the states as row vectors)\nAT = A';\n\n% Take the p initial values of the simulation to equal the process mean, \n% which is calculated from the parameters A and w\nif any(w)\n % Process has nonzero mean mval = inv(B)*w' where \n % B = eye(m) - A1 -... - Ap; \n % Assemble B\n B = eye(m);\n for j=1:p\n B = B - A(:, (j-1)*m+1:j*m);\n end\n % Get mean value of process\n mval = w / B';\n \n % The optimal forecast of the next state given the p previous\n % states is stored in the vector x. The vector x is initialized\n % with the process mean.\n x = ones(p,1)*mval;\nelse\n % Process has zero mean\n x = zeros(p,m); \nend\n\n% Initialize state vectors\nu = [x; zeros(ndisc+n,m)];\n\n% Simulate n+ndisc observations. In order to make use of Matlab's\n% vectorization capabilities, the cases p=1 and p>1 must be treated \n% separately.\nif p==1\n for k=2:ndisc+n+1; \n x(1,:) = u(k-1,:)*AT;\n u(k,:) = x + randvec(k-1,:);\n end\nelse\n for k=p+1:ndisc+n+p; \n for j=1:p;\n x(j,:) = u(k-j,:)*AT((j-1)*m+1:j*m,:);\n end\n u(k,:) = sum(x)+randvec(k-p,:);\n end\nend\n\n% return only the last n simulated state vectors\nv = u(ndisc+p+1:ndisc+n+p,:); \n\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/spectral/spm_mar_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7830241898410757}} {"text": "function [ax_mps2] = calcPathAx(s_m, v_mps)\n%_________________________________________________________________\n%% Documentation \n%\n% Authors: Alexander Wischnewski (alexander.wischnewski@tum.de)\n% \n% Start Date: 08.02.2018\n% \n% Description: calculates the acceleration profile corresponding to a \n% velocity profile for a given path length. Constant\n% acceleration is assumed between the discretization points. \n% \n% Inputs:\n% s_m Vector with path length values\n% v_mps Vector with velocity at these path points \n%\n% Outputs: \n% ax_mps2 Vector with accelerations valid from the current to the\n% next point. \n\n% initialize variables\nax_mps2 = zeros(length(v_mps), 1); \n% calculate acceleration based on the assumption that it is constant\n% between two discretization points. Last point can't be calculated as no\n% further velocity information is available for the point behind. \ndS = diff(s_m); \ndV = diff(v_mps); \nax_mps2(1:(end-1)) = (dV.^2 + 2.*dV.*v_mps(1:(end-1)))./(2.*dS); \n% copy last point which could be calculated, as no better information is\n% available \nax_mps2(end) = ax_mps2(end-1); ", "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/control/src/calcPathAx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7830241812541275}} {"text": "function phi=pt2MaxEntropyCoords(x,v,algorithm,maxIter,epsScal)\n%%PT2MAXENTROPYCOORDS Convert a point in a polygon to maximum entropy\n% coordinates. This is a type of barycentric coordinate system in 2D\n% that applies to points in polygons and is described in Section 7 of\n% [1]. These coordinates can be useful for Barycentric mapping and\n% for interpolation.\n%\n%INPUTS: x The 2XnumPts set of points to convert into maximum entropy\n% coordinates.\n% v The 2XnumBases set of vertices of the polygon defining the\n% coordinate system. The vertices can be given in clockwise or\n% counterclockwise order. It is assumed that the first vertex is\n% not repeated at the end.\n% algorithm An optional parameter specifying the edge weight function to\n% use. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) Use the \n% edge weight of Hormann and Sukumar, which is the first one\n% given in [1].\n% 1 Use the second edge weight given in [1].\n% maxIter The maximum number of iterations of Newton's method to use. The\n% default if omitted or an empty matrix is passed is 100 and\n% generally, far fewer iterations are actually needed.\n% epsScal Convergence is determined when\n% abs(stepSize)<=epsScal*eps(lambda), where lambda is the 2X1\n% vector parameter being estimated from which the weights phi are\n% derived in [1]. The default if omitted or an empty matrix is\n% passed is 1.\n%\n%OUTPUTS: phi A numBasesXnumPts set of the maximum entropy coordinates of\n% the points given in x. Note that sum(phi(:,k))=1 for any k.\n% Points on the edge and outside of the polygon will typically\n% return a vector of NaNs.\n%\n%EXAMPLE 1:\n%In this example, the coordinates of two points are found and the points\n%are recreated from the phi values. The residual error of the reverse\n%conversion is seen to be on the order of finite precision errors.\n% numVertices=5;\n% v=zeros(2,numVertices);\n% v(:,1)=[-2;3];\n% v(:,2)=[11;0];\n% v(:,3)=[9;10];\n% v(:,4)=[7;11];\n% v(:,5)=[0;10];\n% x=[[6;5],[8;2]];\n% phi=pt2MaxEntropyCoords(x,v);\n% xBack=barycentricCoords2Pt(phi,v);\n% ResidualErr=max(max(abs(xBack-x)))\n%\n%EXAMPLE 2:\n%This draws a convex polygon and a set of horizontal and vertical lines in\n%the polygon. Then, the points of the lines are converted to maximum\n%entropy coordinates and the vertices of the polygon are moved. After\n%conversion back to Cartesian coordinates, one can see how the original\n%grid in the polygon has been warped.\n% numVertices=5;\n% v=zeros(2,numVertices);\n% v(:,1)=[-2;3];\n% v(:,2)=[11;0];\n% v(:,3)=[9;10];\n% v(:,4)=[7;11];\n% v(:,5)=[0;10];\n% \n% vertLines=-1:1:10;\n% numVertLines=length(vertLines);\n% horizLines=1:10;\n% numHorizLines=length(horizLines);\n% numLinPts=99;\n% xVert=zeros(2,numLinPts,numVertLines);\n% xHoriz=zeros(2,numLinPts,numHorizLines);\n% for k=1:numVertLines\n% xVert(1,:,k)=vertLines(k);\n% xVert(2,:,k)=linspace(0,11,numLinPts);\n% sel=pointIsInPolygon(v,xVert(:,:,k),false)==0;\n% xVert(:,sel,k)=NaN;\n% end\n% for k=1:numHorizLines\n% xHoriz(1,:,k)=linspace(-2,11,numLinPts);\n% xHoriz(2,:,k)=horizLines(k);\n% sel=pointIsInPolygon(v,xHoriz(:,:,k),false)==0;\n% xHoriz(:,sel,k)=NaN;\n% end\n% \n% figure(1)\n% clf\n% hold on\n% plot([v(1,:),v(1,1)],[v(2,:),v(2,1)],'-c','linewidth',2)\n% axis([-2, 12, 0, 12])\n% for k=1:numVertLines\n% plot(xVert(1,:,k),xVert(2,:,k),'-r')\n% end\n% for k=1:numHorizLines\n% plot(xHoriz(1,:,k),xHoriz(2,:,k),'-b')\n% end\n% phiVert=pt2MaxEntropyCoords(xVert(:,:),v);\n% phiHoriz=pt2MaxEntropyCoords(xHoriz(:,:),v);\n% \n% %Move the vertices, but keep the shape convex and the vertices still in\n% %counterclockwise order.\n% v(:,1)=[3;2];\n% v(:,2)=[8;0];\n% v(:,3)=[10;10];\n% v(:,4)=[9;11];\n% v(:,5)=[3;10];\n% \n% figure(2)\n% clf\n% hold on\n% plot([v(1,:),v(1,1)],[v(2,:),v(2,1)],'-c','linewidth',2)\n% axis([-2, 12, 0, 12])\n% %Synthesize the corresponding points in the transformed coordinate\n% %system.\n% xTransVert=reshape(barycentricCoords2Pt(phiVert,v),[2,numLinPts,numVertLines]);\n% xTransHoriz=reshape(barycentricCoords2Pt(phiHoriz,v),[2,numLinPts,numHorizLines]);\n% for k=1:numVertLines\n% plot(xTransVert(1,:,k),xTransVert(2,:,k),'-r')\n% end\n% for k=1:numHorizLines\n% plot(xTransHoriz(1,:,k),xTransHoriz(2,:,k),'-b')\n% end\n%\n%REFERENCES:\n%[1] M. S. Floater, \"Generalized barycentric coordinates and applications,\"\n% Acta Numerica, vol. 24, pp. 161-214, 1 May 2015.\n%\n%September 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(epsScal))\n epsScal=1;\nend\n\nif(nargin<4||isempty(maxIter))\n maxIter=100;\nend\n\nif(nargin<3||isempty(algorithm))\n algorithm=0;\nend\n\nnumPts=size(x,2);\nnumBases=size(v,2);\nphi=zeros(numBases,numPts);\nfor curPt=1:numPts\n if(any(isnan(x(:,curPt))))\n phi(:,curPt)=NaN;\n continue;\n end\n\n diffs=bsxfun(@minus,x(:,curPt),v);\n mags=sqrt(sum(diffs.*diffs,1));\n\n rhoVals=zeros(numBases,1);\n if(algorithm==0)\n for k=1:(numBases-1)\n rhoVals(k)=mags(k)+mags(k+1)-norm(v(:,k)-v(:,k+1));\n end\n rhoVals(numBases)=mags(numBases)+mags(1)-norm(v(:,numBases)-v(:,1));\n elseif(algorithm==1)\n for k=1:(numBases-1)\n rhoVals(k)=mags(k)*mags(k+1)+dot(diffs(:,k),diffs(:,k+1));\n end\n rhoVals(numBases)=mags(numBases)*mags(1)+dot(diffs(:,numBases),diffs(:,1));\n else\n error('Unknown algorithm specified.') \n end\n\n piVals=zeros(1,numBases);\n piVals(1)=prod(rhoVals(2:(numBases-1)));\n for k=2:(numBases-1)\n piVals(k)=prod(rhoVals([1:(k-2),(k+1):numBases]));\n end\n piVals(numBases)=prod(rhoVals(1:(numBases-2)));\n\n mi=piVals/sum(piVals);\n d=-diffs;\n\n %lambda can start uniform. \n lambda=[1/2;1/2];\n %Use Newton's method.\n for curIter=1:maxIter\n [F,H]=getFAndH(lambda,d,mi);\n \n if(any(~isfinite(H(:))))\n lambda=[NaN;NaN];\n break;\n end\n \n stepVal=pinv(H)*F;\n \n if(all(abs(stepVal)<=epsScal*eps(lambda)))\n %Convergence to some multiple of finite precision limits.\n break; \n end\n lambda=lambda-stepVal;\n end\n\n wi=mi.*exp(sum(bsxfun(@times,lambda,d),1));\n phi(:,curPt)=wi/sum(wi);\nend\nend\n\nfunction [gradF,H]=getFAndH(lambda,d,mi)\n%%GETFANDH Get the the gradient and the Hessian of the cost function.\n\nmExpdTerms=bsxfun(@times,mi.*exp(sum(bsxfun(@times,lambda,d),1)),d);\n\n%The gradient.\ngradF=sum(mExpdTerms,2);\nH=zeros(2,2);\nH(1,1)=sum(mExpdTerms(1,:).*d(1,:));\nH(2,1)=sum(mExpdTerms(1,:).*d(2,:));\nH(1,2)=H(2,1);\nH(2,2)=sum(mExpdTerms(2,:).*d(2,:));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Barycentric_Coordinate_Systems/pt2MaxEntropyCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.783019031388243}} {"text": "function [C, L, U] = SpectralClustering(W, k, Type)\n%SPECTRALCLUSTERING Executes spectral clustering algorithm\n% Executes the spectral clustering algorithm defined by\n% Type on the adjacency matrix W and returns the k cluster\n% indicator vectors as columns in C.\n% If L and U are also called, the (normalized) Laplacian and\n% eigenvectors will also be returned.\n%\n% 'W' - Adjacency matrix, needs to be square\n% 'k' - Number of clusters to look for\n% 'Type' - Defines the type of spectral clustering algorithm\n% that should be used. Choices are:\n% 1 - Unnormalized\n% 2 - Normalized according to Shi and Malik (2000)\n% 3 - Normalized according to Jordan and Weiss (2002)\n%\n% References:\n% - Ulrike von Luxburg, \"A Tutorial on Spectral Clustering\", \n% Statistics and Computing 17 (4), 2007\n%\n% Author: Ingo Buerk\n% Year : 2011/2012\n% Bachelor Thesis\n\n% calculate degree matrix\ndegs = sum(W, 2);\nD = sparse(1:size(W, 1), 1:size(W, 2), degs);\n\n% compute unnormalized Laplacian\nL = D - W;\n\n% compute normalized Laplacian if needed\nswitch Type\n case 2\n % avoid dividing by zero\n degs(degs == 0) = eps;\n % calculate inverse of D\n D = spdiags(1./degs, 0, size(D, 1), size(D, 2));\n \n % calculate normalized Laplacian\n L = D * L;\n case 3\n % avoid dividing by zero\n degs(degs == 0) = eps;\n % calculate D^(-1/2)\n D = spdiags(1./(degs.^0.5), 0, size(D, 1), size(D, 2));\n \n % calculate normalized Laplacian\n L = D * L * D;\nend\n\n% compute the eigenvectors corresponding to the k smallest\n% eigenvalues\ndiff = eps;\n[U, ~] = eigs(L, k, diff);\n\n% in case of the Jordan-Weiss algorithm, we need to normalize\n% the eigenvectors row-wise\nif Type == 3\n U = bsxfun(@rdivide, U, sqrt(sum(U.^2, 2)));\nend\n\n% now use the k-means algorithm to cluster U row-wise\n% C will be a n-by-1 matrix containing the cluster number for\n% each data point\nC = kmeans(U, k, 'start', 'sample', ...\n 'EmptyAction', 'singleton');\n \n% now convert C to a n-by-k matrix containing the k indicator\n% vectors as columns\nC = sparse(1:size(D, 1), C, 1);\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/SpectralClustering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7830127132722331}} {"text": "%% Efficient subpixel image registration by cross-correlation. \n% Registers two images (2-D rigid translation) within a fraction \n% of a pixel specified by the user. Instead of computing a zero-padded FFT \n% (fast Fourier transform), this code uses selective upsampling by a\n% matrix-multiply DFT (discrete FT) to dramatically reduce computation time and memory\n% without sacrificing accuracy. With this procedure all the image points are used to\n% compute the upsampled cross-correlation in a very small neighborhood around its peak. This \n% algorithm is referred to as the single-step DFT algorithm in [1].\n%\n% [1] Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, \n% \"Efficient subpixel image registration algorithms,\" Opt. Lett. 33, \n% 156-158 (2008).\n%\n% ----------------------------------------------------------------------- \n%\n% Copyright (c) 2016, Manuel Guizar Sicairos, James R. Fienup, University of Rochester\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% * Neither the name of the University of Rochester nor the names\n% of its contributors may be used to endorse or promote products derived\n% from this software without specific prior written permission.\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%% Syntax\n% The code receives the FFT of the reference and the shifted images, and an\n% (integer) upsampling factor. The code expects FFTs with DC in (1,1) so do not use\n% fftshift.\n%\n% output = dftregistration(fft2(f),fft2(g),usfac);\n%\n% The images are registered to within 1/usfac of a pixel.\n%\n% output(1) is the normalized root-mean-squared error (NRMSE) [1] between f and\n% g. \n%\n% output(2) is the global phase difference between the two images (should be\n% zero if images are real-valued and non-negative).\n%\n% output(3) and output(4) are the row and column shifts between f and g respectively. \n%\n% [output Greg] = dftregistration(fft2(f),fft2(g),usfac);\n%\n% Greg is an optional output, it returns the Fourier transform of the registered version of g,\n% where the global phase difference [output(2)] is also compensated.\n\n\n%% Obtain a reference and shifted images\n% To illustrate the use of the algorithm, lets obtain a reference and a\n% shifted image. First we read the reference image f(x,y)\nf = im2double(imread('cameraman.tif'));\n\n%%\n% Define g(x,y) as a version of f(x,y) shifted by fractional values of a\n% pixel and multiplied by a global phase. \ndeltar = -3.48574;\ndeltac = 8.73837;\nphase = 2;\n[nr,nc]=size(f);\nNr = ifftshift((-fix(nr/2):ceil(nr/2)-1));\nNc = ifftshift((-fix(nc/2):ceil(nc/2)-1));\n[Nc,Nr] = meshgrid(Nc,Nr);\ng = ifft2(fft2(f).*exp(1i*2*pi*(deltar*Nr/nr+deltac*Nc/nc))).*exp(-1i*phase);\nfigure(1);\nsubplot(1,2,1);\nimshow(abs(f));\ntitle('Reference image, f(x,y)')\nsubplot(1,2,2);\nimshow(abs(g));\ntitle('Shifted image, g(x,y)')\n%%\n% We have shifted the image by 8.73837 and -3.48574 pixels in the x and\n% y direction, respectively, and added a phase of 2 radians to g(x,y). The shift \n% was implemented by applying a linear phase on its\n% FT, thus we have assumed that the images wrap around (features leaving one \n% side of the window reappear on the opposite side) and that the image is band-limited\n% (interpolated by a sinc function). Cross-correlation image registration by DFTs \n% (both the matrix-multiply DFT and the zero-padded FFT) share these assumptions. \n%\n% This registration technique is well suited to compare images that are captured\n% in Fourier domain (i.e. to evaluate an image reconstruction by holography\n% or phase retrieval) which are strictly band-limited and exhibit the\n% wrap-around effect.\n%\n% Even though the registration code assumes band-limited images that wrap around, we \n% have obtained very good results when applying it to\n% band-limited microscope images, and aliased imagery. That is when shifting \n% the image brings in new content instead of wrapping it around or when the\n% images are not band-limited.\n\n%% Sample Image Registration\n% dftregistration.m receives the FT of f and g and the upsampling factor. \n% The code expects DC of the FTs at (1,1) so don't use fftshift. \n%\n% We now use the image registration code to register f and g within 0.01\n% pixels by specifying an upsampling parameter of 100\nusfac = 100;\n[output, Greg] = dftregistration(fft2(f),fft2(g),usfac);\ndisplay(output),\n\n%% \n% The pixel shift error (difference between the true and obtained shifts)\n% is 0.0016 and 0.0043 in the x and y directions respectively. Well within\n% the expected accuracy of 0.01. Notice that using the conventional zero-padded \n% FFT approach with the same accuracy, would\n% require computation of a 25,600x25,600 FFT, which would require more than\n% 19 Gbytes of RAM and a very comfortable chair.\n%\n% The following plot shows the reference image and the registered image.\nfigure(1);\nsubplot(1,2,1);\nimshow(abs(f));\ntitle('Reference image, f(x,y)')\nsubplot(1,2,2);\nimshow(abs(ifft2(Greg)));\ntitle('Registered image, gr(x,y)')\n%% Disclaimer\n% I have made every effort to evaluate the proper working of this code\n% under many different conditions. However, it is the responsibility of\n% the user to ensure that this registration code is adequate and working \n% correcntly for their application.\n%\n% Feel free to e-mail me with questions or comments. \n", "meta": {"author": "AbdoKamel", "repo": "sidd-ground-truth-image-estimation", "sha": "ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2", "save_path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation", "path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation/sidd-ground-truth-image-estimation-ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2/efficient_subpixel_registration/efficient_subpixel_registration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7829662328470564}} {"text": "function lambda = minij_eigenvalues ( n )\n\n%*****************************************************************************80\n%\n%% MINIJ_EIGENVALUES returns the eigenvalues of the MINIJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n for i = 1 : n\n angle = ( 2 * i - 1 ) * pi / ( 2 * n + 1 );\n lambda(i,1) = 0.5 / ( 1.0 - cos ( angle ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/minij_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7828161517637843}} {"text": "function [rho,theta,R]=findTrigMomentFromSamp(n,x,w)\n%%FINDTRIGMOMENTFROMSAMPLE Given a set of samples of a circular\n% distribution, determine a particular trigonometric sample\n% moment.\n%\n%INPUTS: n The order of the moment desired. This is >=1.\n% x The 1XN or NX1 vector of possibly weighted samples.\n% w The NX1 weights associated with the samples. If this parameter\n% is omitted or an empty matrix is passed, then the samples are\n% uniformly weighted.\n%\n%OUTPUTS: rho The (complex) mean resultant value for the nth moment. Note\n% that rho=R*exp(1j*theta).\n% theta The (real) trigonometric mean angle in radians for the nth\n% moment. This is between -pi and pi.\n% R The (real) mean resultant length for the nth moment.\n%\n%An expression for the complex trigonometric moments is given in Equation\n%14 of [1]. This is just a weighted version of the definition in Chapter\n%2.4 of [2].\n%\n%REFERENCES:\n%[1] G. Kurz, I. Gilitschenski, R. Y. Siegwart, and U. D. Hanebeck,\n% \"Methods for deterministic approximation of circular densities,\"\n% Journal of Advances in Information Fusion, vol. 11, no. 2, pp.\n% 138-156, Dec. 2016.\n%[2] K. V. Mardia and P. E. Jupp, Directional Statistics. Chichester: John\n% Wiley and Sons, 2000.\n%\n%April 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=length(x);\nif(nargin<3||isempty(w))\n w=ones(N,1);\nend\n\n%Normalize.\nw=w/sum(w);\n\nrho=sum(exp(1i*n*x(:)).*w(:));\nif(nargout>1)\n theta=angle(rho);\n R=abs(rho);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/findTrigMomentFromSamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7828161479638145}} {"text": "function f = fxy5 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% FXY5 is the fourth 2D example.\n%\n% Discussion:\n%\n% This is example 3.1 in the reference.\n%\n% It is known as the discontinuous medium wave function.\n%\n% Here, we are computing the second component of the solution, U(X,Y).\n%\n% It should be plotted on (x,y) in [-1,0]x[0,0.1].\n%\n% The second variable y actually represents time.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Rick Archibald, Anne Gelb, Jungho Yoon,\n% Determining the locations and discontinuities in the derivatives\n% of functions,\n% Applied Numerical Mathematics,\n% Volume 58, 2008, pages 577-592.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), Y(N), the arguments.\n%\n% Output, real F(N,1), the function values.\n%\n\n%\n% Destroy all row vectors!\n%\n x = x ( : );\n y = y ( : );\n\n cl = 0.87879;\n cr = 1.0;\n omega = 12.0;\n rhol = 0.55556;\n rhor = 1.0;\n\n f = zeros ( n, 1 );\n\n i = find ( x(1:n) <= -0.5 );\n j = find ( -0.5 < x(1:n) );\n \n f(i) = sin ( pi * omega * ( y(i) - ( x(i) + 0.5 ) / cl ) ) ...\n + ( rhol * cl - rhor * cr ) / ( rhol * cl + rhor * cr ) ...\n / ( rhol * cl ) ...\n * sin ( pi * omega * ( y(i) + ( x(i) + 0.5 ) / cl ) );\n\n f(j) = 2.0 / ( rhol * cl + rhor * cr ) ...\n * sin ( pi * omega * ( y(j) - ( x(j) + 0.5 ) / cl ) );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/edge/fxy5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8615382040983516, "lm_q1q2_score": 0.7828090375308339}} {"text": "function [ l, u ] = l1nn_lu ( n, h )\n\n%*****************************************************************************80\n%\n%% L1NN_LU computes the LU factors of the 1D NN Laplacian.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n% N must be at least 3.\n%\n% Input, real H, the spacing between points.\n%\n% Output, real L(N,N), U(N,n), the LU factors.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'L1NN_LU - Fatal error!\\n' );\n fprintf ( 1, ' N < 3.\\n' );\n error ( 'L1NN_LU - Fatal error!' );\n end\n\n l = zeros ( n, n );\n\n for i = 1 : n\n l(i,i) = 1.0;\n end\n\n for i = 2 : n\n l(i,i-1) = - 1.0;\n end\n\n u = zeros ( n, n );\n\n for i = 1 : n - 1\n u(i,i) = 1.0;\n end\n u(n,n) = 0.0;\n\n for i = 1 : n - 1\n u(i,i+1) = - 1.0;\n end\n\n u(1:n,1:n) = u(1:n,1:n) / h / h;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laplacian/l1nn_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7827726072933298}} {"text": "function [X maxdot] = packing_on_the_sphere(d, n, epsilon, X0)\n% Return a set of points spread out on the sphere.\n%\n% function [X maxdot] = packing_on_the_sphere(d, n, epsilon, X0)\n%\n% Using optimization on the oblique manifold, that is, the product of\n% spheres, this function returns a set of n points with unit norm in R^d in\n% the form of a matrix X of size nxd, such that the points are spread out\n% on the sphere. Ideally, we would minimize the maximum inner product\n% between any two points X(i, :) and X(j, :), i~=j, but that is a nonsmooth\n% cost function. Instead, we replace the max function by a classical\n% log-sum-exp approximation and (attempt to) solve:\n%\n% min_{X in OB(d, n)} log( .5*sum_{i~=j} exp( xi'*xj/epsilon ) ),\n%\n% with xi = X(:, i) and epsilon is some \"diffusion constant\". As epsilon\n% goes to zero, the cost function is a sharper approximation of the max\n% function (under some assumptions), but the cost function becomes stiffer\n% and hence harder to optimize.\n%\n% The second output, maxdot, is the maximum inner product between any two\n% points in the returned X. This number is the one we truly are trying to\n% minimize.\n%\n% Notice that this cost function is invariant under rotation of X:\n% f(X) = f(XQ) for all orthogonal Q in O(d).\n% This calls for optimization over the set of symmetric positive\n% semidefinite matrices of size n and rank d with unit diagonal, which can\n% be thought of as the quotient of the oblique manifold OB(d, n) by O(d):\n% See elliptopefactory.\n%\n% This is known as the Thomson or, more specifically, the Tammes problem:\n% http://en.wikipedia.org/wiki/Tammes_problem\n% An interesting page by Neil Sloane collecting best known packings is\n% available here http://neilsloane.com/packings/\n\n% This file is part of Manopt and is copyrighted. See the license file.\n%\n% Main author: Nicolas Boumal, July 2, 2013\n% Contributors:\n%\n% Change log:\n% Aug. 14, 2013 (NB) : Code now compatible to experiment with both the\n% obliquefactory and the elliptopefactory.\n%\n% Jan. 7, 2014 (NB) : Added reference to Neil Sloane's page and the\n% maxdot output.\n%\n% June 24, 2014 (NB) : Now shifting exponentials to alleviate numerical\n% trouble when epsilon is too small.\n% \n \n if ~exist('d', 'var') || isempty(d)\n % Dimension of the embedding space: R^d\n d = 3;\n end\n if ~exist('n', 'var') || isempty(n)\n % Number n of points to place of the sphere in R^d.\n % For example, n=12 yields an icosahedron:\n % https://en.wikipedia.org/wiki/Icosahedron\n % Notice though that platonic solids are not always optimal.\n % Try for example n = 8: you don't get a cube.\n n = 24;\n end\n if ~exist('epsilon', 'var') || isempty(epsilon)\n % This value should be as close to 0 as affordable.\n % If it is too close to zero, optimization first becomes much\n % slower, than simply doesn't work anymore becomes of floating\n % point overflow errors (NaN's and Inf's start to appear).\n % If it is too large, then log-sum-exp is a poor approximation of\n % the max function, and the spread will be less uniform.\n % An okay value seems to be 0.01 or 0.001 for example. Note that a\n % better strategy than using a small epsilon straightaway is to\n % reduce epsilon bit by bit and to warm-start subsequent\n % optimization in that way. Trustregions will be more appropriate\n % for these fine tunings.\n epsilon = 0.0015;\n end\n \n % Pick your manifold (the elliptope factory quotients out the global\n % rotation invariance of the problem, which is more natural but\n % conceptually a bit more complicated --- for usage with the toolbox it\n % is the same though: just uncomment the appropriate line).\n manifold = obliquefactory(d, n, true);\n % manifold = elliptopefactory(n, d);\n \n % Generate a random initial guess if none was given.\n if ~exist('X0', 'var') || isempty(X0)\n X0 = manifold.rand();\n end\n\n % Define the cost function with caching system used: the store\n % structure we receive as input is tied to the input point X. Everytime\n % this cost function is called at this point X, we will receive the\n % same store structure back. We may modify the store structure inside\n % the function and return it: the changes will be remembered for next\n % time.\n function [f store] = cost(X, store)\n if ~isfield(store, 'ready')\n XXt = X*X';\n % Shift the exponentials by the maximum value to reduce\n % numerical trouble due to possible overflows.\n s = max(max(triu(XXt, 1)));\n expXXt = exp((XXt-s)/epsilon);\n % Zero out the diagonal\n expXXt(1:(n+1):end) = 0;\n u = sum(sum(triu(expXXt, 1)));\n store.XXt = XXt;\n store.s = s;\n store.expXXt = expXXt;\n store.u = u;\n store.ready = true;\n end\n u = store.u;\n s = store.s;\n f = s + epsilon*log(u);\n end\n\n % Define the gradient of the cost. When the gradient is called at a\n % point X for which the cost was already called, the store structure we\n % receive remember everything that the cost function stored in it, so\n % we can reuse previously computed elements.\n function [g store] = grad(X, store)\n if ~isfield(store, 'ready')\n [~, store] = cost(X, store);\n end\n % Compute the Euclidean gradient\n eg = store.expXXt*X / store.u;\n % Convert to the Riemannian gradient (by projection)\n g = manifold.egrad2rgrad(X, eg);\n end\n\n % Setup the problem structure with its manifold M and cost+grad\n % functions.\n problem.M = manifold;\n problem.cost = @cost;\n problem.grad = @grad;\n\n % For debugging, it's always nice to check the gradient a few times.\n % checkgradient(problem);\n % pause;\n \n % Call a solver on our problem with a few options defined. We did not\n % specify the Hessian but it is still okay to call trustregion: Manopt\n % will approximate the Hessian with finite differences of the gradient.\n opts.tolgradnorm = 1e-8;\n opts.maxtime = 1200;\n opts.maxiter = 1e5;\n % X = trustregions(problem, X0, opts);\n X = conjugategradient(problem, X0, opts);\n \n % Evaluate the maximum inner product between any two points of X.\n XXt = X*X';\n dots = XXt(find(triu(ones(n), 1))); %#ok\n maxdot = max(dots);\n \n % Similarly, even though we did not specify the Hessian, we may still\n % estimate its spectrum at the solution. It should reflect the\n % invariance of the cost function under a global rotatioon of the\n % sphere, which is an invariance under the group O(d) of dimension\n % d(d-1)/2 : this translates into d(d-1)/2 zero eigenvalues in the\n % spectrum of the Hessian.\n % The approximate Hessian is not a linear operator, and is it a\n % fortiori not symmetric. The result of this computation is thus not\n % reliable. It does display the zero eigenvalues as expected though.\n if manifold.dim() < 300\n evs = real(hessianspectrum(problem, X));\n figure;\n stem(1:length(evs), sort(evs), '.');\n title(['Eigenvalues of the approximate Hessian of the cost ' ...\n 'function at the solution']);\n end\n \n \n % Show how the inner products X(:, i)'*X(:, j) are distributed.\n figure;\n hist(real(acos(dots)), 20);\n title('Histogram of the geodesic distances');\n \n % This is the quantity we actually want to minimize.\n fprintf('Maximum inner product between two points: %g\\n', maxdot);\n \n \n % Give some visualization if the dimension allows\n if d == 2\n % For the circle, the optimal solution consists in spreading the\n % points with angles uniformly sampled in (0, 2pi). This\n % corresponds to the following value for the max inner product:\n fprintf('Optimal value for the max inner product: %g\\n', cos(2*pi/n));\n figure;\n t = linspace(-pi, pi, 201);\n plot(cos(t), sin(t), '-', 'LineWidth', 3, 'Color', [152,186,220]/255);\n daspect([1 1 1]);\n box off;\n axis off;\n hold on;\n plot(X(:, 1), X(:, 2), 'r.', 'MarkerSize', 25);\n hold off;\n end\n if d == 3\n figure;\n % Plot the sphere\n [sphere_x sphere_y sphere_z] = sphere(50);\n handle = surf(sphere_x, sphere_y, sphere_z);\n set(handle, 'FaceColor', [152,186,220]/255);\n set(handle, 'FaceAlpha', .5);\n set(handle, 'EdgeColor', [152,186,220]/255);\n set(handle, 'EdgeAlpha', .5);\n daspect([1 1 1]);\n box off;\n axis off;\n hold on;\n % Add the chosen points\n Y = 1.02*X';\n plot3(Y(1, :), Y(2, :), Y(3, :), 'r.', 'MarkerSize', 25);\n % And connect the points which are at minimal distance,\n % within some tolerance.\n min_distance = real(acos(maxdot));\n connected = real(acos(XXt)) <= 1.20*min_distance;\n [Ic Jc] = find(triu(connected, 1));\n for k = 1 : length(Ic)\n i = Ic(k); j = Jc(k);\n plot3(Y(1, [i j]), Y(2, [i j]), Y(3, [i j]), 'k-');\n end\n hold off;\n end\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/examples/packing_on_the_sphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7827254353059011}} {"text": "function [ x, w ] = cce ( l )\n\n%*****************************************************************************80\n%\n%% CCE computes a Clenshaw Curtis Exponential quadrature rule based on level.\n%\n% Discussion:\n%\n% Our convention is that the abscissas are numbered from left to right.\n%\n% The rule is defined on [0,1].\n%\n% The integral to approximate:\n%\n% Integral ( 0 <= X <= 1 ) F(X) dX\n%\n% The quadrature rule:\n%\n% Sum ( 1 <= I <= N ) W(I) * F ( X(I) )\n%\n% The input value of L selects the size of the rule as follows:\n% L = 1, N = 1;\n% 1 < L, N = 2^(L-1)+1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer L, the level of the rule.\n% 1 <= L.\n%\n% Output, real X(N,1), the abscissas.\n%\n% Output, real W(N,1), the weights.\n%\n if ( l < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CCE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of L = %d\\n', l );\n error ( 'CCE - Fatal error!' );\n end\n%\n% Find the value of N according to the level.\n%\n n = cce_order ( l );\n%\n% Compute the points and weights.\n%\n [ x, w ] = cc ( n );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/cce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7827254333491238}} {"text": "%IMMOMENTS PRTools routine for computing central moments of object images\n%\n%\t M = IMMOMENTS(A,TYPE,MOMENTS)\n%\n% INPUT\n% A Dataset with object images dataset\n% TYPE Desired type of moments\n% MOMENTS Desired moments\n%\n% OUTPUT\n% M Dataset with moments replacing images\n%\n% DESCRIPTION\n% Computes for the image A a (1*N) vector M moments as defined by TYPE\n% and MOMENTS. The following types are supported:\n%\n% TYPE = 'none' Standard moments as specified in the Nx2 array MOMENTS.\n% Moments are computed with respect to the image center.\n% This is the default for TYPE.\n% Default MOMENTS = [1 0; 0 1];\n% TYPE = 'central' Central moments as specified in the Nx2 array MOMENTS.\n% Moments are computed with respect to the image mean\n% Default MOMENTS = [2 0; 1 1; 0 2], which computes\n% the variance in the x-direction (horizontal), the\n% covariance between x and y and the variance in the\n% y-direction (vertical).\n% TYPE = 'scaled' Scale-invariant moments as specified in the Nx2 array\n% MOMENTS. Default MOMENTS = [2 0; 1 1; 0 2].\n% After: M. Sonka et al.,\n% Image processing, analysis and machine vision.\n% TYPE = 'hu' Calculates 7 moments of Hu, invariant to translation,\n% rotation and scale.\n% After: M. Sonka et al.,\n% Image processing, analysis and machine vision.\n% TYPE = 'zer' Calculates the Zernike moments up to the order as \n% specified in the scalar MOMENTS (1 <= MOMENTS <= 12). \n% MOMENTS = 12 generates in total 47 moments.\n% After: A. Khotanzad and Y.H. Hong, Invariant image\n% recognition by Zernike moments, IEEE-PAMI, vol. 12,\n% no. 5, 1990, 489-497.\n%\n% See DATASETS\n\n% Copyright: D. de Ridder, 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 = immoments(a,type,mom)\n\n\tif nargin < 3, mom = []; end\n\tif nargin < 2 | isempty(type), type = 'none'; end\n\tisobjim(a);\n\t[m,k] = size(a);\n\tim = data2im(a);\n\tfor i = 1:m\n\t\timi = im(:,:,i);\n\t\tswitch type\n\t\tcase {'none'}\n\t\t\tif isempty(mom)\n\t\t\t\tmom = [1 0; 0 1];\n\t\t\tend\n\t\t\tmout = moments(imi,mom(:,1),mom(:,2),0,0);\n\t\tcase {'central'}\n\t\t\tif isempty(mom)\n\t\t\t\tmom = [2 0; 1 1; 0 2];\n\t\t\tend\n\t\t\tmout = moments(imi,mom(:,1),mom(:,2),1,0);\t\t\n\t\tcase {'scaled'}\n\t\t\tif isempty(mom)\n\t\t\t\tmom = [2 0; 1 1; 0 2];\n\t\t\tend\n\t\t\tmout = moments(imi,mom(:,1)',mom(:,2)',1,1);\t\t\n\t\tcase {'hu' 'Hu'}\n\t\t\tmout = hu_moments(imi);\n\t\tcase {'zer' 'zernike' 'Zernike'}\n\t\t\tif isempty(mom)\n\t\t\t\tmom = 12;\n\t\t\tend\n\t\t\tmout = zernike_moments(imi,mom);\n\t\totherwise\n\t\t\terror('Moments should be of type none, central, scaled, hu or zer')\n\t\tend\n\t\tif i==1\n\t\t\tb = zeros(m,length(mout));\n\t\tend\n\t\tb(i,:) = mout;\n\tend\n\tb = setdata(a,b);\n\t\t\n% M = MOMENTS (IM, P, Q, CENTRAL, SCALED)\n%\n% Calculates moments of order (P+Q) (can be arrays of indentical length)\n% on image IM. If CENTRAL is set to 1 (default: 0), returns translation-\n% invariant moments; if SCALED is set to 1 (default: 0), returns scale-\n% invariant moments.\n%\n% After: M. Sonka et al., Image processing, analysis and machine vision.\n\nfunction m = moments (im,p,q,central,scaled)\n\n\tif (nargin < 5), scaled = 0; \tend;\n\tif (nargin < 4), central = 0; end;\n if (nargin < 3)\n \terror ('Insufficient number of parameters.');\n end;\n \n\tif (length(p) ~= length(q))\n \terror ('Arrays P and Q should have equal length.');\n end;\n \n if (scaled & ~central)\n \terror ('Scale-invariant moments should always be central.');\n end;\n\n % xx, yy are grids with co-ordinates\n [xs,ys] = size(im);\n [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2);\n \n\tif (central)\n \n \t% Calculate zeroth and first order moments\n\t m00 = sum(sum(im));\n\t m10 = sum(sum(im.*xx));\n\t m01 = sum(sum(im.*yy));\n \n % This gives the center of gravity\n xc = m10/m00;\n yc = m01/m00;\n \n % Subtract this from the grids to center the object\n xx = xx - xc;\n yy = yy - yc;\n \n end;\n \n % Calculate moment(s) (p,q).\n for i = 1:length(p)\n\t\tm(i) = sum(sum((xx.^p(i)).*(yy.^q(i)).*im));\n end;\n \n if (scaled)\n \n \tc = 1 + (p+q)/2;\n \n % m00 should be known, as scaled moments are always central\n m = m ./ (m00.^c);\n \n\tend;\n\t \nreturn;\n\n% M = HU_MOMENTS (IM)\n%\n% Calculates 7 moments of Hu on image IM, invariant to translation, \n% rotation and scale.\n%\n% After: M. Sonka et al., Image processing, analysis and machine vision.\n\nfunction m = hu_moments (im)\n\n\tp = [ 1 0 2 1 2 0 3 ];\n\tq = [ 1 2 0 2 1 3 0 ];\n\n n = moments(im,p,q,1,1);\n \n m(1) = n(2) + n(3);\n m(2) = (n(3) - n(2))^2 + 4*n(1)^2;\n m(3) = (n(7) - 3*n(4))^2 + (3*n(5) - n(6))^2;\n m(4) = (n(7) + n(4))^2 + ( n(5) + n(6))^2;\n m(5) = ( n(7) - 3*n(4)) * (n(7) + n(4)) * ...\n ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) + ...\n (3*n(5) - n(6)) * (n(5) + n(6)) * ...\n (3*(n(7) + n(4))^2 - (n(5) + n(6))^2);\n m(6) = (n(3) - n(2)) * ((n(7) + n(4))^2 - (n(5) + n(6))^2) + ...\n 4*n(1) * (n(7)+n(4)) * (n(5)+n(6)); \n m(7) = (3*n(5) - n(6)) * (n(7) + n(4)) * ...\n ( (n(7) + n(4))^2 - 3*(n(5) + n(6))^2) - ...\n ( n(7) - 3*n(4)) * (n(5) + n(6)) * ...\n (3*(n(7) + n(4))^2 - (n(5) + n(6))^2);\n \nreturn;\n\n% M = ZERNIKE_MOMENTS (IM, ORDER)\n%\n% Calculates Zernike moments up to and including ORDER (<= 12) on image IM.\n% Default: ORDER = 12.\n\nfunction m = zernike_moments (im, order)\n\n if (nargin < 2), order = 12; end;\n if (order < 1 | order > 12), error ('order should be 1..12'); end;\n\n % xx, yy are grids with co-ordinates\n\n [xs,ys] = size(im);\n [xx,yy] = meshgrid(-(ys-1)/2:1:(ys-1)/2,-(xs-1)/2:1:(xs-1)/2);\n\n % Calculate center of mass and distance of any pixel to it\n\n m = moments (im,[0 1 0],[0 0 1],0,0);\n xc = m(2)/m(1); yc = m(3)/m(1);\n xx = xx - xc; yy = yy - yc;\n\n len = sqrt(xx.^2+yy.^2);\n max_len = max(max(len));\n\n % Map pixels to unit circle; prevent divide by zero.\n\n rho = len/max_len;\n rho_tmp = rho; rho_tmp(find(rho==0)) = 1;\n theta = acos((xx/max_len)./rho_tmp);\n\n % Flip angle for pixels above center of mass\n\n yneg = length(find(yy(:,1)<0));\n theta(:,1:yneg) = 2*pi - theta(:,1:yneg);\n\n % Calculate coefficients\n\n c = zeros(order,order);\n s = zeros(order,order);\n\n i = 1;\n for n = 2:order\n for l = n:-2:0\n r = polynomial (n,l,rho);\n c = sum(sum(r.*cos(l*theta)))*((n+1)/(pi*max_len^2));\n s = sum(sum(r.*sin(l*theta)))*((n+1)/(pi*max_len^2));\n m(i) = sqrt(c^2+s^2);\n i = i + 1;\n end;\n end;\n\nreturn\n\nfunction p = polynomial (n,l,rho)\n\n switch (n)\n case 2, switch (l)\n case 0, p = 2*(rho.^2)-1;\n case 2, p = (rho.^2);\n end;\n case 3, switch (l)\n case 1, p = 3*(rho.^3)-2*rho;\n case 3, p = (rho.^3);\n end;\n case 4, switch (l)\n case 0, p = 6*(rho.^4)-6*(rho.^2)+1;\n case 2, p = 4*(rho.^4)-3*(rho.^2);\n case 4, p = (rho.^4);\n end;\n case 5, switch (l)\n case 1, p = 10*(rho.^5)-12*(rho.^3)+3*rho;\n case 3, p = 5*(rho.^5)- 4*(rho.^3);\n case 5, p = (rho.^5);\n end;\n case 6, switch (l)\n case 0, p = 20*(rho.^6)-30*(rho.^4)+12*(rho.^2)-1;\n case 2, p = 15*(rho.^6)-20*(rho.^4)+ 6*(rho.^2);\n case 4, p = 6*(rho.^6)- 5*(rho.^4);\n case 6, p = (rho.^6);\n end;\n case 7, switch (l)\n case 1, p = 35*(rho.^7)-60*(rho.^5)+30*(rho.^3)-4*rho;\n case 3, p = 21*(rho.^7)-30*(rho.^5)+10*(rho.^3);\n case 5, p = 7*(rho.^7)- 6*(rho.^5);\n case 7, p = (rho.^7);\n end;\n case 8, switch (l)\n case 0, p = 70*(rho.^8)-140*(rho.^6)+90*(rho.^4)-20*(rho.^2)+1;\n case 2, p = 56*(rho.^8)-105*(rho.^6)+60*(rho.^4)-10*(rho.^2);\n case 4, p = 28*(rho.^8)- 42*(rho.^6)+15*(rho.^4);\n case 6, p = 8*(rho.^8)- 7*(rho.^6);\n case 8, p = (rho.^8);\n end;\n case 9, switch (l)\n case 1, p = 126*(rho.^9)-280*(rho.^7)+210*(rho.^5)-60*(rho.^3)+5*rho;\n case 3, p = 84*(rho.^9)-168*(rho.^7)+105*(rho.^5)-20*(rho.^3);\n case 5, p = 36*(rho.^9)- 56*(rho.^7)+ 21*(rho.^5);\n case 7, p = 9*(rho.^9)- 8*(rho.^7);\n case 9, p = (rho.^9);\n end;\n case 10, switch (l)\n case 0, p = 252*(rho.^10)-630*(rho.^8)+560*(rho.^6)-210*(rho.^4)+30*(rho.^2)-1;\n case 2, p = 210*(rho.^10)-504*(rho.^8)+420*(rho.^6)-140*(rho.^4)+15*(rho.^2);\n case 4, p = 129*(rho.^10)-252*(rho.^8)+168*(rho.^6)- 35*(rho.^4);\n case 6, p = 45*(rho.^10)- 72*(rho.^8)+ 28*(rho.^6);\n case 8, p = 10*(rho.^10)- 9*(rho.^8);\n case 10, p = (rho.^10);\n end;\n case 11, switch (l)\n case 1, p = 462*(rho.^11)-1260*(rho.^9)+1260*(rho.^7)-560*(rho.^5)+105*(rho.^3)-6*rho;\n case 3, p = 330*(rho.^11)- 840*(rho.^9)+ 756*(rho.^7)-280*(rho.^5)+ 35*(rho.^3);\n case 5, p = 165*(rho.^11)- 360*(rho.^9)+ 252*(rho.^7)- 56*(rho.^5);\n case 7, p = 55*(rho.^11)- 90*(rho.^9)+ 36*(rho.^7);\n case 9, p = 11*(rho.^11)- 10*(rho.^9);\n case 11, p = (rho.^11);\n end;\n case 12, switch (l)\n case 0, p = 924*(rho.^12)-2772*(rho.^10)+3150*(rho.^8)-1680*(rho.^6)+420*(rho.^4)-42*(rho.^2)+1;\n case 2, p = 792*(rho.^12)-2310*(rho.^10)+2520*(rho.^8)-1260*(rho.^6)+280*(rho.^4)-21*(rho.^2);\n case 4, p = 495*(rho.^12)-1320*(rho.^10)+1260*(rho.^8)- 504*(rho.^6)+ 70*(rho.^4);\n case 6, p = 220*(rho.^12)- 495*(rho.^10)+ 360*(rho.^8)- 84*(rho.^6);\n case 8, p = 66*(rho.^12)- 110*(rho.^10)+ 45*(rho.^8);\n case 10, p = 12*(rho.^12)- 11*(rho.^10);\n case 12, p = (rho.^12);\n end;\n end;\n\nreturn\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/immoments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7827254258741331}} {"text": "function [uHessMat,uTriMat,Q,Z]=HessenbergTriangRed(A,B)\n%%HESSENBERGTRIANGRED Perform a Hessenberg triangular reduction of the nXn\n% matrices A and B. This finds Q and Z such that Q'*A*Z= an\n% upper Hessenberg matrix and Q'*B*Z is an upper triangular\n% matrix.\n%\n%INPUTS: A, B Two real nXn matrices.\n%\n%OUTPUTS: uHessMat The upper Hessenberg matrix obtained from Q'*A*Z.\n% uTriMat The upper triangular matrix obtained with Q'*B*Z.\n%\n%This function implements algorithm 7.7.1 in [1].\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%September 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(A,1);\n\nif(nargout>2)\n Z=eye(n,n);\n %B=Q*R. Replace B with Q'*B and A with Q'*A\n [Q,R]=qr(B);\n B=R;%Q'*B=R.\n A=Q'*A;\n\n for j=1:(n-2)\n for i=n:-1:(j+2)\n %Zeros A(i,j)\n [c,s]=GivensCS(A(i-1,j),A(i,j));\n rotMat=[c, s;\n -s, c];\n A((i-1):i,j:n)=rotMat'*A((i-1):i,j:n);\n B((i-1):i,(i-1):n)=rotMat'*B((i-1):i,(i-1):n);\n\n Q(:,(i-1):i) = Q(:,(i-1):i)*rotMat;\n\n %Zeros B(i,i-1).\n [c,s]=GivensCS(-B(i,i),B(i,i-1));\n rotMat=[c, s;\n -s, c];\n B(1:i,(i-1):i) = B(1:i,(i-1):i)*rotMat;\n A(1:n,(i-1):i) = A(1:n,(i-1):i)*rotMat;\n\n Z(:,(i-1):i) = Z(:,(i-1):i)*rotMat;\n end\n end\n uHessMat=A;\n uTriMat=B;\nelse\n %If Q and Z are not desired, don't compute them.\n \n %B=Q*R. Replace B with Q'*B and A with Q'*A\n [Q,R]=qr(B);\n B=R;%Q'*B=R.\n A=Q'*A;\n for j=1:(n-2)\n for i=n:-1:(j+2)\n %Zeros A(i,j)\n [c,s]=GivensCS(A(i-1,j),A(i,j));\n rotMat=[c, s;\n -s, c];\n A((i-1):i,j:n)=rotMat'*A((i-1):i,j:n);\n B((i-1):i,(i-1):n)=rotMat'*B((i-1):i,(i-1):n);\n\n %Zeros B(i,i-1).\n [c,s]=GivensCS(-B(i,i),B(i,i-1));\n rotMat=[c, s;\n -s, c];\n B(1:i,(i-1):i) = B(1:i,(i-1):i)*rotMat;\n A(1:n,(i-1):i) = A(1:n,(i-1):i)*rotMat;\n end\n end\n uHessMat=A;\n uTriMat=B;\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/HessenbergTriangRed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.782691284920604}} {"text": "function [f] = betad(z)\n%BETAD Dirichlet Beta function\n%\n%usage: f = betad(z)\n%\n%tested on version 5.3.1\n%\n% This program calculates the Dirichlet Beta function\n% for the elements of Z using the Dirichlet deta function.\n% Z may be complex and any size.\n%\n% Note: this is NOT the beta function defined by\n% Gamma(x)*Gamma(y)/Gamma(x+y)\n%\n% Has zeros for z=(-odd integers),\n% and infinite number of zeros for z=1/2+i*y\n%\n%\n%see also: Zeta, Deta, Eta, Lambda, Bern, Euler\n\n%Paul Godfrey\n%pgodfrey@conexant.com\n%3-24-01\n\nf=deta(z,2);\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/978-special-functions-math-library/betad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7826680345747322}} {"text": "function euler = qua2euler(qin)\n% qua2euler: transforms quaternion to Euler angles.\n%\n% INPUT\n% qin: 4x1 quaternion.\n%\n% OUTPUT\n% euler: 3x1 Euler angles [roll pitch yaw] (rad, rad, rad).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.000000000\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n%\n%\t\tDr. Paolo Zoccarato's comments at\n% https://github.com/rodralez/NaveGo/pull/9\n%\n%\t\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: 005\n% Date: 2017/12/05\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\n% Quaternion format from Crassidis' book.\n\nDCMbn = qua2dcm(qin);\n\nphi = atan2( DCMbn(3,2), DCMbn(3,3) ); % roll\ntheta = asin (-DCMbn(3,1) ); % pitch\npsi = atan2( DCMbn(2,1), DCMbn(1,1) ); % yaw\n\neuler = [phi theta psi];\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/conversions/qua2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7826680345747321}} {"text": "function disk_integrals_test01 ( )\n\n%*****************************************************************************80\n%\n%% DISK_INTEGRALS_TEST01 uses DISK01_SAMPLE to estimate various integrals.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 2;\n n = 4192;\n test_num = 20;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01\\n' );\n fprintf ( 1, ' Estimate monomial integrals using Monte Carlo\\n' );\n fprintf ( 1, ' over the interior of the unit disk in 2D.\\n' );\n%\n% Get sample points.\n%\n seed = 123456789;\n [ x, seed ] = disk01_sample ( n, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of sample points used is %d\\n', n );\n%\n% Randomly choose X,Y exponents between 0 and 8.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' If any exponent is odd, the integral is zero.\\n' );\n fprintf ( 1, ' We will restrict this test to randomly chosen even exponents.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ex Ey MC-Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n\n [ e, seed ] = i4vec_uniform_ab ( m, 0, 4, seed );\n\n e(1:m) = e(1:m) * 2;\n\n value = monomial_value ( m, n, e, x );\n\n result = disk01_area ( ) * sum ( value(1:n) ) / n;\n exact = disk01_monomial_integral ( e );\n error = abs ( result - exact );\n\n fprintf ( 1, ' %2d %2d %14.6g %14.6g %10.2e\\n', ...\n e(1:m), result, exact, error );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/disk_integrals/disk_integrals_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7826586346379695}} {"text": "function p = sigmoid(log_odds)\n% SIGMOID: Inverse of the logit function.\n% This is a one-to-one mapping from log odds to probability. \n% i.e. it maps the real line to the interval (0,1).\n%\n% p = sigmoid(log_odds)\n\nassert(nargin==1)\n\np = 1 ./ (1 + exp(-log_odds));\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/maths/sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7825973295531917}} {"text": "function [qp]=zn3tr(input)\n% [qp]=zn3tr(input)\n% Ziegler-Nichols PID controller for processes of 3rd order.\n% This function computes parameters of the controller (q0, q1, q2, p1, p2).\n% Controller is based on trapezoidal method of discretization.\n% Transfer function of the controller is as follows:\n%\n% q0 + q1*z^-1 + q2*z^-2 q0 + q1*z^-1 + q2*z^-2\n% G(z^-1) = ------------------------ = ------------------------\n% 1 - z^-1 1 + p1*z^-1 + p2*z^-2\n%\n% where p1=-1 and p2=0.\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2 + b3*z^-3\n% Gs(z^-1) = ---------------------------------\n% 1 + a1*z^-1 + a2*z^-2 + a3*z^-3\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... a3\n% input(6) ... b3\n% input(7) ... sample time T0\n% Output: qp ... controller parameters \n% qp(1) ... q0\n% qp(2) ... q1\n% qp(3) ... q2\n% qp(4) ... p1 (-1)\n% qp(5) ... p2 (0)\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\na3 = input(5);\nb3 = input(6);\nT0 = input(7);\n\n% compute ultimate gain and frequency\n[Kpu, Tu] = ultim([b1 b2 b3],[a1 a2 a3],T0);\n\nKp = 0.6*Kpu;\nTi = Tu/2;\nTd = Tu/8;\n\nq0 = Kp*(1 + T0/(2*Ti) + Td/T0);\nq1 = -Kp*(1 - T0/(2*Ti) + 2*Td/T0);\nq2 = Kp*(Td/T0);\np1 = -1;\np2 = 0;\n\nqp=[q0; q1; q2; p1; 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/8381-stcsl-standard-version/zn3tr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7825626342784898}} {"text": "%ANGDIFF Difference of two angles\n%\n% D = ANGDIFF(TH1, TH2) returns the difference between angles TH1 and TH2 on\n% the circle. The result is in the interval [-pi pi). If TH1 is a column \n% vector, and TH2 a scalar then return a column vector where TH2 is modulo \n% subtracted from the corresponding elements of TH1.\n%\n% D = ANGDIFF(TH) returns the equivalent angle to TH in the interval [-pi pi).\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 .\n%\n% http://www.petercorke.com\n\nfunction d = angdiff(th1, th2)\n\n if nargin < 2\n% THIS IS A BAD IDEA, WHERE IS IT USED?\n% if length(th1) > 1\n% d = th1(1) - th1(2);\n% else\n% d = th1;\n% end\n d = th1;\n else\n d = th1 - th2;\n end\n\n \n d = mod(d+pi, 2*pi) - pi;\n\n% Simplistic version of the code, easy to see what it does, but slow...\n%\n% for very negative angles keep adding 2pi\n% while true\n% k = find(d < -pi);\n% if isempty(k)\n% break;\n% end\n% d(k) = d(k) + 2*pi;\n% end\n% \n% % for very positive angles keep subtracting 2pi\n% while true\n% k = find(d > pi);\n% if isempty(k)\n% break;\n% end\n% d(k) = d(k) - 2*pi;\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/angdiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.782543505144593}} {"text": "function prob_test039 ( )\n\n%*****************************************************************************80\n%\n%% TEST039 tests COSINE_MEAN, COSINE_SAMPLE, COSINE_VARIANCE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n nsample = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST039\\n' );\n fprintf ( 1, ' For the Cosine PDF:\\n' );\n fprintf ( 1, ' COSINE_MEAN computes the mean;\\n' );\n fprintf ( 1, ' COSINE_SAMPLE samples;\\n' );\n fprintf ( 1, ' COSINE_VARIANCE computes the variance.\\n' );\n\n a = 2.0;\n b = 1.0;\n\n check = cosine_check ( a, b );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST039 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n mean = cosine_mean ( a, b );\n variance = cosine_variance ( a, b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF parameter B = %14f\\n', b );\n fprintf ( 1, ' PDF mean = %14f\\n', mean );\n fprintf ( 1, ' PDF variance = %14f\\n', variance );\n \n for i = 1 : nsample\n [ x(i), seed ] = cosine_sample ( a, b, seed );\n end\n\n mean = r8vec_mean ( nsample, x );\n variance = r8vec_variance ( nsample, x );\n xmax = max ( x(1:nsample) );\n xmin = min ( x(1:nsample) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sample size = %6d\\n', nsample );\n fprintf ( 1, ' Sample mean = %14f\\n', mean );\n fprintf ( 1, ' Sample variance = %14f\\n', variance );\n fprintf ( 1, ' Sample maximum = %14f\\n', xmax );\n fprintf ( 1, ' Sample minimum = %14f\\n', xmin );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/prob_test039.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.782543489337151}} {"text": "%\n% y = nnormn(x,dim,p)\n%\n% NNORMN normalizes an array x by its p-vector norms along dimension .\n%\n% dim: dimension along which to calculate norm. Default first nonsingleton\n% p: norm-type. Default is 2.\n%\n% Equivalence: normc(x) == nnormn(x,1,2), normr(x) == nnormn(x,2,2)\n%\n% See also NORMC, NORMR, NNORM\n\n% Created by Bill Winter December 2005\n% Based on normc and normr\nfunction x = nnormn(x,dim,p)\nsiz = size(x);\nif nargin < 2, dim = find(siz > 1,1); end\nif nargin < 3, p = 2; end\nswitch p\n case inf, a = max(x,[],dim); % max\n case -inf, a = min(x,[],dim); % min\n case 1, a = sum(abs(x),dim); % manhattan\n case 2, a = sqrt(sum(abs(x).^2,dim)); % euclidean\n otherwise, a = sum(abs(x).^p,dim).^(1/p); % p-norm\nend\na(a == 0) = 1;\nN(1:length(siz)) = {':'};\nN{dim} = ones(1,siz(dim));\nx = x./a(N{:});", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11139-array-tool-set/array/nnormn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.782512477393649}} {"text": "function [X, W, mu_X] = prewhiten(X)\n%PREWHITEN Performs prewhitening of a dataset X\n%\n% [X, W, mu_X] = prewhiten(X)\n%\n% Performs prewhitening of the dataset X. Prewhitening concentrates the main\n% variance in the data in a relatively small number of dimensions, and \n% removes all first-order structure from the data. In other words, after\n% the prewhitening, the covariance matrix of the data is the identity\n% matrix. The function returns the subtracted data mean in mu_X, and the\n% applied linear mapping in W.\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 welcome;\n\n % Compute and apply the ZCA mapping\n mu_X = mean(X, 1);\n X = bsxfun(@minus, X, mu_X);\n mappedX = X / sqrtm(cov(X));\n if nargout > 1\n W = X \\ mappedX;\n end \n ", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/Demo_DFFN-master/drtoolbox/prewhiten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7825124763506301}} {"text": "function X=RiccatiSolveC(A,B,Q,R,S,E)\n%%RICCATISOLVEC Solve the general continuous-time Riccati equation.\n%\n%INPUTS: A An nXn matrix.\n% B An nXm matrix, where m<=n.\n% Q An nXn matrix such that Q=Q' and all eigenvalues are non-\n% negative.\n% R An optional mXm matrix such that R=R' and all eigenvalues are\n% non-negative. If omitted, eye(m,m) is used.\n% S An optional nXm matrix. If omitted, zeros(n,n) is used.\n% E An optional nXn matrix. If omitted, eye(n) is used.\n%\n%OUTPUTS: X The nXn nonnegative definite solution to the discrete-time\n% algebraic Ricatti equation.\n%\n%This function finds the nonnegative definite solution to the \n%continuous-time Ricatti equation having the form\n%A'*X*E+E'*X*A-(E'*X*B+S)*inv(R)*(B'*X*E+S')+Q=0\n%or, if R, S, and E are omitted, the equation under consideration becomes\n%A'*X+X*A-X*B*B'*X+Q=0\n%The algorithm of [1] is used. Note that this function does not work with\n%problems of the form -X*B*B'*X+Q=0 due to numerical issues.\n%\n%The continuous-time Ricatti equation arises when solving for the steady-\n%state covariance of a continuous-time linear Kalman filter, as described\n%in Chapter 9.2.3 of [2].\n%\n%REFERENCES:\n%[1] W. F. Arnold III and A. J. Laub, \"Generalized eigenproblem algorithms\n% and software for algebraic Riccati equations,\" Proceedings of the\n% IEEE, vol. 72, no. 12, pp. 1746-1754, Dec. 1984.\n%[2] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n% Applications to Tracking and Navigation. New York: John Wiley and\n% Sons, Inc, 2001.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(A,1);\nm=size(B,2);\n\nif(nargin<4)\n R=eye(m,m);\nend\n\nif(nargin<5)\n S=zeros(n,m);\nend\n\nif(nargin<6)\n E=eye(n); \nend\n\nL=[E, zeros(n,n),zeros(n,m);\n zeros(n,n), E', zeros(n,m);\n zeros(m,n), zeros(m,n),zeros(m,m)];\nM=[A, zeros(n,n), B;\n -Q, -A', -S;\n S', B', R];\n\n[MHat,LHat,V,U]=qz(M,L,'real');\n[~,~,~,U]=ordqz(MHat,LHat,V,U,'lhp');\n\nW=[E, zeros(n,n),zeros(n,m);\n zeros(n,n), eye(n),zeros(n,m)]*U;\n\nW11=W(1:n,1:n);\nW21=W((n+1):(2*n),1:n);\n\nX=W21/W11;\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\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/RiccatiSolveC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7825018191761336}} {"text": "function ray = bisector(varargin)\n%BISECTOR Return the bisector of two lines, or 3 points\n%\n% RAY = bisector(LINE1, LINE2);\n% create the bisector of the two lines, given as [x0 y0 dx dy].\n%\n% RAY = bisector(P1, P2, P3);\n% create the bisector of lines (P2 P1) and (P2 P3).\n%\n% The result has the form [x0 y0 dx dy], with [x0 y0] being the origin\n% point ans [dx dy] being the direction vector, normalized to have unit\n% norm.\n% \n% See also:\n% lines2d, rays2d\n%\n% ---------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% created the 31/10/2003.\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2005-07-07 add bisector of 3 points\n% 2010-11-05 ode cleanup\n\nif length(varargin)==2\n % two lines\n line1 = varargin{1};\n line2 = varargin{2};\n \n point = intersectLines(line1, line2); \n \nelseif length(varargin)==3\n % three points\n p1 = varargin{1};\n p2 = varargin{2};\n p3 = varargin{3};\n\n line1 = createLine(p2, p1);\n line2 = createLine(p2, p3);\n point = p2;\n \nelseif length(varargin)==1\n % three points, given in one array\n var = varargin{1};\n p1 = var(1, :);\n p2 = var(2, :);\n p3 = var(3, :);\n\n line1 = createLine(p2, p1);\n line2 = createLine(p2, p3);\n point = p2;\nend\n\n% compute line angles\na1 = lineAngle(line1);\na2 = lineAngle(line2);\n\n% compute bisector angle (angle of first line + half angle between lines)\nangle = mod(a1 + mod(a2-a1+2*pi, 2*pi)/2, pi*2);\n\n% create the resulting ray\nray = [point cos(angle) sin(angle)];\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/bisector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7822776830899455}} {"text": "% DERIVEST demo script\n\n% This script file is designed to be used in cell mode\n% from the matlab editor, or best of all, use the publish\n% to HTML feature from the matlab editor. Older versions\n% of matlab can copy and paste entire blocks of code into\n% the Matlab command window.\n\n% DERIVEST is property/value is driven for its arguments.\n% Properties can be shortened to the\n\n%% derivative of exp(x), at x == 0\n[deriv,err] = derivest(@(x) exp(x),0)\n\n%% DERIVEST can also use an inline function\n[deriv,err] = derivest(inline('exp(x)'),0)\n\n%% Higher order derivatives (second derivative)\n% Truth: 0\n[deriv,err] = derivest(@(x) sin(x),pi,'deriv',2)\n\n%% Higher order derivatives (third derivative)\n% Truth: 1\n[deriv,err] = derivest(@(x) cos(x),pi/2,'der',3)\n\n%% Higher order derivatives (up to the fourth derivative)\n% Truth: sqrt(2)/2 = 0.707106781186548\n[deriv,err] = derivest(@(x) sin(x),pi/4,'d',4)\n\n%% Evaluate the indicated (default = first) derivative at multiple points\n[deriv,err] = derivest(@(x) sin(x),linspace(0,2*pi,13))\n\n%% Specify the step size (default stepsize = 0.1)\nderiv = derivest(@(x) polyval(1:5,x),1,'deriv',4,'FixedStep',1)\n\n%% Provide other parameters via an anonymous function\n% At a minimizer of a function, its derivative should be\n% essentially zero. So, first, find a local minima of a\n% first kind bessel function of order nu.\nnu = 0;\nfun = @(t) besselj(nu,t);\nfplot(fun,[0,10])\nx0 = fminbnd(fun,0,10,optimset('TolX',1.e-15))\nhold on\nplot(x0,fun(x0),'ro')\nhold off\n\nderiv = derivest(fun,x0,'d',1)\n\n%% The second derivative should be positive at a minimizer.\nderiv = derivest(fun,x0,'d',2)\n\n%% Compute the numerical gradient vector of a 2-d function\n% Note: the gradient at this point should be [4 6]\nfun = @(x,y) x.^2 + y.^2;\nxy = [2 3];\ngradvec = [derivest(@(x) fun(x,xy(2)),xy(1),'d',1), ...\n derivest(@(y) fun(xy(1),y),xy(2),'d',1)]\n\n%% Compute the numerical Laplacian function of a 2-d function\n% Note: The Laplacian of this function should be everywhere == 4\nfun = @(x,y) x.^2 + y.^2;\nxy = [2 3];\nlapval = derivest(@(x) fun(x,xy(2)),xy(1),'d',2) + ...\n derivest(@(y) fun(xy(1),y),xy(2),'d',2)\n\n%% Compute the derivative of a function using a central difference scheme\n% Sometimes you may not want your function to be evaluated\n% above or below a given point. A 'central' difference scheme will\n% look in both directions equally.\n[deriv,err] = derivest(@(x) sinh(x),0,'Style','central')\n\n%% Compute the derivative of a function using a forward difference scheme\n% But a forward scheme will only look above x0.\n[deriv,err] = derivest(@(x) sinh(x),0,'Style','forward')\n\n%% Compute the derivative of a function using a backward difference scheme\n% And a backward scheme will only look below x0.\n[deriv,err] = derivest(@(x) sinh(x),0,'Style','backward')\n\n%% Although a central rule may put some samples in the wrong places, it may still succeed\n[d,e,del]=derivest(@(x) log(x),.001,'style','central')\n\n%% But forcing the use of a one-sided rule may be smart anyway\n[d,e,del]=derivest(@(x) log(x),.001,'style','forward')\n\n%% Control the behavior of DERIVEST - forward 2nd order method, with only 1 Romberg term\n% Compute the first derivative, also return the final stepsize chosen\n[deriv,err,fdelta] = derivest(@(x) tan(x),pi,'deriv',1,'Style','for','MethodOrder',2,'RombergTerms',1)\n\n%% Functions should be vectorized for speed, but its not always easy to do.\n[deriv,err] = derivest(@(x) x.^2,0:5,'deriv',1)\n[deriv,err] = derivest(@(x) x^2,0:5,'deriv',1,'vectorized','no')\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/13490-adaptive-robust-numerical-differentiation/DERIVESTsuite/demo/derivest_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7822776750811195}} {"text": "function gen_laguerre_rule ( order, alpha, a, b, filename )\n\n%*****************************************************************************80\n%\n%% GEN_LAGUERRE_RULE generates a Gauss-Laguerre rule.\n%\n% Discussion:\n%\n% This program computes a standard or exponentially weighted \n% generalized Gauss-Laguerre quadrature rule and writes it to a file.\n%\n% The user specifies:\n% * the ORDER (number of points) in the rule;\n% * ALPHA, the exponent of |X|;\n% * A, the left endpoint of integration;\n% * B, the scale factor in the exponential;\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% 24 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEN_LAGUERRE_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a generalized Gauss-Laguerre rule for approximating\\n' );\n fprintf ( 1, ' Integral ( a <= x < oo ) |x-a|^ALPHA exp(-B*(x-a)) f(x) dx\\n' );\n fprintf ( 1, ' of order ORDER.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies ORDER, ALPHA, A, B, and FILENAME.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER is the number of points.\\n' );\n fprintf ( 1, ' ALPHA is the exponent of |X|.\\n' );\n fprintf ( 1, ' A is the left endpoint (typically 0).\\n' );\n fprintf ( 1, ' B is the exponential scale factor (typically 1).\\n' );\n fprintf ( 1, ' FILENAME is used to generate 3 files:\\n' );\n fprintf ( 1, ' * filename_w.txt - the weight file\\n' );\n fprintf ( 1, ' * filename_x.txt - the abscissa file.\\n' );\n fprintf ( 1, ' * filename_r.txt - the region file.\\n' );\n%\n% Initialize the parameters.\n%\n beta = 0.0;\n%\n% Get ORDER.\n%\n if ( nargin < 1 )\n order = input ( ' Enter the rule order ORDER.' );\n elseif ( ischar ( order ) )\n order = str2num ( order );\n end\n%\n% Get ALPHA.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ALPHA is the exponent of |X| in the weighting function.\\n' );\n fprintf ( 1, ' ALPHA is a real number strictly greater than -1.\\n' );\n fprintf ( 1, '\\n' );\n alpha = input ( ' Enter the value of ALPHA.' );\n elseif ( ischar ( alpha ) )\n alpha = str2num ( alpha );\n end\n%\n% Get A.\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A is the left endpoint, typically 0.\\n' );\n fprintf ( 1, '\\n' );\n a = input ( ' Enter the value of A.' );\n elseif ( ischar ( a ) )\n a = str2num ( a );\n end\n%\n% Get B.\n%\n if ( nargin < 4 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' B is the exponential scale factor, typically 1.\\n' );\n fprintf ( 1, '\\n' );\n b = input ( ' Enter the value of B.' );\n elseif ( ischar ( b ) )\n b = str2num ( b );\n end\n%\n% Get FILENAME:\n%\n if ( nargin < 5 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FILENAME specifies the ''root name'' of the quadrature files).\\n' );\n filename = input ( ' Enter FILENAME as a quoted string:' );\n end\n%\n% Input summary.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER = %d\\n', order );\n fprintf ( 1, ' ALPHA = %f\\n', alpha );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' FILENAME = \"%s\".\\n', filename );\n%\n% Construct the rule.\n%\n kind = 5;\n [ x, w ] = cgqf ( order, kind, alpha, beta, a, b );\n%\n% Write the rule.\n%\n r = zeros ( 2, 1 );\n r(1) = a;\n r(2) = r8_huge ( );\n rule_write ( order, filename, x, w, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEN_LAGUERRE_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ t, wts ] = cdgqf ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CDGQF computes a Gauss quadrature formula with default A, B and simple knots.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with a classical weight function with default values for A and B,\n% and only simple knots.\n%\n% There are no moments checks and no printing is done.\n%\n% Use routine EIQFS to evaluate a quadrature computed by CGQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n parchk ( kind, 2 * nt, alpha, beta );\n%\n% Get the Jacobi matrix and zero-th moment.\n%\n [ aj, bj, zemu ] = class_matrix ( kind, nt, alpha, beta );\n%\n% Compute the knots and weights.\n%\n [ t, wts ] = sgqf ( nt, aj, bj, zemu );\n\n return\nend\nfunction [ t, wts ] = cgqf ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% CGQF computes knots and weights of a Gauss quadrature formula.\n%\n% Discussion:\n%\n% The user may specify the interval (A,B).\n%\n% Only simple knots are produced.\n%\n% The user may request that the routine print the knots and weights,\n% and perform a moment check.\n%\n% Use routine EIQFS to evaluate this quadrature formula.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula for default values of A and B.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n%\n% Scale the quadrature rule.\n%\n [ t, wts ] = scqf ( nt, t, mlt, wts, nt, ndx, kind, alpha, beta, a, b );\n\n return\nend\nfunction [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n end\n\n return\nend\nfunction [ d, z ] = imtqlx ( n, d, e, z )\n\n%*****************************************************************************80\n%\n%% IMTQLX diagonalizes a symmetric tridiagonal matrix.\n%\n% Discussion:\n%\n% This routine is a slightly modified version of the EISPACK routine to\n% perform the implicit QL algorithm on a symmetric tridiagonal matrix.\n%\n% The authors thank the authors of EISPACK for permission to use this\n% routine.\n%\n% It has been modified to produce the product Q' * Z, where Z is an input\n% vector and Q is the orthogonal matrix diagonalizing the input matrix.\n% The changes consist (essentialy) of applying the orthogonal transformations\n% directly to Z as they are generated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Roger Martin, James Wilkinson,\n% The Implicit QL Algorithm,\n% Numerische Mathematik,\n% Volume 12, Number 5, December 1968, pages 377-383.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real D(N), the diagonal entries of the matrix.\n%\n% Input, real E(N), the subdiagonal entries of the\n% matrix, in entries E(1) through E(N-1). \n%\n% Input, real Z(N), a vector to be operated on.\n%\n% Output, real D(N), the diagonal entries of the diagonalized matrix.\n%\n% Output, real Z(N), the value of Q' * Z, where Q is the matrix that \n% diagonalizes the input symmetric tridiagonal matrix.\n%\n itn = 30;\n\n prec = eps;\n\n if ( n == 1 )\n return\n end\n\n e(n) = 0.0;\n\n for l = 1 : n\n\n j = 0;\n\n while ( 1 )\n\n for m = l : n\n\n if ( m == n )\n break\n end\n\n if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) )\n break\n end\n\n end\n\n p = d(l);\n\n if ( m == l )\n break\n end\n\n if ( j == itn )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IMTQLX - Fatal error!\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n error ( 'IMTQLX - Fatal error!' );\n end\n\n j = j + 1;\n g = ( d(l+1) - p ) / ( 2.0 * e(l) );\n r = sqrt ( g * g + 1.0 );\n g = d(m) - p + e(l) / ( g + r8_sign ( g ) * abs ( r ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ii = 1 : mml\n\n i = m - ii;\n f = s * e(i);\n b = c * e(i);\n\n if ( abs ( f ) >= abs ( g ) )\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e(i+1) = f * r;\n s = 1.0 / r;\n c = c * s;\n else\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e(i+1) = g * r;\n c = 1.0 / r;\n s = s * c;\n end\n\n g = d(i+1) - p;\n r = ( d(i) - g ) * s + 2.0 * c * b;\n p = s * r;\n d(i+1) = g + p;\n g = c * r - b;\n f = z(i+1);\n z(i+1) = s * z(i) + c * f;\n z(i) = c * z(i) - s * f;\n\n end\n\n d(l) = d(l) - p;\n e(l) = g;\n e(m) = 0.0;\n\n end\n\n end\n\n for ii = 2 : n\n\n i = ii - 1;\n k = i;\n p = d(i);\n\n for j = ii : n\n if ( d(j) < p )\n k = j;\n p = d(j);\n end\n end\n\n if ( k ~= i )\n d(k) = d(i);\n d(i) = p;\n p = z(i);\n z(i) = z(k);\n z(k) = p;\n end\n\n end\n\n return\nend\nfunction parchk ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PARCHK checks parameters ALPHA and BETA for classical weight functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the highest moment to\n% be calculated. This value is only needed when KIND = 8.\n%\n% Input, real ALPHA, BETA, the parameters, if required\n% by the value of KIND.\n%\n if ( kind <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND <= 0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.\n%\n if ( 3 <= kind && alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= KIND and ALPHA <= -1.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check BETA for Jacobi.\n%\n if ( kind == 4 && beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 4 and BETA <= -1.0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA and BETA for rational.\n%\n if ( kind == 8 )\n tmp = alpha + beta + m + 1.0;\n if ( 0.0 <= tmp || tmp <= beta )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 8 but condition on ALPHA and BETA fails.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n end\n\n return\nend\nfunction value = r8_huge ( )\n\n%*****************************************************************************80\n%\n%% R8_HUGE returns a \"huge\" real number.\n%\n% Discussion:\n%\n% The value returned by this function is NOT required to be the\n% maximum representable R8. This value varies from machine to machine,\n% from compiler to compiler, and may cause problems when being printed.\n% We simply want a \"very large\" but non-infinite number.\n%\n% MATLAB provides a built-in symbolic constant \"inf\" that can be used\n% if a huge number is really what you want!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, a huge number.\n%\n value = 1.0E+30;\n\n return\nend\nfunction value = r8_sign ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIGN returns the sign of an R8.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose sign is desired.\n%\n% Output, real VALUE, the sign of X.\n%\n if ( 0 <= x )\n value = +1.0;\n else\n value = -1.0;\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6e', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16e', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction rule_write ( order, filename, x, w, r )\n\n%*****************************************************************************80\n%\n%% RULE_WRITE writes a quadrature rule to a file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, string FILENAME, specifies the output files.\n% write files 'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining \n% weights, abscissas, and region.\n%\n% Input, real X(ORDER), the abscissas.\n%\n% Input, real W(ORDER), the weights.\n%\n% Input, real R(2), the region.\n%\n filename_x = strcat ( filename, '_x.txt' );\n filename_w = strcat ( filename, '_w.txt' );\n filename_r = strcat ( filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' Creating quadrature files.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Root\" file name is \"%s\".\\n', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight file will be \"%s\".\\n', filename_w );\n fprintf ( 1, ' Abscissa file will be \"%s\".\\n', filename_x );\n fprintf ( 1, ' Region file will be \"%s\".\\n', filename_r );\n\n r8mat_write ( filename_w, 1, order, w' );\n r8mat_write ( filename_x, 1, order, x' );\n r8mat_write ( filename_r, 1, 2, r' );\n\n return\nend\nfunction [ t, wts ] = scqf ( nt, t, mlt, wts, nwts, ndx, kind, alpha, ...\n beta, a, b )\n\n%*****************************************************************************80\n%\n%% SCQF scales a quadrature formula to a nonstandard interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the original knots.\n%\n% Input, integer MLT(NT), the multiplicity of the knots.\n%\n% Input, real WTS(NWTS), the weights.\n%\n% Input, integer NWTS, the number of weights.\n%\n% Input, integer NDX(NT), used to index the array WTS.\n% For more details see the comments in CAWIQ.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the scaled knots.\n%\n% Output, real WTS(NWTS), the scaled weights.\n%\n temp = eps;\n\n parchk ( kind, 1, alpha, beta )\n\n if ( kind == 1 )\n\n al = 0.0;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 2 )\n\n al = -0.5;\n be = -0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 3 )\n\n al = alpha;\n be = alpha;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 4 )\n\n al = alpha;\n be = beta;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 5 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / b;\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 6 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / sqrt ( b );\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 7 )\n\n al = alpha;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 8 )\n\n if ( a + b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' A + B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = a + b;\n al = alpha;\n be = beta;\n\n elseif ( kind == 9 )\n\n al = 0.5;\n be = 0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n end\n\n p = slp^( al + be + 1.0 );\n\n for k = 1 : nt\n\n t(k) = shft + slp * t(k);\n l = abs ( ndx(k) );\n\n if ( l ~= 0 )\n tmp = p;\n for i = l : l + mlt(k) - 1\n wts(i) = wts(i) * tmp;\n tmp = tmp * slp;\n end\n end\n\n end\n\n return\nend\nfunction [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n\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/gen_laguerre_rule/gen_laguerre_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7822140698904023}} {"text": "function w = nc_compute ( n, x_min, x_max, x )\n\n%*****************************************************************************80\n%\n%% NC_COMPUTE computes a Newton-Cotes quadrature rule.\n%\n% Discussion:\n%\n% For the interval [X_MIN,X_MAX], the Newton-Cotes quadrature rule\n% estimates\n%\n% Integral ( X_MIN <= X <= X_MAX ) F(X) dX\n%\n% using N abscissas X and weights W:\n%\n% Sum ( 1 <= I <= N ) W(I) * F ( X(I) ).\n%\n% For the CLOSED rule, the equally spaced abscissas include A and B.\n% For the OPEN rule, the equally spaced abscissas do not include A and B.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Input, real X_MIN, X_MAX, the endpoints of the interval.\n%\n% Input, real X(N), the abscissas.\n%\n% Output, real W(N,1), the weights.\n%\n d = zeros ( n, 1 );\n w = zeros ( n, 1 );\n\n for i = 1 : n\n%\n% Compute the Lagrange basis polynomial which is 1 at X(I),\n% and zero at the other nodes.\n%\n d(1:n) = 0.0;\n d(i) = 1.0;\n\n for j = 2 : n\n for k = j : n\n d(n+j-k) = ( d(n+j-k-1) - d(n+j-k) ) / ( x(n+1-k) - x(n+j-k) );\n end\n end\n\n for j = 1 : n - 1\n for k = 1 : n - j\n d(n-k) = d(n-k) - x(n-k-j+1) * d(n-k+1);\n end\n end\n%\n% Evaluate the antiderivative of the polynomial at the endpoints.\n%\n yvala = d(n) / n;\n for j = n - 1 : -1 : 1\n yvala = yvala * x_min + d(j) / j;\n end\n yvala = yvala * x_min;\n\n yvalb = d(n) / n;\n for j = n - 1 : -1 : 1\n yvalb = yvalb * x_max + d(j) / j;\n end\n yvalb = yvalb * x_max;\n\n w(i) = yvalb - yvala;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_total_poly/nc_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7822140635897139}} {"text": "function a = poisson ( nrow, ncol )\n\n%*****************************************************************************80\n%\n%% POISSON returns the POISSON matrix.\n%\n% Formula:\n%\n% if ( I = J )\n% A(I,J) = 4.0\n% elseif ( I = J+1 or I = J-1 or I = J+NROW or I = J-NROW )\n% A(I,J) = -1.0\n% else\n% A(I,J) = 0.0\n%\n% Example:\n%\n% NROW = NCOL = 3\n%\n% 4 -1 0 | -1 0 0 | 0 0 0\n% -1 4 -1 | 0 -1 0 | 0 0 0\n% 0 -1 4 | 0 0 -1 | 0 0 0\n% ----------------------------\n% -1 0 0 | 4 -1 0 | -1 0 0\n% 0 -1 0 | -1 4 -1 | 0 -1 0\n% 0 0 -1 | 0 -1 4 | 0 0 -1\n% ----------------------------\n% 0 0 0 | -1 0 0 | 4 -1 0\n% 0 0 0 | 0 -1 0 | -1 4 -1\n% 0 0 0 | 0 0 -1 | 0 -1 4\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A results from discretizing Poisson's equation with the\n% 5 point operator on a square mesh of N points.\n%\n% A has eigenvalues\n%\n% LAMBDA(I,J) = 4 - 2 * COS(I*PI/(N+1))\n% - 2 * COS(J*PI/(M+1)), I = 1 to N, J = 1 to M.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub, Charles Van Loan,\n% Matrix Computations, second edition,\n% Johns Hopkins University Press, Baltimore, Maryland, 1989\n% (Section 4.5.4).\n%\n% Parameters:\n%\n% Input, integer NROW, NCOL, the number of rows and columns \n% in the grid.\n%\n% Output, real A(NROW*NCOL,NROW*NCOL), the matrix.\n%\n n = nrow * ncol;\n\n a = zeros ( n, n );\n\n i = 0;\n\n for i1 = 1 : nrow\n for j1 = 1 : ncol\n\n i = i + 1;\n\n if ( 1 < i1 )\n j = i - ncol;\n a(i,j) = -1.0;\n end\n\n if ( 1 < j1 )\n j = i - 1;\n a(i,j) = -1.0;\n end\n\n j = i;\n a(i,j) = 4.0;\n\n if ( j1 < ncol )\n j = i + 1;\n a(i,j) = -1.0;\n end\n\n if ( i1 < nrow )\n j = i + ncol;\n a(i,j) = -1.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/poisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7822140619539689}} {"text": "function pdf = weibull_discrete_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% WEIBULL_DISCRETE_PDF evaluates the discrete Weibull PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B) = ( 1 - A )**X**B - ( 1 - A )**(X+1)**B.\n%\n% WEIBULL_DISCRETE_PDF(X)(A,1) = GEOMETRIC_PDF(X)(A)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X, the argument of the PDF.\n% 0 <= X\n%\n% Input, real A, B, the parameters that define the PDF.\n% 0 <= A <= 1,\n% 0 < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0 )\n pdf = 0.0;\n else\n pdf = ( 1.0 - a )^(x^b) - ( 1.0 - a )^((x+1)^b);\n end\n\n return\nend\n", "meta": {"author": "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/weibull_discrete_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7821807067141777}} {"text": "function y=stdtpdf(x,mu,sigma2,nu)\n% Probability Density Function (PDF) for the Standardized T distribution\n%\n% USAGE:\n% Y = stdtpdf(X,MU,SIGMA2,NU)\n%\n% INPUTS:\n% X - Standardized T random variables\n% MU - Mean of X, either scalar or size(x) \n% SIGMA2 - Variance of X, either scalar or size(x)\n% NU - Degree of freedom parameters, either scalar or size(x)\n%\n% OUTPUTS:\n% Y - Probability density evaluated at X\n%\n% COMMENTS:\n% NU>2\n%\n% REFERENCES:\n% [1] Cassella and Berger (1990) 'Statistical Inference'\n%\n% See also STDTCDF, STDTINV, STDTRND, STDTLOGLIK, TPDF \n\n% Copyright:\n% Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 6 Date: 8/21/2014\n\n[T,K]=size(x);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif K~=1\n error('X must be a column vector');\nend\n\nif nargin==4\n if length(mu)~=1 && ~all(size(mu)==[T K])\n error('mu must be either a scalar or the same size as X');\n end\n if any(sigma2<=0)\n error('sigma2 must contain only positive elements')\n end\n if length(sigma2)==1\n sigma2=sigma2*ones(T,K);\n elseif size(sigma2,1)~=T || size(sigma2,2)~=1\n error('sigma2 must be a scalar or a vector with the same dimensions as X');\n end\n if length(nu)>1 || nu<=2\n error('nu must be a scalar greater than 2');\n end\n x=x-mu;\nelse\n error('Only 4 inputs supported');\nend\n\n\nconstant = exp(gammaln( 0.5 * (nu + 1)) - gammaln(0.5 * nu));\ny = constant ./ sqrt(pi * (nu - 2) * sigma2) .* (1 + (x-mu) .^ 2.0 / (sigma2 * (nu - 2))) .^ (-(nu + 1) / 2);\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/distributions/stdtpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7821807043056108}} {"text": "%% This file will symbolic solve for the ODE of the Single Pendulum on a Cart system.\n% Coded By: K\n% Data: 2019/04/27\n%%\nclc;clear;close all\n% Define the symbolic symbols you need\nsyms x0(t) dx0(t) ddx0 theta(t) dtheta(t) ddtheta M m L F k0 k1 g I1 dum\n% Set some variables to zero to simplify the model\nI1=0; k0=0; k1=0;\n% First define the position of the pendulum mass center\nx1=x0+L*sin(theta)\ny1=L*cos(theta)\n\n% Now define the velocity of the cart and moving mass\nv0=diff(x0,t)\nv1x=diff(x1,t)\nv1y=diff(y1,t)\n\n% Substitute the variables\nv0=subs(v0,diff(x0,t),dx0);\nv1x=subs(v1x,diff(x0,t),dx0);\nv1x=subs(v1x,diff(theta,t),dtheta);\nv1y=subs(v1y,diff(x0,t),dx0);\nv1y=subs(v1y,diff(theta,t),dtheta);\n\nsimplify(v1x^2+v1y^2)\nsimplify(v1x)\nsimplify(v1y)\n\n% Now define the kinetic energy of the system\nEngK=simplify(0.5*M*v0^2+0.5*m*simplify(v1x^2+v1y^2)+0.5*I1*diff(theta,t)^2)\nEngP=m*g*(cos(theta))*L\n\n% Define the Rayley disspation function\nDamp=0.5*k0*v0^2+0.5*k1*dtheta^2;\n\n% Now define the Lagrangian\nLag=simplify(EngK-EngP)\n\n%% Now get the second order ODE\nthe1Part1=diff(subs(Lag,dtheta,dum),dum);\nthe1Part1=subs(the1Part1,dum,dtheta);\nthe1Part1=diff(the1Part1,t);\n%\nthe1Part2=diff(subs(Lag,theta,dum),dum);\nthe1Part2=subs(the1Part2,dum,theta);\n% \nthe1Part3=diff(subs(Damp,dtheta,dum),dum);\nthe1Part3=subs(the1Part3,dum,dtheta);\neqn1=the1Part1-the1Part2+the1Part3\n%\neqn1=subs(eqn1,diff(dx0(t), t),ddx0);\neqn1=subs(eqn1,diff(x0(t), t, t),ddx0);\neqn1=subs(eqn1,diff(theta(t), t),dtheta);\neqn1=subs(eqn1,diff(dtheta(t), t),ddtheta);\n\n% Second equation\nthe2Part1=diff(subs(Lag,dx0,dum),dum);\nthe2Part1=subs(the2Part1,dum,dx0);\nthe2Part1=diff(the2Part1,t);\n%\nthe2Part2=diff(subs(Lag,x0,dum),dum);\nthe2Part2=subs(the2Part2,dum,x0);\n% \nthe2Part3=diff(subs(Damp,dx0,dum),dum);\nthe2Part3=subs(the2Part3,dum,dx0);\neqn2=the2Part1-the2Part2+the2Part3-F\n%\neqn2=subs(eqn2,diff(dx0(t), t),ddx0);\neqn2=subs(eqn2,diff(x0(t), t, t),ddx0);\neqn2=subs(eqn2,diff(theta(t), t),dtheta);\neqn2=subs(eqn2,diff(dtheta(t), t),ddtheta);\n\n% Final eqn1 and eqn2\nEqn1=simplify(eqn1)==0 \nEqn2=simplify(eqn2)==0\n\n%% Solve for ddtheta and ddx0\neqns=[Eqn1 Eqn2];\nvars=[ddtheta ddx0];\n[Ans1 Ans2]=solve(eqns,vars);\n\nAns1=simplify(Ans1)\nAns2=simplify(Ans2)\n\n%% Now rewrite the second order system into first order system\nsyms z1 z2 z3 z4\nthisisddtheta1=simplify(subs(Ans1,[theta(t) x0(t) dtheta(t) dx0(t)],[z1 z2 z3 z4]))\nthisisddtheta2=simplify(subs(Ans2,[theta(t) x0(t) dtheta(t) dx0(t)],[z1 z2 z3 z4]))\n\n%% Save this file into Matlab Function\n% dtheta=z3, dx=z4, ddtheta=thisistheta1, ddx=thisistheta2\nEqns=[z3;z4;thisisddtheta1;thisisddtheta2]\n\nmatlabFunction(Eqns,'File','SinglePendulum_ODE','Vars',{t,[z1 z2 z3 z4],F,M,m,L,g},'Optimize',true)\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/SymbolicCalODE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7821806965875922}} {"text": "%% RD_FEM solves a 1D reaction/diffusion problem using finite elements.\n%\n% Discussion:\n%\n% This script sets up and runs a finite element simulation code \n% for a 1D reaction/diffusion equation.\n%\n% The dynamics are given by the following reaction/diffusion equation\n% for the function W(T,X):\n%\n% W_t = W_xx + NL(W,c),\n%\n% where NL(W,c) is a polynomial in W:\n%\n% NL(W,c) = c(1) + c(2) * W + c(3) * W^2 + c(4) * W^3\n%\n% with Neumann boundary conditions at X = 0.0 and X = 1.0:\n%\n% W_x(T,0.0) = 0.0\n% W_x(T,1.0) = 0.0\n%\n% and initial condition at T = 0.0:\n%\n% W(0,X) = sin ( pi * X ).\n%\n% The problem is to be solved for 0.0 <= T <= 4.0, 0.0 <= X <= 1.0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 April 2011\n%\n% Author:\n%\n% Eugene Cliff\n%\n% Reference:\n%\n% Jeffrey Borggaard, John Burkardt, John Burns, Eugene Cliff,\n% Working Notes on a Reaction Diffusion Model: a Finite Element Formulation.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RD_FEM:\\n' );\n fprintf ( 1, ' Solve a 1D time-dependent reaction/diffusion problem\\n' );\n fprintf ( 1, ' with a nonlinear term and Neumann boundary conditions,\\n' );\n fprintf ( 1, ' using Neumann boundary conditions.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The equation is discretized using the finite element method.\\n' );\n%\n% Set initial condition.\n% The first option uses a centered hat.\n%\n if ( 0 )\n w_0 = @(x) 1.0 + basic_hat ( 8.0 * x - 4.0 );\n else\n w_0 = @(x) sin(pi*x);\n end\n%\n% Set the polynomial coefficients of the reaction term.\n% Here, c = -x + x^3 = x * ( x^2 - 1 )\n%\n c = [ 0.0; -1.0; 0.0; 1.0 ];\n%\n% Select 101 times for output.\n%\n t = ( 0.0 : 0.04 : 4.0 );\n%\n% The number of spatial grid points is N+1;\n%\n n = 32;\n x = linspace ( 0.0, 1.0, n + 1 );\n%\n% T is a vector of 101 times.\n% W is an array of 101x33 function values.\n%\n [ T, W ] = rd_lin_spline ( w_0, t, n, c );\n%\n% Plot the results.\n%\n plot_rd ( t, x, W, c )\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RD_FEM:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem_neumann/rd_fem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.7821150957305505}} {"text": "function[a]=morseafun(varargin)\n%MORSEAFUN Returns the generalized Morse wavelet amplitude or a-function.\n%\n% MORSEAFUN is a low-level function called by many a number of the Morse\n% wavelet functions.\n%\n% A=MORSEAFUN(GAMMA,BETA) returns the generalized Morse wavelet \n% amplitude, called \"A_{BETA,GAMMA}\" by Lilly and Olhede (2009).\n%\n% By default, A is chosen such that the maximum of the frequency-\n% domain wavelet is equal to 2, the ``bandpass normalization.''\n%\n% A=MORSEAFUN(GAMMA,BETA,'energy') instead returns the coefficient\n% giving the wavelet unit energy. \n%\n% A=MORSEAFUN(K,GAMMA,BETA,'energy') returns the unit energy coefficient \n% appropriate for the Kth-order wavelet. The default choice is K=1.\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2006--2016 J.M. Lilly --- type 'help jlab_license' for details\n\nif strcmpi(varargin{1},'--t')\n morseafun_test;return\nend\n\nstr='band';\nif ischar(varargin{end})\n str=varargin{end};\n varargin=varargin(1:end-1);\nend\n\nk=1;\nif length(varargin)==3\n k=varargin{1};\n varargin=varargin(2:end);\nend\n\nga=varargin{1};\nbe=varargin{2};\nif strcmpi(str(1:3),'ban')\n om=morsefreq(ga,be); \n% a=frac(2,(om.^be).*exp(-om.^ga));\n a=frac(2,exp(be.*log(om)-om.^ga));\n a(be==0)=2;\nelseif strcmpi(str(1:3),'tes')\n a=sqrt(frac(2 *pi*ga.*2.^frac(2*be+1,ga),gamma(frac(2*be+1,ga)))); \nelseif strcmpi(str(1:3),'ene')\n r=frac(2*be+1,ga);\n a=double((2*pi*ga.*(2.^r).*exp(gammaln(k)-gammaln(k+r-1))).^(1/2));\nend\n\nfunction[]=morseafun_test\n\nga1=(2:1:9);\nbe1=(1:1:10);\n[ga,be]=meshgrid(ga1,be1);\nom=reshape(morsefreq(ga,be),10,8);\n\ndom=0.01;\nomgrid=permute((0:dom:20)',[3 2 1]);\nomgrid=vrep(omgrid,length(ga1),2);\nomgrid=vrep(omgrid,length(be1),1);\n\nomgrid=omgrid.*vrep(om,size(omgrid,3),3);\na=morseafun(ga,be,'energy');\n\nbegrid=vrep(be,size(omgrid,3),3);\ngagrid=vrep(ga,size(omgrid,3),3);\nagrid=vrep(a,size(omgrid,3),3);\n\npsi=agrid.*omgrid.^begrid.*exp(-omgrid.^gagrid);\npsiint=vsum(psi.^2,3).*dom.*om./(2*pi);\n\nreporttest('MORSEAFUN unit energy', allall(abs(psiint-1)<1e-2))\n\na2=morseafun(ga,be,'test');\nreporttest('MORSEAFUN unit energy, alternate formulation', aresame(a,a2,1e-6));\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/jWavelet/morseafun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7819974936603358}} {"text": "function [ fea, out ] = ex_laplace1( varargin )\n%EX_LAPLACE1 2D Laplace equation example on a unit square.\n%\n% [ FEA, OUT ] = EX_LAPLACE1( VARARGIN ) Laplace equation on a unit square\n% with exact solution 2*y/((1+x)^2+y^2). Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% igrid scalar 1/{0} Cell type (0=quadrilaterals, 1=triangles)\n% hmax scalar {1/10} Max grid cell size\n% refsol string {2*y/((1+x)^2+y^2)} Reference solution\n% sfun string {sflag1} Shape function\n% iphys scalar 0/{1} Use physics mode to define problem (=1)\n% or directly define fea.eqn/bdr fields (=0)\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'igrid', 0; ...\n 'hmax', 0.1; ...\n 'refsol', '2*y/((1+x)^2+y^2)'; ...\n 'sfun', 'sflag1'; ...\n 'iphys', 1; ...\n 'icub', 2; ...\n 'iplot', 1; ...\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\n% Geometry definition.\ngobj = gobj_rectangle();\nfea.geom.objects = { gobj };\n\n\n% Grid generation.\nif ( opt.igrid==-1 )\n fea.grid = rectgrid(round(1/opt.hmax));\n fea.grid = quad2tri( fea.grid );\nelseif ( opt.igrid==0 )\n fea.grid = rectgrid(round(1/opt.hmax));\nelse\n fea.grid = gridgen(fea,'hmax',opt.hmax,'fid',fid);\nend\nn_bdr = max(fea.grid.b(3,:)); % Number of boundaries.\n\n\n% Problem definition.\nfea.sdim = { 'x' 'y' }; % Coordinate names.\nif ( opt.iphys==1 )\n\n fea = addphys(fea,@poisson); % Add Poisson equation physics mode.\n fea.phys.poi.sfun = { opt.sfun }; % Set shape function.\n fea.phys.poi.eqn.coef{3,4} = { 0 }; % Set source term coefficient to zero.\n fea.phys.poi.bdr.coef{1,end} = repmat({opt.refsol},1,n_bdr); % Set Dirichlet boundary coefficient to reference solution.\n fea = parsephys(fea); % Check and parse physics modes.\n\nelse\n\n fea.dvar = { 'u' }; % Dependent variable name.\n fea.sfun = { opt.sfun }; % Shape function.\n\n % Define equation system.\n fea.eqn.a.form = { [2 3;2 3] }; % First row indicates test function space (2=x-derivative + 3=y-derivative),\n % second row indicates trial function space (2=x-derivative + 3=y-derivative).\n fea.eqn.a.coef = { 1 }; % Coefficient used in assembling stiffness matrix.\n\n fea.eqn.f.form = { 1 }; % Test function space to evaluate in right hand side (1=function values).\n fea.eqn.f.coef = { 0 }; % Coefficient used in right hand side.\n\n % Define boundary conditions.\n fea.bdr.d = cell(1,n_bdr);\n [fea.bdr.d{:}] = deal(opt.refsol); % Assign reference solution to all boundaries (Dirichlet).\n\n fea.bdr.n = cell(1,n_bdr); % No Neumann boundaries ('fea.bdr.n' empty).\n\nend\n\n\n% Parse and solve problem.\nfea = parseprob(fea); % Check and parse problem struct.\nfea.sol.u = solvestat(fea,'fid',fid,'icub',opt.icub); % Call to stationary solver.\n\n\n% Postprocessing.\ns_err = ['abs(',opt.refsol,'-u)'];\nif ( opt.iplot>0 )\n figure\n subplot(2,1,1)\n postplot(fea,'surfexpr','u')\n title('Solution u')\n subplot(2,1,2)\n postplot(fea,'surfexpr',s_err)\n title('Error')\nend\n\n\n% Error checking.\nif ( size(fea.grid.c,1)==4 )\n xi = [0;0];\nelse\n xi = [1/3;1/3;1/3];\nend\nerr = evalexpr0(s_err,xi,1,1:size(fea.grid.c,2),[],fea);\nref = evalexpr0('u',xi,1,1:size(fea.grid.c,2),[],fea);\nerr = sqrt(sum(err.^2)/sum(ref.^2));\n\nif( ~isempty(fid) )\n fprintf(fid,'\\nL2 Error: %f\\n',err)\n fprintf(fid,'\\n\\n')\nend\n\nout.err = err;\nout.pass = out.err<0.01;\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_laplace1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.781997479792461}} {"text": "%The basic idea behind the false position method is similar to the bisection\n%method in that we continuously shrink the interval the root lies on until\n%the algorithm converges on the root. Unlike the bisection method, the false\n%position method does not halve the interval with each iteration. Instead of\n%using the midpoint of a and b to create the new interval, the false position\n%method uses the x-intercept of the line connecting f(a) and f(b). This \n%algorithm converges faster than the bisection method.\n\n%INPUTS:\n%Function handle f\n%endpoint a\n%endpoint b\n%maximum tolerated error\n\n%OUTPUTS:\n%An approximated value for the root of f within the defined interval.\n\n%Written by MatteoRaso\n\nfunction y = false_position(f, a, b, error)\n if ~(f(a) < 0)\n disp(\"f(a) must be less than 0\")\n elseif ~(f(b) > 0)\n disp(\"f(b) must be greater than zero\")\n else \n c = 100000;\n while abs(f(c)) > error\n %Formula for the x-intercept\n c = -f(b) * (b - a) / (f(b) - f(a)) + b;\n if f(c) < 0\n a = c;\n else\n b = c;\n endif\n disp(f(c))\n endwhile\n x = [\"The root is approximately located at \", num2str(c)];\n disp(x)\n y = c;\n endif\nendfunction\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/arithmetic_analysis/false_position.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7819774164171005}} {"text": "function [w3j,jmin, jmax] = Wigner3j_new(j2, j3, m1, m2, m3)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\tThis subroutine will calculate the Wigner 3j symbols\n%\n%\t\tj j2 j3\n%\t\tm1 m2 m3\n%\n%\tfor all allowable values of j. The returned values in the array j are \n%\tcalculated only for the limits\n%\n%\t\tjmin = max(|j2-j3|, |m1|)\n%\t\tjmax = j2 + j3\n%\n%\tTo be non-zero, m1 + m2 + m3 = 0. In addition, it is assumed that all j and m are \n%\tintegers. Returned values have a relative error less than ~1.d-8 when j2 and j3 \n%\tare less than 103 (see below). In practice, this routine is probably usable up to 165.\n%\n%\tThis routine is based upon the stable non-linear recurence relations of Luscombe and \n%\tLuban (1998) for the \"non classical\" regions near jmin and jmax. For the classical \n%\tregion, the standard three term recursion relationship is used (Schulten and Gordon 1975). \n%\tNote that this three term recursion can be unstable and can also lead to overflows. Thus \n%\tthe values are rescaled by a factor \"scalef\" whenever the absolute value of the 3j coefficient \n%\tbecomes greater than unity. Also, the direction of the iteration starts from low values of j\n%\tto high values, but when abs(w3j(j+2)/w3j(j)) is less than one, the iteration will restart \n%\tfrom high to low values. More efficient algorithms might be found for specific cases \n%\t(for instance, when all m's are zero).\n%\n%\tVerification: \n%\n%\tThe results have been verified against this routine run in quadruple precision.\n%\tFor 1.e7 acceptable random values of j2, j3, m2, and m3 between -200 and 200, the relative error\n%\twas calculated only for those 3j coefficients that had an absolute value greater than \n%\t1.d-17 (values smaller than this are for all practical purposed zero, and can be heavily \n%\taffected by machine roundoff errors or underflow). 853 combinations of parameters were found\n%\tto have relative errors greater than 1.d-8. Here I list the minimum value of max(j2,j3) for\n%\tdifferent ranges of error, as well as the number of times this occured\n%\t\n%\t1.d-7 < error <=1.d-8 = 103\t# = 483\n%\t1.d-6 < error <= 1.d-7 = 116\t# = 240\n%\t1.d-5 < error <= 1.d-6 = 165\t# = 93\n%\t1.d-4 < error <= 1.d-5 = 167\t# = 36\n%\n%\tMany times (maybe always), the large relative errors occur when the 3j coefficient \n%\tchanges sign and is close to zero. (I.e., adjacent values are about 10.e7 times greater \n%\tin magnitude.) Thus, if one does not need to know highly accurate values of the 3j coefficients\n%\twhen they are almost zero (i.e., ~1.d-10) this routine is probably usable up to about 160.\n%\n%\tThese results have also been verified for parameter values less than 100 using a code\n%\tbased on the algorith of de Blanc (1987), which was originally coded by Olav van Genabeek, \n%\tand modified by M. Fang (note that this code was run in quadruple precision, and\n%\tonly calculates one coefficient for each call. I also have no idea if this code\n%\twas verified.) Maximum relative errors in this case were less than 1.d-8 for a large number\n%\tof values (again, only 3j coefficients greater than 1.d-17 were considered here).\n%\t\n%\tThe biggest improvement that could be made in this routine is to determine when one should\n%\tstop iterating in the forward direction, and start iterating from high to low values. \n%\n%\tCalling parameters\n%\t\tIN\t\n%\t\t\tj2, j3, m1, m2, m3 \tInteger values.\n%\t\tOUT\t\n%\t\t\tw3j\t\t\tArray of length jmax - jmin + 1.\n%\t\t\tjmin, jmax\t\tMinimum and maximum values\n%\t\t\t\t\t\tout output array.\n%\tDependencies: None\n%\t\n%\tWritten by Mark Wieczorek August (2004)\n%\n%\tAugust 2009: Based on the suggestions of Roelof Rietbroek, the calculation of RS has been slightly\n%\tmodified so that division by zero will not cause a run time crash (this behavior depends on how the \n%\tcompiler treats IEEE floating point exceptions). These values were never used in the original code \n%\twhen this did occur.\n%\n%\tCopyright (c) 2005-2009, Mark A. Wieczorek\n%\tAll rights reserved.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\timplicit none\n%\tinteger, intent(in) ::\tj2, j3, m1, m2, m3\n%\tinteger, intent(out) ::\tjmin, jmax\n%\treal*8, intent(out) ::\tw3j(:)\n%\treal*8 ::\t\twnmid, wpmid, scalef, denom, rs(j2+j3+1), &\n%\t\t\t\twl(j2+j3+1), wu(j2+j3+1), xjmin, yjmin, yjmax, zjmax, xj, zj\n%\tinteger :: \t\tj, jnum, jp, jn, k, flag1, flag2, jmid\n\t\n\n%% some basic constants\n\nflag1 = 0;\nflag2 = 0;\n\t\nscalef = 1;\n\t\njmin = max(abs(j2-j3), abs(m1));\njmax = j2 + j3;\njnum = jmax - jmin + 1;\n\nw3j = zeros(1,jnum);\n\n%% some simple functions\njindex = @(j) j-jmin+1;\n\na = @(j) sqrt((j.^2 - (j2-j3).^2) .* ((j2+j3+1).^2 - j.^2) * (j.^2-m1^2));\n\ny= @(j) -(2*j+1) .* ( m1 .* (j2.*(j2+1) - j3*(j3+1)) - (m3-m2).*j.*(j+1));\n \nx = @(j) j .* a(j+1);\n\t\t\nz = @(j) (j+1) .* a(j);\n\n%% exclude some basic cases\twhich give zero\nif abs(m2) > j2 || abs(m3) > j3\n return\nelseif m1 + m2 + m3 ~= 0\n return\nelseif jmax < jmin\n return\nend\n\t\n%% Only one term is present\n\t\nif jnum == 1\n \n w3j = 1 / sqrt(2 * jmin + 1);\n \n if (w3j < 0 && (-1)^(j2-j3+m2+m3) > 0) || ...\n (w3j > 0 && (-1)^(j2-j3+m2+m3) < 0)\n w3j = -w3j;\n end\n return\n \nend\n\t\t\n%% more then one term\n%\n% Calculate lower non-classical values for [jmin, jn]. If the second term\n%\tcan not be calculated because the recursion relationsips give rise to a\n%\t1/0, set flag1 to 1. If all m's are zero, this is not a problem\n%\tas all odd terms must be zero.\n%\n\n\t\nrs = 0;\nwl = 0;\n\t\nxjmin = x(jmin);\nyjmin = y(jmin);\n\t\nif (m1 == 0 && m2 == 0 && m3 == 0) % All m's are zero\n\t\n wl(jindex(jmin)) = 1;\n wl(jindex(jmin+1)) = 0;\n jn = jmin+1;\n \nelseif yjmin == 0 % The second terms is either zero\n\t\n if xjmin == 0 % or undefined\n flag1 = 1;\n jn = jmin;\n else\n wl(jindex(jmin)) = 1;\n wl(jindex(jmin+1)) = 0;\n jn = jmin+1;\n end\n\t\t\nelseif xjmin * yjmin >= 0 % The second term is outside of the non-classical region\n \n wl(jindex(jmin)) = 1;\n wl(jindex(jmin+1)) = -yjmin / xjmin;\n jn = jmin+1;\n\t\t\nelse\t\t\t\t\t\t\t% Calculate terms in the non-classical region\n\t\n rs(jindex(jmin)) = -xjmin / yjmin;\n\t\t\n jn = jmax;\n for j = jmin + 1:jmax-1\n \n denom = y(j) + z(j)*rs(jindex(j-1));\n xj = x(j);\n if abs(xj) > abs(denom) || xj * denom >= 0 || denom == 0\n jn = j-1;\n break\n else\n rs(jindex(j)) = -xj / denom;\n end\n\t\t\t\t\n end\n\t\t\n wl(jindex(jn)) = 1;\n\t\t\n for k = 1:jn - jmin\n \n wl(jindex(jn-k)) = wl(jindex(jn-k+1)) * rs(jindex(jn-k));\n \n end\n \n if jn == jmin\t% Calculate at least two terms so that\n \n wl(jindex(jmin+1)) = -yjmin / xjmin;\t\t% these can be used in three term\n jn = jmin+1;\t\t\t\t\t% recursion\n \n end\n\nend\n\t\nif jn == jmax\t\t\t\t\t% All terms are calculated\n\t\n w3j = wl;\n \n % normalize\n norm = sum((2*(jmin:jmax)+1) .* w3j.^2);\n w3j = w3j ./ sqrt(norm);\n\n % fix sign\n if (w3j(end) < 0 && (-1)^(j2-j3+m2+m3) > 0) || ...\n (w3j(end) > 0 && (-1)^(j2-j3+m2+m3) < 0)\n w3j = -w3j;\n end\n \n return\nend\n\n%%\n%\n% \tCalculate upper non-classical values for [jp, jmax].\n%\tIf the second last term can not be calculated because the\n%\trecursion relations give a 1/0, set flag2 to 1.\n%\t(Note, I don't think that this ever happens).\n%\n\nwu = 0;\n\t\nyjmax = y(jmax);\nzjmax = z(jmax);\n\t\nif (m1 == 0 && m2 == 0 && m3 == 0)\n\t\n wu(jindex(jmax)) = 1;\n wu(jindex(jmax-1)) = 0;\n jp = jmax-1;\n\t\t\nelseif yjmax == 0\n\t\n if zjmax == 0\n flag2 = 1;\n jp = jmax;\n else\n wu(jindex(jmax)) = 1;\n wu(jindex(jmax-1)) = - yjmax / zjmax;\n jp = jmax-1;\n end\n\t\t\nelseif yjmax * zjmax >= 0\n\t\n wu(jindex(jmax)) = 1;\n wu(jindex(jmax-1)) = - yjmax / zjmax;\n jp = jmax-1;\n\nelse\n rs(jindex(jmax)) = -zjmax / yjmax;\n\n jp = jmin;\n for j = jmax-1:-1:jn\n \n denom = y(j) + x(j)*rs(jindex(j+1));\n zj = z(j);\n if abs(zj) > abs(denom) || zj * denom >= 0 || denom == 0\n jp = j+1;\n break\n else\n rs(jindex(j)) = -zj / denom;\n end\n \n end\n\t\t\n wu(jindex(jp)) = 1;\n \n for k=1:jmax - jp\n wu(jindex(jp+k)) = wu(jindex(jp+k-1))*rs(jindex(jp+k));\n end\n \n\t\t\n if jp == jmax\n wu(jindex(jmax-1)) = - yjmax / zjmax;\n jp = jmax-1;\n end\n\t\t\nend\n\t\n%% \n%\n% \tCalculate classical terms for [jn+1, jp-1] using standard three\n% \tterm rercusion relationship. Start from both jn and jp and stop at the\n% \tmidpoint. If flag1 is set, perform the recursion solely from high to\n% \tlow values. If flag2 is set, perform the recursion solely from low to high.\n\t\nif flag1 == 0\n\t\n jmid = ceil((jn + jp)/2);\n\t\t\n for j = jn : jmid - 1\n \n wl(jindex(j+1)) = - (z(j)*wl(jindex(j-1)) +y(j)*wl(jindex(j))) / x(j);\n\t\t\t\n if abs(wl(jindex(j+1))) > 1 \t\t\t\t% watch out for overflows.\n wl(jindex(jmin):jindex(j+1)) = wl(jindex(jmin):jindex(j+1)) / scalef;\n end\n\t\t\t\n % if values are decreasing\n if (abs(wl(jindex(j+1)) / wl(jindex(j-1))) < 1 && wl(jindex(j+1)) ~= 0)\n \n % stop upward iteration\n jmid = j+1;\t% and start with the downward\n break\t% iteration.\n end\n end\n\t\t\n wnmid = wl(jindex(jmid));\n\t\t\n if (abs(wnmid/wl(jindex(jmid-1))) < 1e-6 && ...\n wl(jindex(jmid-1)) ~= 0) \t\t\t\t% Make sure that the stopping\n \n wnmid = wl(jindex(jmid-1));\t\t\t\t\t% midpoint value is not a zero,\n jmid = jmid - 1;\t\t\t\t\t\t\t% or close to it%\n end\n\t\t\n\t\t\n for j=jp:-1:jmid+1\n wu(jindex(j-1)) = - (x(j)*wu(jindex(j+1)) + y(j)*wu(jindex(j)) ) / z(j);\n if (abs(wu(jindex(j-1))) > 1)\n wu(jindex(j-1):jindex(jmax)) = wu(jindex(j-1):jindex(jmax)) / scalef;\n end\n \n end\n\t\t\n wpmid = wu(jindex(jmid));\n\t\t\n % rescale two sequences to common midpoint\n\t\t\n if jmid == jmax\n w3j(1:jnum) = wl(1:jnum);\n elseif jmid == jmin\n w3j(1:jnum) = wu(1:jnum);\n else\n w3j(1:jindex(jmid)) = wl(1:jindex(jmid)) * wpmid / wnmid;\n w3j(jindex(jmid+1):jindex(jmax)) = wu(jindex(jmid+1):jindex(jmax));\n end\n\t\t\nelseif (flag1 == 1 && flag2 == 0) \t% iterature in downward direction only\n\t\t\n for j=jp:-1:jmin+1\n wu(jindex(j-1)) = - (x(j)*wu(jindex(j+1)) + y(j)*wu(jindex(j)) ) / z(j);\n if (abs(wu(jindex(j-1))) > 1)\n wu(jindex(j-1):jindex(jmax)) = wu(jindex(j-1):jindex(jmax)) / scalef;\n end\n end\n\t\t\n w3j(1:jnum) = wu(1:jnum);\n\t\t\nelseif flag2 == 1 && flag1 == 0 % iterature in upward direction only\n\t\t\n for j = jn:jp-1\n wl(jindex(j+1)) = - (z(j)*wl(jindex(j-1)) +y(j)*wl(jindex(j))) / x(j);\n if abs(wl(jindex(j+1))) > 1\n wl(jindex(jmin):jindex(j+1)) = wl(jindex(jmin):jindex(j+1))/ scalef;\n end\n end\n\t\t\n w3j = wl;\n\t\t\nelseif flag1 == 1 && flag2 == 1\n\n error('Can not calculate function for input values');\n\nend\n\n% normalize\nnorm = sum((2*(jmin:jmax)+1) .* w3j.^2); \nw3j = w3j ./ sqrt(norm);\n\n% fix sign\nif (w3j(end) < 0 && (-1)^(j2-j3+m2+m3) > 0) || ...\n (w3j(end) > 0 && (-1)^(j2-j3+m2+m3) < 0)\n w3j = -w3j;\nend\n\n\t\t\nend\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tools/math_tools/Wigner3j_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.7819710857551277}} {"text": "function s = QuinticTimeScaling(Tf, t)\n% *** CHAPTER 9: TRAJECTORY GENERATION ***\n% Takes Tf: Total time of the motion in seconds from rest to rest,\n% t: The current time t satisfying 0 < t < Tf.\n% Returns s: The path parameter s(t) corresponding to a fifth-order\n% polynomial motion that begins and ends at zero velocity and \n% zero acceleration.\n% Example Input: \n% \n% clear; clc;\n% Tf = 2;\n% t = 0.6;\n% s = QuinticTimeScaling(Tf,t)\n% \n% Output:\n% s =\n% 0.1631\n\ns = 10 * (t / Tf) ^ 3 - 15 * (t / Tf) ^ 4 + 6 * (t / Tf) ^ 5;\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/QuinticTimeScaling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7819308710143394}} {"text": "function K = knPoly(X, Y, o, c)\n% Polynomial kernel k(x,y)=(x'y+c)^o\n% Input:\n% X: d x nx data matrix\n% Y: d x ny data matrix\n% o: order of polynomial\n% c: constant\n% Ouput:\n% K: nx x ny kernel matrix\n% Written by Mo Chen (sth4nth@gmail.com).\nif nargin < 4\n c = 0;\nend\n\nif nargin < 3\n o = 3;\nend\n\nif nargin < 2 || isempty(Y) \n K = (dot(X,X,1)+c).^o; % norm in kernel space\nelse\n K = (X'*Y+c).^o;\nend\n\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter06/knPoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7819308588006209}} {"text": "% runpca() - perform principal component analysis (PCA) using singular value \n% decomposition (SVD) using Matlab svd() or svds()\n% >> inv(eigvec)*data = pc;\n% Usage:\n% >> [pc,eigvec,sv] = runpca(data);\n% >> [pc,eigvec,sv] = runpca(data,num,norm)\n%\n% Inputs:\n% data - input data matrix (rows are variables, columns observations)\n% num - number of principal comps to return {def|0|[] -> rows in data}\n% norm - 1/0 = do/don't normalize the eigvec's to be equivariant \n% {def|0 -> no normalization}\n% Outputs:\n% pc - the principal components, i.e. >> inv(eigvec)*data = pc;\n% eigvec - the inverse weight matrix (=eigenvectors). >> data = eigvec*pc; \n% sv - the singular values (=eigenvalues)\n%\n% Author: Colin Humphries, CNL / Salk Institute, 1997\n%\n% See also: runica()\n\n% Copyright (C) Colin Humphries, CNL / Salk Institute, Aug, 1997\n%\n% This program is free software; you can redistribute it 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/31/00 renamed runpca() and improved usage message -sm\n% 01-25-02 reformated help & license, added links -ad \n\nfunction [pc,M,S] = runpca(data,N,norm)\n\nBIG_N = 50; % for efficiency, switch to sdvs() when BIG_N<=N or N==rows\n\nif nargin < 1\n help runpca\n return\nend\n\nrows = size(data,1);\n\n% remove the mean\nfor i = 1:rows\n data(i,:) = data(i,:) - mean(data(i,:));\nend\n\nif nargin < 3\n norm = 0;\nelseif isempty(norm)\n norm = 0;\nend\n\nif nargin < 2\n N = 0;\nend\nif isempty(N)\n N = 0;\nend\n\n\nif N == 0 | N == rows\n N = rows;\n [U,S,V] = svd(data',0); % performa SVD\n if norm == 0\n pc = U';\n M = (S*V')';\n else % norm\n pc = (U*S)';\n M = V;\n end\nelse\n if N > size(data,1)\n error('N must be <= the number of rows in data.')\n end\n %if N <= BIG_N | N == rows\n %[U,S,V] = svd(data',0);\n %else\n [U,S,V] = svds(data',N);\n %end\n if norm == 0\n pc = U';\n M = (S*V')';\n else % norm\n pc = (U*S)';\n M = V;\n end \n %if N > BIG_N & N < rows\n %pc = pc(1:N,:);\n %M = M(:,1:N);\n %end\nend\n%S = diag(S(1:N,1:N));\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/miscfunc/runpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7819308531026794}} {"text": "% Thanks for Carlos Lopez for this file and many other enhancements to the mp toolbox.\n%quick and dirty tests\nprecision=1000;%notice that tol~=(.5)^precision;\na42=mp(rand(4,2),precision);%It will be nice to use mprand, but it doesn't work\nb42=mp(rand(4,2),precision);\n\n%2) direct/inverse pairs\nc_mp=norm(asin(sin(a42))-a42);disp(['2.1 sin/asin' setstr(9) num2str(c_mp)])\nc_mp=norm(acos(cos(a42))-a42);disp(['2.2 cos/acos' setstr(9) num2str(c_mp)])\nc_mp=norm(atan(tan(a42))-a42);disp(['2.3 tan/atan' setstr(9) num2str(c_mp)])\nc_mp=norm(asinh(sinh(a42))-a42);disp(['2.4 sinh/asinh' setstr(9) num2str(c_mp)])\nc_mp=norm(acosh(cosh(a42))-a42);disp(['2.5 cosh/acosh' setstr(9) num2str(c_mp)])\nc_mp=norm(atanh(tanh(a42))-a42);disp(['2.6 tanh/atanh' setstr(9) num2str(c_mp)])\nc_mp=norm(exp(log(a42))-a42);disp( ['2.7 exp/log ' setstr(9) num2str(c_mp)])\nc_mp=norm(sqrt(a42.^2)-a42);disp( ['2.8 sqrt/^2 ' setstr(9) num2str(c_mp)])\n\n%4) Catastrophic cancellation \nz=sqrt(117)-sqrt(116);zExact=1/(sqrt(117)+sqrt(116));\ndisp('4.1 Improvement in the catastrophic cancellation of sqrt(117)-sqrt(116)')\ndisp([setstr(9) 'Standard double precision:' num2str(abs(z/zExact-1)) ])\nfor precision=300:100:1000\n zmp=sqrt(mp(117,precision))-sqrt(mp(116,precision));zmpExact=1/(sqrt(mp(117,precision))+sqrt(mp(116,precision)));\n disp([setstr(9) 'Multiple precision = ' num2str(precision) ':' num2str(abs((zmp/zmpExact-1)))])\nend\n\ndisp('4.2 Accuracy of tan(pi/4)-1')\nfor precision=300:100:1000\n zmp=mp('pi',precision)/4;\n disp([setstr(9) 'Multiple precision = ' num2str(precision) ':' num2str(((tan(zmp)-1)))])\nend\ndisp('4.3 Accuracy of 4*atan2(-1,1)+pi')\nfor precision=300:100:1000\n zmp=mp('pi',2*precision);%Request a higher precision pi in order to compare\n one=mp(1,precision);\n disp([setstr(9) 'Multiple precision = ' num2str(precision) ':' ...\n num2str(((atan2(-one,one)*4+zmp)))])\nend\n\n%5) Test matrix; we will only test that the accuracy \n%of an exact inverse times the matrix is closer to the identity in mp rather than in double\nn=14;\ndisp(['5.1 Hilbert matrix and its exact inverse.'])\ndisp([' norm in double: ' num2str([norm(hilb(n)*invhilb(n)-eye(n))])])\nfor precision=300:100:1000\n mp_set_defaults(precision);\n %5.1 Hilbert\n one=mp(1);\n \n J = 1:n;\n J = J(ones(n,1),:);\n I = J';\n E = mp(ones(n,n));\n mpHilb = E./(I+J-one);\n \n %Now the inverse; this is a slightly modified version of invhilb.m to produce mp values\n p = n;\n H = mp(zeros(n,n));\n for k = 1:n\n i=mp(k);\n if k > 1, p = ((n-i+one)*p*(n+i-one))/(k-one)^2; end\n r = p*p;\n H(k,k) = r/(2*i-one);\n for j = i+1:n\n % r = -((n-j+one)*r*(n+j-one))/(j-one)^2;\n num = -((n-j+one)*r*(n+j-one));\n den= (j-one)^2;\n r = num/den;\n H(k,j) = r/(i+j-one);\n H(j,k) = r/(i+j-one);\n end\n end\n disp(['precision=' num2str(precision) ':' setstr(9) num2str(norm(H*mpHilb-eye(n)))]);\nend\n%check also some auxiliary functions (unrelated with precision!)\nX = mp([2 8 4;7 3 9]); \n%see \"help min\" for full documentation\nif all(min(X,[],1) == [2 3 4]), disp('Test 6.1 passed'), else, disp('Test 6.1 failed'),end\nif all(min(X,[],2) == [2;3]), disp('Test 6.2 passed'), else, disp('Test 6.2 failed'),end\nif all(min(X,5)==[2 5 4;5 3 5]), disp('Test 6.3 passed'), else, disp('Test 6.3 failed'),end\n\nif all(max(X,[],1)==[7 8 9]), disp('Test 6.4 passed'), else, disp('Test 6.4 failed'),end\nif all(max(X,[],2)==[8;9]), disp('Test 6.5 passed'), else, disp('Test 6.5 failed'),end\nif all(max(X,5)==[5 8 5;7 5 9]),disp('Test 6.6 passed'), else, disp('Test 6.6 failed'),end\n\nX = mp([0 1 2;3 4 5]);\nif all(sum(X,1) == [3 5 7]), disp('Test 6.7 passed'), else, disp('Test 6.7 failed'),end\nif all(sum(X,2) == [ 3;12]), disp('Test 6.8 passed'), else, disp('Test 6.8 failed'),end\n\nX = mp([3 7 5;0 4 2]);\nif all(sort(X,1) == [0 4 2;3 7 5] ), disp('Test 6.9 passed'), else, disp('Test 6.9 failed'),end\nif all(sort(X,2) == [3 5 7;0 2 4] ), disp('Test 6.10 passed'), else, disp('Test 6.10 failed'),end\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/mp_TESTING2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7817707907902021}} {"text": "function [v,usediters] = projfunc( s, k1, k2, nn )\n\n% Solves the following problem:\n% Given a vector s, find the vector v having sum(abs(v))=k1 \n% and sum(v.^2)=k2 which is closest to s in the euclidian sense.\n% If the binary flag nn is set, the vector v is additionally\n% restricted to being non-negative (v>=0).\n% \n% Written 2.7.2004 by Patrik O. Hoyer\n%\n \n% Problem dimension\nN = length(s);\n\n% If non-negativity flag not set, record signs and take abs\nif ~nn,\n isneg = s<0;\n s = abs(s);\nend\n\n% Start by projecting the point to the sum constraint hyperplane\nv = s + (k1-sum(s))/N; \n\n% Initialize zerocoeff (initially, no elements are assumed zero)\nzerocoeff = [];\n\nj = 0;\nwhile 1,\n\n % This does the proposed projection operator\n midpoint = ones(N,1)*k1/(N-length(zerocoeff)); \n midpoint(zerocoeff) = 0;\n w = v-midpoint;\n a = sum(w.^2); \n b = 2*w'*v;\n c = sum(v.^2)-k2;\n alphap = (-b+real(sqrt(b^2-4*a*c)))/(2*a); \n v = alphap*w + v;\n \n if all(v>=0),\n\t% We've found our solution\n\tusediters = j+1;\n\tbreak;\n end\n \n j = j+1;\n \n % Set negs to zero, subtract appropriate amount from rest\n zerocoeff = find(v<=0);\n v(zerocoeff) = 0;\n tempsum = sum(v);\n v = v + (k1-tempsum)/(N-length(zerocoeff));\n v(zerocoeff) = 0;\n \nend\n\n% If non-negativity flag not set, return signs to solution\nif ~nn,\n v = (-2*isneg + 1).*v;\nend\n\n% Check for problems\nif max(max(abs(imag(v))))>1e-10,\n error('Somehow got imaginary values!');\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/sparse/sparse_auxiliary/projfunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7817618251990618}} {"text": "function uv=spherAng2Uv(azEl,systemType,includeW,Ms,Muv)\n%%SPHERANG2UV Convert azimuth and elevation in spherical coordinates into a\n% [u;v] or [u;v;w] direction cosine vector in 3D. Direction\n% cosines u and v are the first two elements of a unit vector\n% in 3D.\n%\n%INPUTS: azEl A 2XN set of N points in [azimuth;elevation] in radians to\n% convert to direction cosines.\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. \n% Elevation is measured up from the x-y plane (towards the\n% z-axis). This is consistent with common spherical\n% coordinate systems for specifying longitude (azimuth) and\n% geocentric latitude (elevation).\n% 1 Azimuth is measured counterclockwise from the z-axis in the\n% z-x plane. Elevation is measured up from the z-x plane\n% (towards the y-axis). This is consistent with some spherical\n% coordinate systems that use the z-axis as the boresight\n% direction of the radar.\n% 2 This is the same as 0 except instead of being given\n% elevation, one is given 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% includeW An optional boolean value indicating whether a third direction\n% cosine component should be included. The u and v direction\n% cosines are two parts of a 3D unit vector. Generally, one might\n% assume that the target is in front of the sensor, so the third\n% component would be positive and is not needed. However, the\n% third component can be included if ambiguity exists. The\n% default if this parameter is omitted or an empty matrix is\n% passed is false.\n% Ms,Muv If either the spherical coordinate system or the u-v coordinate\n% system is rotated compared to the global Cartesian coordinate\n% system, these optional 3X3 matrices provide the rotations. Ms\n% is a 3X3 matrix to go from the alignment of a global\n% Cartesian coordinate system to that in which the spherical\n% coordinates are computed. Similarly, Muv is a rotation matrix\n% to go from the alignment of a global Cartesian cordinate system\n% to that in which the u-v(-w) coordinates are computed. If\n% either of these in omitted or an empty matrix is passed, then\n% the missing one is replaced with the identity matrix.\n%\n%OUTPUTS: uv A 2XN (without w) or 3XN (with w) set of direction cosines\n% values corresponding to the specified angles.\n%\n%Direction cosines and spherical coordinate systems are discussed in [1].\n%\n%EXAMPLE:\n%In this example, a spherical value is converted to uv coordiantes and then\n%back, demonostrating the consistency of the functions spherAng2Uv and\n%uv2SpherAng. The relative error should be about zero.\n% zSpher=[0.4;0.7];\n% systemType=3;\n% includeW=true;\n% Ms=Euler2Ang2RotMat(0.1,0.2,'xy');\n% Muv=Euler1Ang2RotMat(0.25,'z');\n% convBack=uv2SpherAng(spherAng2Uv(zSpher,systemType,includeW,Ms,Muv),systemType,Ms,Muv);\n% relErr=max(abs((convBack-zSpher)./zSpher))\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%June 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(Muv))\n Muv=eye(3,3);\nend\n\nif(nargin<4||isempty(Ms))\n Ms=eye(3,3);\nend\n\nif(nargin<3||isempty(includeW))\n includeW=false; \nend\n\nif(nargin<2||isempty(systemType))\n systemType=0;\nend\n\nazimuth=azEl(1,:);\nelevation=azEl(2,:);\n\nif(systemType==2)\n elevation=pi/2-elevation;\n systemType=0;\nelseif(systemType==3)\n azimuth=pi/2-azimuth;\n systemType=0;\nend\n\nswitch(systemType)\n case 0\n uv=Muv*Ms'*[cos(azimuth).*cos(elevation);\n sin(azimuth).*cos(elevation);\n sin(elevation)];\n case 1\n uv=Muv*Ms'*[sin(azimuth).*cos(elevation);\n sin(elevation);\n cos(azimuth).*cos(elevation)];\n otherwise\n error('Invalid system type specified.')\nend\n\nif(includeW==false)\n uv=uv(1: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/spherAng2Uv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7817599971108228}} {"text": "%% Example 8.6: Simulating from a trigonometric nonlinear SDE\n%\n% Copyright: \n% 2018 - Simo Särkkä and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%% Gaussian approximation\n\n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',1);\n rand('state',1);\n end\n\n % Parameters\n tspan = 0:1:10;\n\n % The model\n f = @(x,t) -(1/10)^2*sin(x).*cos(x).^3;\n L = @(x,t) 1/10*cos(x).^2;\n \n % The derivatives\n df = @(x,t) -1/100*cos(x).^2.*(2*cos(2*x)-1);\n ddf = @(x,t) 1/100*(sin(2*x) + 2*sin(4*x));\n dL = @(x,t) -1/5*sin(x).*cos(x);\n ddL = @(x,t) -1/5*cos(2*x);\n \n % Exact solution\n solfun = @(wt,x0) atan(1/10*wt +tan(x0));\n\n % Intial\n x0 = 1;\n\n \n%% Sample \n\n x = zeros(1,10000);\n xem = x;\n xw20 = x;\n xw20g = x;\n \n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',1);\n rand('state',1);\n end\n \n for j=1:size(x,2)\n \n % Use Euler-Maruyama\n foo = eulermaruyama_weak(f,L,tspan,x0,1);\n xem(:,j) = foo(:,end);\n \n % Report\n if rem(j,100)==0, j, end\n \n end\n \n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',1);\n rand('state',1);\n end\n \n for j=1:size(x,2)\n \n % Weak order 2.0\n foo = w20scalar({f,df,ddf},{L,dL,ddL},tspan,x0,1,false);\n xw20(:,j) = foo(:,end);\n \n % Report\n if rem(j,100)==0, j, end\n \n end\n \n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',1);\n rand('state',1);\n end\n \n for j=1:size(x,2)\n\n % Weak order 2.0 (Gaussian increments)\n foo = w20scalar({f,df,ddf},{L,dL,ddL},tspan,x0,1,true);\n xw20g(:,j) = foo(:,end);\n \n % Store\n x(:,j) = foo(:,end);\n \n % Report\n if rem(j,100)==0, j, end\n \n end\n \n \n%% Visualize\n \n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',1);\n rand('state',1);\n end\n\n % Samples from the exact solution\n xe = solfun(sqrt(tspan(end))*randn(1,200000),x0); \n \n % Bins\n nbins = 64;\n t = linspace(min(xe),max(xe)+.1,nbins);\n \n figure(2); clf; hold on\n\n % Show solution\n n = histc(xe,t);\n fill(t,n/numel(xe),1,'FaceColor',[.7 .7 .7],'EdgeColor',[.7 .7 .7])\n \n % Show solution w2.0\n n = histc(xw20,t);\n stairs(t-(t(2)-t(1))/2,n/numel(xw20),'-k')\n \n % Limits\n xlim([.35 1.25])\n lims = ylim;\n \n % Label\n xlabel('$x$')\n \n % Ticks\n set(gca,'XTick',0:.2:1.2)\n \n\n figure(3); clf; hold on\n\n % Show solution\n n = histc(xe,t);\n fill(t,n/numel(xe),1,'FaceColor',[.7 .7 .7],'EdgeColor',[.7 .7 .7])\n \n % Show solution w2.0 (Gaussian increments)\n n = histc(xw20g,t);\n stairs(t-(t(2)-t(1))/2,n/numel(xw20g),'-k')\n \n % Limits\n %xlim([min(t) max(t)])\n xlim([.35 1.25])\n ylim(lims)\n \n % Show legend\n legend('Exact','Weak order $2.0$')\n \n % Label\n xlabel('$x$')\n \n % Ticks\n set(gca,'XTick',0:.2:1.2)\n \n", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch08_ex06_weak_itotaylor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7817599935206937}} {"text": "function [lambda,v] = eig3(M,a12,a13,a22,a23,a33,varargin)\n% eigenvalue and vectors of a symmetric 3x3 matrix\n%\n% Syntax\n%\n% lambda = eig3(M)\n%\n% lambda = eig3(a11,a12,a13,a22,a23,a33)\n%\n%\n% [v,lambda] = eig3(a11,a12,a13,a22,a23,a33)\n%\n% Input\n% M - array of symmetric 3x3 matrix\n% a11, a12,a13,a22,a23,a33 - vector of matrix elements\n%\n% Output\n% lambda - eigen values\n% v - eigen vectors\n%\n\n% get input\nif nargin == 1\n a11 = M(1,1,:); a12 = M(1,2,:); a13 = M(1,3,:);\n a22 = M(2,2,:); a23 = M(2,3,:); a33 = M(3,3,:);\nelse\n a11 = M;\nend\n\ns = size(a11);\n\n% input should be column vectors\na11 = a11(:).'; a12 = a12(:).'; a13 = a13(:).';\na22 = a22(:).'; a23 = a23(:).'; a33 = a33(:).';\n\n% Given a real symmetric 3x3 matrix A, compute the eigenvalues\np1 = a12.^2 +a13.^2 + a23.^2;\n\nq = (a11 + a22 + a33)/3;\np2 = (a11 - q).^2 + (a22 - q).^2 + (a33 - q).^2 + 2 * p1;\np = sqrt(p2 / 6);\n\n%r = det(A-q*Id) / 2 / p^3;\nr = (a11-q) .* ( (a22-q) .* (a33-q) - a23.^2) + ...\n a12 .* (a13 .* a23 - a12 .* (a33-q)) + ...\n a13 .* (a12 .* a23 - (a22-q) .* a13);\nr = r / 2 ./ p.^3;\n\n% In exact arithmetic for a symmetric matrix -1 <= r <= 1\n% but computation error can leave it slightly outside this range.\nphi = acos(r) / 3;\nphi(r <= -1) = pi / 3;\nphi(r >= 1) = 0;\n\n% the eigenvalues satisfy eig3 <= eig2 <= eig1\nlambda = zeros(3,numel(a11));\nlambda(1,:) = q + 2 * p .* cos(phi + (2*pi/3));\nlambda(3,:) = q + 2 * p .* cos(phi);\nlambda(2,:) = 3 * q - lambda(1,:) - lambda(3,:); % since trace(A) = eig1 + eig2 + eig3\n\n\nif nargout > 1\n \n % this is only required for matlab versions prior to 2015\n b11 = repmat(a11,3,1); b12 = repmat(a12,3,1); b13 = repmat(a13,3,1);\n b22 = repmat(a22,3,1); b23 = repmat(a23,3,1); b33 = repmat(a33,3,1);\n \n v = vector3d(b12 .* b23 - b13 .* (b22 - lambda),...\n b13 .* b12 - (b11 - lambda) .* b23,...\n (b11 - lambda) .* (b22 - lambda) - b12 .* b12,'antipodal');\n \n v = v.normalize;\n \n % fallback for special cases\n % TODO: this should be done better\n id = ~(abs(det(v(1,:),v(2,:),v(3,:))) > (1 - 1e-5)) | isnan(lambda(1,:)); \n x = v.x; y = v.y; z = v.z;\n for k = find(id)\n \n [V,l] = eig([a11(k) a12(k) a13(k);...\n a12(k) a22(k) a23(k); ...\n a13(k) a23(k) a33(k)]);\n \n x(:,k) = V(1,:); y(:,k) = V(2,:); z(:,k) = V(3,:);\n lambda(:,k) = diag(l);\n \n end\n v.x = x; v.y = y; v.z = z;\n \n %a1 = vector3d(a11-lambda(1),a12,a13);\n %a2 = vector3d(a12,a22-lambda(1),23);\n %a3 = vector3d(a13,a23,33-lambda(1));\n \n %cross(a2,a3)\n\n % return only the largest eigen vector\n if check_option(varargin,'largest'), v = reshape(v(3,:),s); end\n \n % for some reason Matlab eig function changes to order outputs if called\n % with two arguments - so we should do the same\n [lambda,v] = deal(v,lambda);\n \nend\n\nend\n\nfunction test\n\n% generate random symmetric 3x3 matrixes\nN = 10\na = rand(6,N);\n\ntic\n[V1,lambda1] = eig3(a(1,:),a(2,:),a(3,:),a(4,:),a(5,:),a(6,:));\ntoc\n\ntic\nlambda2 = zeros(3,N);\nV2 = vector3d.zeros(3,N)\nfor i = 1:N\n A = [a(1,i),a(2,i),a(3,i);a(2,i),a(4,i),a(5,i);a(3,i),a(5,i),a(6,i)];\n [V,lambda2(:,i)] = eig(A,'vector');\n V2(1,i) = vector3d(V(:,1));\n V2(2,i) = vector3d(V(:,2));\n V2(3,i) = vector3d(V(:,3));\nend\ntoc\n\nnorm(lambda1 - flipud(lambda2)) ./ N\nmax(angle(V1(:),V2(:)))\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/tools/math_tools/eig3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.781684139561711}} {"text": "function [dphi,dlambda,h] = togeod(a,finv,X,Y,Z)\n%TOGEOD Subroutine to calculate geodetic coordinates\n% latitude, longitude, height given Cartesian\n% coordinates X,Y,Z, and reference ellipsoid\n% values semi-major axis (a) and the inverse\n% of flattening (finv).\n\n% The units of linear parameters X,Y,Z,a must all agree (m,km,mi,ft,..etc)\n% The output units of angular quantities will be in decimal degrees\n% (15.5 degrees not 15 deg 30 min). The output units of h will be the\n% same as the units of X,Y,Z,a.\n\n% Copyright (C) 1987 C. Goad, Columbus, Ohio\n% Reprinted with permission of author, 1996\n% Fortran code translated into MATLAB\n% Kai Borre 03-30-96\n% Changed according to Matlab ver. 6.5.1, 9 February 2004\n\nh = 0;\ntolsq = 1.e-10;\nmaxit = 1000;\n% compute radians-to-degree factor\nrtd = 180/pi;\n% compute square of eccentricity\nif finv < 1.e-20\n esq = 0;\nelse \n esq = (2-1/finv)/finv; \nend\noneesq = 1-esq;\n% first guess\n% P is distance from spin axix\nP = sqrt(X^2+Y^2);\n% direct calculation of longitude\nif P > 1.e-20\n dlambda = atan2(Y,X)*rtd;\nelse\n dlambda = 0; \nend;\nif (dlambda < 0)\n dlambda = dlambda + 360;\nend\n% r is distance from origin (0,0,0)\nr = sqrt(P^2+Z^2);\nif r > 1.e-20\n sinphi = Z/r;\nelse\n sinphi = 0; \nend\ndphi = asin(sinphi);\n% initial value of height = distance from origin minus\n% approximate distance from origin to surface of ellipsoid\nif r < 1.e-20\n h = 0;\n return;\nend;\nh = r-a*(1-sinphi*sinphi/finv);\n% iterate\nfor i = 1:maxit\n sinphi = sin(dphi);\n cosphi = cos(dphi);\n % compute radius of curvature in prime vertical direction\n N_phi = a/sqrt(1-esq*sinphi*sinphi);\n % compute residuals in P and Z\n dP = P - (N_phi + h) * cosphi;\n dZ = Z - (N_phi*oneesq + h) * sinphi;\n % update height and latitude\n h = h+(sinphi*dZ+cosphi*dP);\n dphi = dphi+(cosphi*dZ-sinphi*dP)/(N_phi + h);\n % test for convergence\n if (dP*dP + dZ*dZ < tolsq)\n break;\n end\n \n % Not Converged--Warn user\n if i == maxit\n fprintf([' Problem in TOGEOD, did not converge in %2.0f',...\n ' iterations\\n'],i)\n end;\nend;\ndphi = dphi*rtd;\n%%%%%%%% end togeod.m %%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/togeod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7815838517757868}} {"text": "% KEYWORDs: normal log pdf\n% this program returns log of f(x)=normal(x; mean_par, variance_par) pdf function and its derivative,\n% the pdf f(x) is defined up to the normalization constant\n% USAGE: [log_function, log_function_prime]=log_normal_pdf(x, alpha, beta)\n% INPUTs: \"x\" is vector of argument values\n% \"function_parameters\" is a vector of parameters of function f(x), function_parameters(1)=mean\n% and function_parameters(2)=variance are parameters of the normal distribution\n% OUTPUTs: \"log_function\" is log[f(x)]\n% \"log_function_prime\" is (d/dx)log[f(x)]\n% NOTES: pdf is log-concave\n% Last modified on Jul 15, 2007\n\nfunction [log_function, log_function_prime]=log_normal_pdf(x, function_parameters)\n\nmean_par=function_parameters(1);\nvariance_par=function_parameters(2);\n\nlog_function=(-0.5/variance_par)*(x-mean_par).^2;\nlog_function_prime=(-1/variance_par)*(x-mean_par);\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/15610-random-number-generation-from-an-arbitrary-log-concave-generalized-pdf/log_normal_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7815838493617064}} {"text": "function [z,ze]=doubleLengthSum(x,xe,y,ye)\n%%DOUBLELENGTHSUM Given two doublelength values, which could, for example,\n% be returned by exactPairMult or exactPairSum, find their sum as\n% another doublelength value.\n%\n%INPUTS: x,xe A real doublelength floating point number. The exact number\n% is x+xe (added with infinite precision) and\n% abs(xe)<=abs(x+xe)*2^(-t)/(1+2^(-t)), where t is the number\n% of bits in the mantissa, which is 53, since it is assumed\n% that these values are floating point doubles.\n% y, ye A second real doublelength floating point number that should\n% be added to x,xe.\n%\n%OUTPUTS: z, ze The doublelength floating point number that is the sum of\n% (x,xe) and (y,ye). If the inputs satisfy the proper\n% splitting of the number into two parts, (the relation in\n% size between abs(xe) and abs(x+xe) and similarly for y and\n% ye), then this will also satisfy the splitting of the\n% numbers. This does not necessarily hold if denormalized\n% numbers are encountered.\n%\n%This function implements the Add2 algorithm of [1].\n%\n%Note that this assumes that the processor rounding mode has been set to\n%round to \"nearest,\" which is the default in Matlab, but which can be\n%changed using the function setProcRoundingMode.\n%\n%EXAMPLE:\n% [z,ze]=doubleLengthSum(1,1e-30,1e20,1e-1)\n%One gets z=1e20 and ze=1.1. The 1e-30 component is truncated away, because\n%it is too small to represent with two doubles. \n%\n%REFERENCES:\n%[1] T. J. Dekker, \"A Floating Point Technique for Extending the Available\n% Precision,\" Numerische Mathematik, vol. 18, no. 3, Jun. 1971, pp.\n% 224-242.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nr=x+y;\nif(abs(x)>abs(y))\n s=x-r+y+ye+xe;\nelse\n s=y-r+x+xe+ye;\nend\n\nz=r+s;\nze=r-z+s;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Accurate_Arithmetic/doubleLengthSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7815808840550078}} {"text": "function val=BesselI1RatioApprox(kappa,algorithm)\n%%BESSELI1RATIOAPPROX Approximate the ratio of modified Bessel functions of\n% the first kind of the form x=I_{1}(kappa)/I_{0}(kappa).\n% For a more exact solution, use the function BesseliRatio,\n% which can also handle different subscripts (orders) for the\n% modified Bessel functions of the first kind.\n%\n%INPUTS: kappa The real argument of the modified Bessel function of the\n% first kind kappa>=0.\n% algorithm A parameter selecting the approximation that is used.\n% Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) Use\n% the approximation used in Equations 8 and 10 of [1].\n% Equation 8 in [1] is the first two terms of an expansion\n% given on page 290 of [2].\n% 1 Use the approximations in Equations 5 and 7 of [3].\n% Equation 5 of [3] is related to a Taylor series expansion\n% given on page 289 of [2].\n%\n%OUTPUTS: x An approximation to the ratio I_{1}(kappa)/I_{0}(kappa).\n%\n%REFERENCES:\n%[1] G. Stienne, S. Reboul, M. Azmani, J. B. Choquel, and M. Benjelloun, A\n% multi-temporal multi-sensor circular fusion filter,\" Information\n% Fusion, vol. 18, pp. 86-100, Jul. 2014.\n%[2] S. R. Jammalamadaka and A. SenGupta, Topics in Circular Statistics.\n% Singapore: World Scientific, 2001.\n%[3] G. Stienne, S. Reboul, J. B. Choquel, and M. Benjelloun, \"Circular\n% data processing tools applied to a phase open loop architecture for\n% multi-channel signals tracking,\" in Position Location and Navigation\n% Symposium, Myrtle Beach, SC, 23-26 Apr. 2012, pp. 633-642.\n%\n%April 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(nargin<2||isempty(algorithm))\n algorithm=0; \n end\n \n switch(algorithm)\n case 0%The method of [1].\n if(kappa>=0.6)\n val=1-1/(2*kappa);\n else\n val=exp(-1/(2*kappa));\n end\n case 1\n if(kappa>=0.6)\n val=(1-3/(8*kappa)-15/(128*kappa^2))/(1+1/(8*kappa)+9/(128*kappa^2));\n else\n val=kappa/2;\n end\n otherwise\n error('Unknown Algorithm Specified.')\n end\n\nend\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/BesselI1RatioApprox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7815808795048526}} {"text": "function [r, s, t] = xyztorst(X, Y, Z)\n\n% function [r,s,t] = xyztorst(x, y, z)\n% Purpose : Transfer from (x,y,z) in equilateral tetrahedron\n% to (r,s,t) coordinates in standard tetrahedron\n\nv1 = [-1,-1/sqrt(3), -1/sqrt(6)]; v2 = [ 1,-1/sqrt(3), -1/sqrt(6)];\nv3 = [ 0, 2/sqrt(3), -1/sqrt(6)]; v4 = [ 0, 0/sqrt(3), 3/sqrt(6)];\n\n% back out right tet nodes\nrhs = [X';Y';Z'] - 0.5*(v2'+v3'+v4'-v1')*ones(1,length(X));\nA = [0.5*(v2-v1)',0.5*(v3-v1)',0.5*(v4-v1)'];\nRST = A\\[rhs];\nr = RST(1,:)'; s = RST(2,:)'; t = RST(3,:)';\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/xyztorst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7815622011966388}} {"text": "function [h,g,a,info]=wfilt_lemarie(N)\n%WFILT_LEMARIE Battle and Lemarie filters\n% Usage: [h,g,a]=wfilt_lemarie(N)\n%\n% Input parameters:\n% N : Filter length, must be even.\n%\n% `[h,g,a]=wfilt_lemarie(N)` calculates $N$ (even) truncated coeficients \n% of orthonormal Battle-Lemarie wavelets. Filter coefficients are obtained \n% by frequency domain sampling and trunctating the impulse response.\n% Due to the truncation, the filterbank might not achieve a perfect \n% reconstruction. The filetrs are included nevertheless since they were\n% the original ones used in the first MRA paper. \n%\n% Examples:\n% ---------\n% :::\n% wfiltinfo('lemarie50');\n%\n% References: mallat89atheory\n\n% Original copyright goes to:\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n\nif rem(N,2)~=0\n error('%s: Filter length must be even.',upper(mfilename));\nend\n\nnum_coefs = N;\nL = 1024;\nH = wfreq_lemarie(L);\nhh=real(ifft(H{1},L));\nhh=[ hh(L-floor(num_coefs/2)+1:L) hh(1:ceil(num_coefs/2))];\nhh=hh/norm(hh);\n\ng{1} = (hh);\ng{2} = -(-1).^(1:length(hh)).*g{1}(end:-1:1);\n\n\ng = cellfun(@(gEl) struct('h',gEl,'offset',-floor(numel(gEl)/2)),g,'UniformOutput',0);\n\nh = g;\na= [2;2];\ninfo.istight = 1;\n\n\nfunction [H,G] = wfreq_lemarie(L)\n%WFREQ_LEMARIE Battle and Lemarie filters frequency resp. sampling\n% Usage: [H,G]=wfreq_lemarie(L)\n%\n% Input parameters:\n% N : Number of samples of the frequency response.\n%\n% `[H,G]=wfreq_lemaire(L)` calculates $L$ samples of the Battle and\n% Lemarie filters frequency responses.\n%\n% References: mallat89atheory\n%\n%\n\n% Original copyright goes to:\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n\n\n% frequency axis\nw=[0:2*pi/L:2*pi*(1-1/L)];\nw(1)=eps;\nw(L/2+1)=w(L/2+1)+1e-15;\n\n% calculation of frequency response of analysis lowpass filter \nnum=0;den=0;\nK=36;\nfor k=-K:K,\n\tnum=1./((w+2*pi*k).^8)+num;\n\tden=1./((2*w+2*pi*k).^8)+den;\nend\nH = cell(2,1);\nH{1}=sqrt(num./(2.^8*den));\nH{1}(1)=1;\n\nH{2} = fftshift(H{1});\nG = cell(2,1);\nG{1} = fliplr(H{1});\nG{2} = fliplr(H{2});\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_lemarie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7815519028621258}} {"text": "function value = r8mat_norm_l1 ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8MAT_NORM_L1 returns the matrix L1 norm of an R8MAT.\n%\n% Discussion:\n%\n% The matrix L1 norm is defined as:\n%\n% value = max ( 1 <= J <= N ) sum ( 1 <= I <= M ) abs ( A(I,J) ).\n%\n% The matrix L1 norm is derived from the vector L1 norm, and\n% satisifies:\n%\n% vec_norm_l1 ( A * x ) <= mat_norm_l1 ( A ) * vec_norm_l1 ( x ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows in A.\n%\n% Input, integer N, the number of columns in A.\n%\n% Input, real A(M,N), the matrix whose L1 norm is desired.\n%\n% Output, real VALUE, the L1 norm of A.\n%\n value = 0.0;\n\n for j = 1 : n\n value = max ( value, sum ( abs ( a(1:m,j) ) ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_norm_l1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8705972801594707, "lm_q1q2_score": 0.781531070189321}} {"text": "function value = i4_is_prime ( n )\n\n%*****************************************************************************80\n%\n%% I4_IS_PRIME reports whether an integer is prime.\n%\n% Discussion:\n%\n% A simple, unoptimized sieve of Erasthosthenes is used to\n% check whether N can be divided by any integer between 2\n% and SQRT(N).\n%\n% Note that negative numbers, 0 and 1 are not considered prime.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the integer to be tested.\n%\n% Output, logical VALUE, is TRUE if N is prime, and FALSE\n% otherwise.\n%\n if ( n <= 0 )\n value = 0;\n return\n end\n\n if ( n == 1 )\n value = 0;\n return\n end\n\n if ( n <= 3 )\n value = 1;\n return\n end\n\n nhi = floor ( sqrt ( n ) );\n\n for i = 2 : nhi\n if ( mod ( n, i ) == 0 )\n value = 0;\n return\n end\n end\n\n value = 1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/i4_is_prime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.781505875774769}} {"text": "function P = legendrepol(N, a, b)\n%-------------------------------------------------------------------------\n%\n% P = legendrepol(N)\n%\n% returns the Legendre polynomials up to order N, orthogonal on\n% the interval [-1,1]. Each row contain the polynomial coefficients in \n% descending order, i.e. the first row is P0 = [0 0 .... 1].\n%\n% P = legendrepol(N),xmin,xmax)\n% \n% returns the Legendre polynomial orthogonal on [xmin, xmax].\n%-------------------------------------------------------------------------\n\n% T. Wik, April 2012\n\n% L is the Legendre polynomials orthogonal on (-1,1):\nif N<1\n\tL = 1;\nelse\n\tL \t\t = zeros(N+1,N+1);\n\tL(1,N+1) = 1; % L0\n\tL(2,N:N+1) = [1 0]; % L1\n for n=1:N-1 % L2 to LN \n \tL(n+2,N-n:N+1) \t= 1/(n+1)* ...\n \t ((2*n+1)*[L(n+1,N+1-n:N+1) 0]-n*[0 0 L(n,N+2-n:N+1)]);\n end\nend\n\nif nargin == 3\n if a > b\n error('legendrepol:wrongArguments','xmin > xmax !')\n end\n% Transform such that P is orthogonal on (xmin,xmax):\n P = zeros(N+1);\n A = zeros(N+1);\n\n for n = 1:N+1\n A(end-n+1,end-n+1:end) = binomial(n-1,2/(b-a),-(a+b)/(b-a));\n Lambda = diag(L(n,:));\n P(n,:) = sum(Lambda*A);\n end\nelseif nargin == 1\n P = L;\nelse\n error('legendrepol:wrongArguments','Use one or three arguments!')\nend \n \n \n\n\nfunction P = binomial(n,a,b)\n%------------------------------------------------------\n%\n% function P = binomial(n,a,b)\n%\n% Returns the polynomial coefficients p(i) for\n%\n% P(x) = (ax + b)^n\n% = p(1)x^n + p(2)x^(n-1) + ... + p(n)x + p(n+1)\n%\n%------------------------------------------------------\n\n% First binomial coefficients for (x+1)^n\n\nif n==0, P=1; return, end\np = zeros(n,n+1);\n\np(1,1:2) = [1 1];\n\nfor j = 2:n\n p(j,1) = 1;\n for k = 2:n\n p(j,k) = p(j-1,k-1) + p(j-1,k);\n end\n p(j,n+1) = 1;\nend\n\n% Adjust for a and b\n\nfor k = 1:n+1;\n P(k) = p(n,k)*a^(n-k+1)*b^(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/36017-legendre-polynomials/legendrepol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7814985704809909}} {"text": "function [MSC]=coherence_MVDR(x1,x2,L,K);\n\n%% This program computes the coherence function between 2 signals \n%% x1 and x2 with the MVDR method.\n%% This algorithm is based on the paper by the same authors:\n%% J. Benesty, J. Chen, and Y. Huang, \"A generalized MVDR spectrum,\" \n%% IEEE Signal Processing letters, vol. 12, pp. 827-830, Dec. 2005.\n\n%% x1, first signal vector of length n\n%% x2, second signal vector of length n\n%% L is the length of MVDR filter or window length\n%% K is the resolution (the higher K, the better the resolution)\n\n%initialization\nxx1 = zeros(L,1);\nxx2 = zeros(L,1);\nr11 = zeros(L,1);\nr22 = zeros(L,1);\nr12 = zeros(L,1);\nr21 = zeros(L,1);\n\n%construction of the Fourier Matrix\nF = zeros(L,K);\nl = [0:L-1]';\nf = exp(2*pi*l*j/K);\nfor k = 0:K-1\n F(:,k+1) = f.^k;\nend\nF = F/sqrt(L);\n\n%number of samples, equal to the lenght of x1 and x2\nn = length(x1);\n\nfor i = 1:n\n xx1 = [x1(i);xx1(1:L-1)];\n xx2 = [x2(i);xx2(1:L-1)];\n r11 = r11 + xx1*conj(xx1(1));\n r22 = r22 + xx2*conj(xx2(1));\n r12 = r12 + xx1*conj(xx2(1));\n r21 = r21 + xx2*conj(xx1(1));\nend\nr11 = r11/n;\nr22 = r22/n;\nr12 = r12/n;\nr21 = r21/n;\n%\nR11 = toeplitz(r11);\nR22 = toeplitz(r22);\nR12 = toeplitz(r12,conj(r21));\n%\n%for regularization\nDt1 = 0.01*r11(1)*diag(diag(ones(L)));\nDt2 = 0.01*r22(1)*diag(diag(ones(L)));\n%\nRi11 = inv(R11 + Dt1);\nRi22 = inv(R22 + Dt2);\nRn12 = Ri11*R12*Ri22;\n%\nSi11 = real(diag(F'*Ri11*F));\nSi22 = real(diag(F'*Ri22*F));\nS12 = diag(F'*Rn12*F);\n%\n%Magnitude squared coherence function\nMSC = real(S12.*conj(S12))./(Si11.*Si22);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9781-coherence-function/coherence_MVDR/coherence_MVDR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7814666237357616}} {"text": "function R = rotation_matrix(phi,dim,orientation)\n%ROTATION_MATRIX 3D rotation matrix\n%\n% Usage: R = rotation_matrix(phi,[dim,[orientation]])\n%\n% Input parameters:\n% phi - angle to rotate the given dim dimension vector / rad\n% dim - dimension to turn around (default: 3, z-axis)\n% orientation - orientation of the rotation, 'clockwise' or\n% 'counterclockwise' (default: 'counterclockwise')\n%\n% Output parameters:\n% R - 3x3 rotation matrix to apply to your vector to\n% rotate: R*y\n%\n%\n% ROTATION_MATRIX(phi,dimension,orientation) returns a rotation matrix R,\n% which is able to rotate a vector around the given dimension about phi.\n%\n% See also: sin, cos\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 = 3;\nnarginchk(nargmin,nargmax);\nisargscalar(phi)\nif nargin<3\n % Set defualt orientation of the rotation\n orientation = 'counterclockwise';\nend\nif nargin<2\n % set default rotation dimension to z-axis\n dim = 3;\nend\nisargchar(orientation);\nisargpositivescalar(dim);\n\n\n%% ===== Computation ====================================================\n% Rotation matrix (see: https://en.wikipedia.org/wiki/Rotation_matrix)\n% get single matrix entries\nr1 = cos(phi);\nr4 = cos(phi);\nif strcmp('counterclockwise',orientation)\n r2 = -sin(phi);\n r3 = sin(phi);\nelseif strcmp('clockwise',orientation)\n r2 = sin(phi);\n r3 = -sin(phi);\nelse\n error('%s: the given orientation \"%s\" is not known.', ...\n upper(mfilename),orientation);\nend\n% Fill up matrix to rotate around the given axis\nif dim==1\n\n R = [1 0 0; ...\n 0 r1 r2; ...\n 0 r3 r4];\nelseif dim==2\n R = [r1 0 r2; ...\n 0 1 0; ...\n r3 0 r4];\nelseif dim==3\n R = [r1 r2 0; ...\n r3 r4 0; ...\n 0 0 1];\nelse\n error('%s: dim has to be 1,2, or 3 and not %i',upper(mfilename),dim);\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_general/rotation_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7814311026035391}} {"text": "function [q,qd,q2d] = mixed_traj(t,C,A,B,w,N)\n% ---------------------------------------------------------------------\n% This function computes \"mixed trajectory\" meaning the trajectory\n% that consistes of finite fourier series and fifth order polynomial\n% Inputs:\n% t - time instants at which trajectory should be evaluated\n% C - coefficients of the fifth order polynomail\n% A - coeffincients of the sine in finite fourier series\n% B - coefficinets of the cosine in finitne fourier series\n% w - fundamental frequency\n% N - number of harmonics\n% ---------------------------------------------------------------------\n% finite fourier series\n[qh,qhd,qh2d] = fourier_series_traj(t,zeros(6,1),A,B,w,N);\n\n% fifth order polynomail trajectory\nqp = C(:,1) + C(:,2).*t + C(:,3).*t.^2 + C(:,4).*t.^3 + ...\n C(:,5).*t.^4 + C(:,6).*t.^5;\nqpd = C(:,2) + 2*C(:,3).*t + 3*C(:,4).*t.^2 + ...\n 4*C(:,5).*t.^3 + 5*C(:,6).*t.^4;\nqp2d = 2*C(:,3) + 6*C(:,4).*t + 12*C(:,5).*t.^2 + 20*C(:,6).*t.^3;\n\nq = qh + qp;\nqd = qhd + qpd;\nq2d = qh2d + qp2d;\n", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/trajectory_optmzn/mixed_traj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7814310954038105}} {"text": "function [max_val,ind] = mDmax(x)\n%MDMAX Largest component in a multidimensional matrix.\n% For a matrix X, MDMAX(X) is the largest element in X. \n%\n% [Y,I] = MDMAX(X) returns the indices of the maximum value in vector I.\n%\n% When X is complex, the maximum is computed using the magnitude\n% MAX(ABS(X)). In the case of equal magnitude elements, then the phase\n% angle MAX(ANGLE(X)) is used.\n%\n% NaN's are ignored when computing the maximum. When all elements in X\n% are NaN's, then the first one is returned as the maximum.\n%\n% Example: If X = [2 8 4; then mDmax(X) is 9,\n% 7 3 9]\n% and\n% [val,ind] = mDmax(X) returns val=9 and ind=[2 3]\n%\n% Note: The vector ind can be used to access elements from X using this\n% neat trick:\n% sub = num2cell(ind)\n% val = x(sub{:}); \n\n[max_val,position] = max(x(:));\nind = myind2sub(size(x),position);\n\n%--------------------------------------------------------------\nfunction ind = myind2sub(siz,ndx)\n\ndim = numel(siz);\nsub = cell(dim,1);\n[sub{:}] = ind2sub(siz,ndx);\nind = cell2mat(sub);\n\n% Old implementation\n% siz = double(siz);\n% \n% n = length(siz);\n% k = [1 cumprod(siz(1:end-1))];\n% for i = n:-1:1,\n% vi = rem(ndx-1, k(i)) + 1;\n% vj = (ndx - vi)/k(i) + 1;\n% ind(:,i) = vj;\n% ndx = vi;\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/37392-maximum-value-in-multidimensional-matrix/mDmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8791467675095292, "lm_q1q2_score": 0.7813494255752942}} {"text": "function x = pwPoly2(tGrid,xGrid,t)\n% x = pwPoly2(tGrid,xGrid,t)\n%\n% This function does piece-wise quadratic interpolation of a set of data.\n%\n% INPUTS:\n% tGrid = [1, 2*n-1] = time grid, knot idx = 1:2:end\n% xGrid = [m, 2*n-1] = function at each grid point in time\n% t = [1, k] = vector of query times (must be contained within tGrid)\n%\n% OUTPUTS:\n% x = [m, k] = function value at each query time\n%\n% NOTES: \n% If t is out of bounds, then all corresponding values for x are replaced\n% with NaN\n%\n\nnGrid = length(tGrid);\nif mod(nGrid-1,2)~=0 || nGrid < 3\n error('The number of grid-points must be odd and at least 3');\nend\n\n% Figure out sizes\nn = floor((length(tGrid)-1)/2);\nm = size(xGrid,1);\nk = length(t);\nx = zeros(m, k);\n\n% Figure out which segment each value of t should be on\nedges = [-inf, tGrid(1:2:end), inf];\n[~, bin] = histc(t,edges);\n\n% Loop over each quadratic segment\nfor i=1:n\n idx = bin==(i+1);\n if sum(idx) > 0\n gridIdx = 2*(i-1) + [1,2,3];\n x(:,idx) = quadInterp(tGrid(gridIdx),xGrid(:,gridIdx),t(idx));\n end\nend\n\n% Replace any out-of-bounds queries with NaN\noutOfBounds = bin==1 | bin==(n+2);\nx(:,outOfBounds) = nan;\n\nend\n\n\nfunction x = quadInterp(tGrid,xGrid,t)\n%\n% This function computes the interpolant over a single interval\n%\n% INPUTS:\n% tGrid = [1, 3] = time grid\n% xGrid = [m, 3] = function grid\n% t = [1, p] = query times, spanned by tGrid\n%\n% OUTPUTS:\n% x = [m, p] = function at query times\n%\n\n% Rescale the query points to be on the domain [-1,1]\nt = 2*(t-tGrid(1))/(tGrid(3)-tGrid(1)) - 1; \n\n% Compute the coefficients:\na = 0.5*(xGrid(:,3) + xGrid(:,1)) - xGrid(:,2);\nb = 0.5*(xGrid(:,3)-xGrid(:,1));\nc = xGrid(:,2);\n\n% Evaluate the polynomial for each dimension of the function:\np = length(t);\nm = size(xGrid,1);\nx = zeros(m,p);\ntt = t.^2;\nfor i=1:m\n x(i,:) = a(i)*tt + b(i)*t + c(i);\nend\n\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/pwPoly/pwPoly2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7812455945761827}} {"text": "%\n% lellippi(phi, k, errtol)\n%\n% Inputs:\n%\n% phi Input angle vector size 1 or 1xN.\n% k Input parameter vector size 1 or 1xN.\n% n Input parameter vector size 1 or 1xN.\n% errtol Error tolerance for Carlson's algorithms.\n%\n% Matlab function to compute Legendre's (incomplete) elliptic integral \n% Pi(phi, k, n). Uses a vectorized implementation of Carlson's Duplication Algorithms \n% for symmetric elliptic integrals as found in \"Computing Elliptic \n% Integrals by Duplication,\" by B. C. Carlson, Numer. Math. 33, 1-16 (1979)\n% and also found in ACM TOMS Algorithm 577. Section 4 in the paper cited\n% here describes how to convert between the symmetric elliptic integrals\n% and Legendre's elliptic integrals.\n%\n% Returns NaN's for any argument values outside input range.\n%\n\nfunction f = lellippi(phi, k, n, errtol)\n% Argument checking for vectorization:\nlphi = length(phi);\nlk = length(k);\nln = length(n);\nerrflag = logical(0);\nif ( ~ ((lphi==lk) & (lphi==ln) & (lk==ln)) )\n if ( (lk==1) & (ln==1) )\n kvec = k * ones(1,lphi);\n nvec = n * ones(1,lphi);\n phivec = phi;\n elseif ( (lphi==1) & (ln==1) ) \n phivec = phi * ones(1,lk);\n nvec = n * ones(1,lk);\n kvec = k;\n elseif ( (lphi==lk) & (ln==1) )\n nvec = n * ones(1,lphi);\n kvec = k;\n phivec = phi;\n elseif ( (lphi==1) & (lk==1) )\n phivec = phi * ones(1,ln);\n kvec = k * ones(1,lk);\n nvec = n;\n elseif ( (lphi==ln) & (lk==1) )\n kvec = k * ones(1,lphi);\n phivec = phi;\n nvec = n;\n elseif ( (lk==ln) & (lphi==1) )\n phivec = phi * ones(1,lk);\n kvec = k;\n nvec = n\n else\n disp('Incompatible input vector dimensions in lellipf!');\n errflag = logical(1);\n end\nelse\n phivec = phi;\n kvec = k;\n nvec = n;\nend\nif (~errflag)\n snphi = sin(phivec);\n csphi = cos(phivec);\n snphi2 = snphi.^2;\n csphi2 = csphi.^2;\n k2 = kvec.^2;\n y = 1.0 - k2.*snphi2;\n p = 1.0 + nvec .* snphi2;\n onesvec = ones(1,length(phivec));\n f = snphi .* rf(csphi2, y, onesvec, errtol) - ...\n nvec .* snphi .* snphi2 .* rj(csphi2, y, onesvec, p, errtol) / 3.0;\nelse\n f = NaN;\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/3705-ellipticintegrals-zip/Elliptic_Integrals/lellippi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7812455923141416}} {"text": "%KGAUSS Gaussian kernel\n%\n% K = KGAUSS(SIGMA) is a 2-dimensional Gaussian kernel of standard deviation\n% SIGMA, and centred within the matrix K whose half-width is H=2xSIGMA and\n% W=2xH+1.\n%\n% K = KGAUSS(SIGMA, H) as above but the half-width H is specified.\n%\n% Notes::\n% - The volume under the Gaussian kernel is one.\n%\n% See also KDGAUSS, KDOG, KLOG, ICONV.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nfunction m = kgauss(sigma, w)\n\n\n if nargin == 1,\n w = ceil(3*sigma);\n end\n ww = 2*w + 1;\n\n [x,y] = meshgrid(-w:w, -w:w);\n\n m = 1/(2*pi*sigma^2) * exp( -(x.^2 + y.^2)/2/sigma^2);\n\n % area under the curve should be 1, but the discrete case is only\n % an approximation, correct it\n %m = m / sum(m(:));\n\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/kgauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7812455869314466}} {"text": "function qwgw_test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests QWGW for the Jacobi weight.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n\n%\n% Set the quadrature interval and number of points.\n%\n a = -1.0;\n b = +1.0;\n n = 5;\n%\n% Set the weight function parameters.\n%\n alpha = 0.25;\n beta = 0.75;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST07:\\n' );\n fprintf ( 1, ' Compute points and weights for Gauss quadrature\\n' );\n fprintf ( 1, ' with the Jacobi weight w(x) = (1-x^2)^alpha*(1+x)^beta\\n' );\n fprintf ( 1, ' Order N = %d\\n', n );\n fprintf ( 1, ' ALPHA = %g\\n', alpha );\n fprintf ( 1, ' BETA = %g\\n', beta );\n fprintf ( 1, ' Interval = [%g,%g]\\n', a, b );\n%\n% Set the recursion coefficients.\n%\n aj = zeros ( n, 1 );\n bj = zeros ( n, 1 );\n\n for j = 1 : n\n jr = j;\n aj(j) = ( beta - alpha ) * ( beta + alpha ) ...\n / ( alpha + beta + 2.0 * jr - 2.0 ) ...\n / ( alpha + beta + 2.0 * jr );\n end\n\n for j = 1 : n - 1\n jr = j;\n bj(j) = 4.0 * jr * ( alpha + jr ) * ( beta + jr ) ...\n * ( alpha + beta + jr ) ...\n / ( ( alpha + beta + 2.0 * jr )^2 - 1.0 ) ...\n / ( alpha + beta + 2.0 * jr )^2;\n end\n bj(n) = 0.0;\n\n bj(1:n) = sqrt ( bj(1:n) );\n\n mu0 = 2.0 ^ ( alpha + beta + 1.0 ) ...\n * gamma ( alpha + 1.0 ) * gamma ( beta + 1.0 ) ...\n / gamma ( alpha + beta + 2.0 );\n%\n% Compute the points and weights.\n%\n [ x, w ] = sgqf ( n, aj, bj, mu0 );\n\n r8vec_print ( n, x, ' Abscissas:' );\n r8vec_print ( n, w, ' Weights:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_golub_welsch/qwgw_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7811058824670422}} {"text": "%% CUBEPOISSONQ1 Poisson equation in a CUBE domain using trilinear cube element \n%\n% cubePoissonQ1 computes trilinear finite element approximations of the\n% Poisson equation in the unit cube on a sequence of hex meshes obtained by\n% uniform refinement. It plots the approximation err vs the number of\n% degree of freedoms.\n% \n% See also \n% cubePoisson, cubePoissonP2\n% \n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all;\n\n%% Parameters \nmaxIt = 4; \nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\n\n%% Domain and pde\nh0 = 1.0/2.0;\ncube = [0 1 0 1 0 1];\n\npde = sincosdata3;\noption.solver = 'amg';\n% option.isoparametric = true;\n\n%% Finite Element Method \nerrL2 = zeros(maxIt,1); \nerrH1 = zeros(maxIt,1); \nerruIuh = zeros(maxIt,1);\nfor k = 1:maxIt\n [node,elem] = cubehexmesh(cube,h0/(2.0^k));\n bdFlag = setboundary3(node,elem,'Dirichlet','abs(z)>eps','Neumann','abs(z) 1, C(1:d-1) = {':,'}; end\n if d < n, C(d+1:n) = {',:'}; end\n C(d) = {'1:k'};\n S = ['(' [C{:}] ')'];\n mi = eval(['b' S]);\n if nargout > 1, loc = eval(['ix' S]); end\n end \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6307-kminima/kminima.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.78106768292481}} {"text": "function pdf = pareto_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% PARETO_PDF evaluates the Pareto PDF.\n%\n% Formula:\n%\n% PDF(X)(A,B) = B * A**B / X**(B+1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n% A <= X\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < A.\n% 0.0 < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < a )\n pdf = 0.0;\n else\n pdf = b * a^b / x^( b + 1.0 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/pareto_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.781067673086361}} {"text": "function y=evalSinCosSeries(c,cosX,sinX)\n%%EVALSINCOSSERIES Evaluate the cosine series\n% y=sum_{i=1}^Nc(i)*cos((i-1)*x)\n% or the sine series\n% y=sum_{i=1}^(N+1)c(i)*sin(i*x)\n% efficiently using Clenshaw summation.\n%\n%INPUTS: c An NX1 or a 1XN vector of the coefficients in the sum.\n% cosX The value cos(x). This value is always required. To evaluate\n% multiple sums at once, this can be a vector or a matrix.\n% sinX If this value is provided, it is sin(x) and the sum evaluated by\n% this function will be a sine series. Otherwise, if this\n% parameter is omitted or an empty matrix is passed, this function\n% will evaluate a cosine series. If this parameter is provided, it\n% must be the same size as cosX.\n%\n%OUTPUTS: y The value of the sum. If cosX was a matrix, then this will be a\n% matrix.\n%\n%This function chooses the correct parameters and calls the function\n%evalClenshawRecurSeries.\n%\n%EXAMPLE:\n% N=200;\n% c=rand(N,1);\n% x=2*pi*rand(4,4);\n% cosX=cos(x);\n% yF=evalSinCosSeries(c,cosX);\n% ySum=zeros(4,4);\n% for k=1:N\n% ySum=ySum+c(k)*cos((k-1)*x); \n% end\n% relativeError=max(max(abs(ySum-yF)./yF))\n% %This will typically be on the order of 1e-12 or less, due simply to\n% %finite precision differences.\n% %Similarly, if we wanted the sine series.\n% sinX=sin(x);\n% yF=evalSinCosSeries(c,cosX,sinX);\n% ySum=zeros(4,4);\n% for k=1:N\n% ySum=ySum+c(k)*sin(k*x); \n% end\n% relativeError=max(max(abs(ySum-yF)./yF))\n% %This will again be on the order of 1e-12 or less, due simply to finite\n% %precision differences.\n%\n%July 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nalphaVal=2*cosX;\nbetaVal=-1;\n\nif(nargin<3||isempty(sinX))\n %A cosine series.\n F0=ones(size(cosX));%=cos(0)\n F1=cosX;\n y=evalClenshawRecurSeries(c,alphaVal,betaVal,F0,F1);\nelse%A sine series\n F0=sinX;\n F1=2*sinX.*cosX;\n y=evalClenshawRecurSeries(c,alphaVal,betaVal,F0,F1);\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/evalSinCosSeries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7810365039286868}} {"text": "function cadj=ref_spreadadj_4(coef)\n%REF_SPREADADJ_4 Symbol of adjoint spreading function.\n% Usage: cadj=ref_spreadadj_4(c,number);\n%\n% Development version by FJ for comparison of different implementations\n% cadj=SPREADADJ(c) will compute the symbol cadj of the spreading \n% operator that is the adjoint of the spreading operator with symbol c. \n%\n% Improved implementation of the direct formula with higher memory\n% needs (but better speed)\n%\n% This implementation uses the same improvements as case 3, but \n% also avoid the use of loop by using matrix pointwise \n% multiplication, which improves the computation time, but also \n% requires more memory due to the contruction of the (L-1)x(L-1) \n% matrix temp\n%\n\nL=size(coef,1);\n\ncadj=zeros(L);\n \n% Proceesing for ii==0 or jj==0\ncadj(1,1)=conj(coef(1,1));\ncadj(2:end,1)=conj(coef(end:-1:2,1));\ncadj(1,2:end,1)=conj(coef(1,end:-1:2));\n\n% Processing for ii~=0 and jj~=0\n\n% Precomputation for exponential term\n\n% Optimization note : As said in note of case 3 ,we are computing \n% the Lth root of unity which have special properties and symetries \n% that could be exploited to highly reduce this computation\ntemp2=exp((-i*2*pi/L)*(0:L-1));\n\n% Optimization note : Here we are computing indexes for all the\n% exponential terms, which leads to a highly structured matrix\n% which strcture can be formalized (notably it is symetric) and\n% used to reduce the computation cost\ntemp=mod((1:L-1)'*(1:L-1),L)+1;\n\n\n% Optimization note : Finaly we construct the matrix containing all\n% the needed exponential terms. \n% This matrix is known as the DFT matrix and appears in the matrix \n% formulation of the dft, but in our case it is used for pointwise \n% multiplication instead of matrix mulitplication.\n% There might be optimized algorithms for the computation of this\n% matrix described in the context of fft.\ntemp=temp2(temp);\n\ncadj(2:L,2:L)=conj(coef(L:-1:2,L:-1:2)).*temp;\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/timing/ref_spreadadj_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.781000815132973}} {"text": "function pdf = dipole_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% DIPOLE_PDF evaluates the Dipole PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B) =\n% 1 / ( PI * ( 1 + X**2 ) )\n% + B**2 * ( ( 1 - X**2 ) * cos ( 2 * A ) + 2.0D+00 * X * sin ( 2 * A ) )\n% / ( PI * ( 1 + X )**2 )\n%\n% Densities of this kind commonly occur in the analysis of resonant\n% scattering of elementary particles.\n%\n% DIPOLE_PDF(X)(A,0) = CAUCHY_PDF(X)(A)\n% A = 0, B = 1 yields the single channel dipole distribution.\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% Reference:\n%\n% Robert Knop,\n% Algorithm 441,\n% ACM Transactions on Mathematical Software.\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% A is arbitrary, but represents an angle, so only 0 <= A <= 2 * PI\n% is interesting,\n% and -1.0D+00 <= B <= 1.0.\n%\n% Output, real PDF, the value of the PDF.\n%\n pdf = 1.0 / ( pi * ( 1.0 + x * x ) ) ...\n + b * b * ( ( 1.0 - x * x ) * cos ( 2.0 * a ) ...\n + 2.0 * x * sin ( 2.0 * x ) ) / ( pi * ( 1.0 + x * x ) * ( 1.0 + x * x ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/dipole_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7810008083305792}} {"text": "function [ vX ] = ProxHuberLossBoyd( vY, paramDelta, paramLambda )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = ProxHuberLossBoyd( vY, paramDelta, paramLambda )\n% Solves the Proximal Operator of the Huber Loss Function:\n% $$ \\arg \\min_{x} \\frac{1}{2} {\\left| x - y \\right\\|}_{2}^{2} + \\lambda {H}_{\\delta} \\left( x \\right) $$\n% Where {H}_{\\delta} \\left( x \\right) is the Huber Loss Function.\n% Input:\n% - vY - Input Vector.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - paramDelta - Parameter Delta.\n% The Delta Parameter of the Huber Loss Function.\n% This is the value the Huber Loss changes from\n% L2 Norm to the L1 Norm.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% - paramLambda - Parameter Lambda.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% Output:\n% - vX - Output Vector.\n% The solution of the Proximal Operator.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. Huber Loss (Wikipedia) - https://en.wikipedia.org/wiki/Huber_loss.\n% 2. Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers (See Huber Fitting).\n% 3. Proximal Operator of the Huber Loss Function - https://math.stackexchange.com/questions/3589025.\n% Remarks:\n% 1. In the reference by Boyd they use the $ \\rho = 1 / \\lambda $ form of\n% the Proximal Operator. Hence the adoption of the scaling. Also the\n% book use Huber Loss Function with $ \\delta = 1 $. \n% TODO:\n% 1. U.\n% Release Notes:\n% - 1.0.000 21/03/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nhProxL1 = @(vX, paramLambda) sign(vX) .* max(abs(vX) - paramLambda, 0);\nvX = ((1 / (1 + paramLambda)) * vY) + (paramDelta * (paramLambda / (1 + paramLambda)) * hProxL1((vY / paramDelta), 1 + paramLambda));\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q2791227/ProxHuberLossBoyd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7809212126023953}} {"text": "function E = keplerEq(M,e,eps)\n% Function solves Kepler's equation M = E-e*sin(E)\n% Input - Mean anomaly M [rad] , Eccentricity e and Epsilon \n% Output eccentric anomaly E [rad]. \n \tEn = M;\n\tEns = En - (En-e*sin(En)- M)/(1 - e*cos(En));\n\twhile ( abs(Ens-En) > eps )\n\t\tEn = Ens;\n\t\tEns = En - (En - e*sin(En) - M)/(1 - e*cos(En));\n\tend;\n\tE = Ens;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39896-keplers-equation-solver/keplerEq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7809212043841763}} {"text": "function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...\n num_features, lambda)\n%COFICOSTFUNC Collaborative filtering cost function\n% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...\n% num_features, lambda) returns the cost and gradient for the\n% collaborative filtering problem.\n%\n\n% Unfold the U and W matrices from params\nX = reshape(params(1:num_movies*num_features), num_movies, num_features);\nTheta = reshape(params(num_movies*num_features+1:end), ...\n num_users, num_features);\n\n \n% You need to return the following values correctly\nJ = 0;\nX_grad = zeros(size(X));\nTheta_grad = zeros(size(Theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost function and gradient for collaborative\n% filtering. Concretely, you should first implement the cost\n% function (without regularization) and make sure it is\n% matches our costs. After that, you should implement the \n% gradient and use the checkCostFunction routine to check\n% that the gradient is correct. Finally, you should implement\n% regularization.\n%\n% Notes: X - num_movies x num_features matrix of movie features\n% Theta - num_users x num_features matrix of user features\n% Y - num_movies x num_users matrix of user ratings of movies\n% R - num_movies x num_users matrix, where R(i, j) = 1 if the \n% i-th movie was rated by the j-th user\n%\n% You should set the following variables correctly:\n%\n% X_grad - num_movies x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of X\n% Theta_grad - num_users x num_features matrix, containing the \n% partial derivatives w.r.t. to each element of Theta\n%\n\ndiff = R .* (X * Theta' - Y);\nsum_squared = @(A) sum(sum(A .^ 2));\n\nJ = (sum_squared(diff) + lambda * (sum_squared(X) + sum_squared(Theta))) /2;\nX_grad = diff * Theta + lambda * X;\nTheta_grad = diff' * X + lambda * Theta;\n\n\n% =============================================================\n\ngrad = [X_grad(:); Theta_grad(:)];\n\nend\n", "meta": {"author": "xjwhhh", "repo": "AndrewNgMachineLearning", "sha": "d9d8491b315755ea3726bc366d72ba069712c363", "save_path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning", "path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning/AndrewNgMachineLearning-d9d8491b315755ea3726bc366d72ba069712c363/code/machine-learning-ex8/ex8/cofiCostFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210673, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7808380039659776}} {"text": "function geometry_test015 ( )\n\n%*****************************************************************************80\n%\n%% TEST015 tests CIRCLE_EXP2IMP_2D, TRIANGLE_CIRCUMCIRCLE_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n n = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST015\\n' );\n fprintf ( 1, ' CIRCLE_EXP2IMP_2D computes the radius and \\n' );\n fprintf ( 1, ' center of the circle through three points.\\n' );\n fprintf ( 1, ' TRIANGLE_CIRCUMCIRCLE_2D computes the radius and \\n' );\n fprintf ( 1, ' center of the circle through the vertices of\\n' );\n fprintf ( 1, ' a triangle.\\n' );\n\n p1test(1:2,1:n) = [ ...\n 4.0, 2.0; ...\n 1.0, 5.0; ...\n -2.0, 2.0 ]';\n\n p2test(1:2,1:n) = [ ...\n 4.0, 2.0; ...\n 5.0, 4.0; ...\n 6.0, 6.0 ]';\n\n p3test(1:2,1:n) = [ ...\n 4.0, 2.0; ...\n 1.0, 5.0; ...\n 4.0, 2.0 ]';\n\n for i = 1 : n\n\n p1(1:2,1) = p1test(1:2,i);\n p2(1:2,1) = p2test(1:2,i);\n p3(1:2,1) = p3test(1:2,i);\n\n r8vec_print ( 2, p1, ' P1:' );\n r8vec_print ( 2, p2, ' P2:' );\n r8vec_print ( 2, p3, ' P3:' );\n\n [ r, center ] = circle_exp2imp_2d ( p1, p2, p3 );\n\n circle_imp_print_2d ( r, center, ' The implicit circle:' )\n\n t(1:2,1:3) = [ p1(1:2,1)'; p2(1:2,1)'; p3(1:2,1)' ]';\n\n [ r, center ] = triangle_circumcircle_2d ( t );\n\n circle_imp_print_2d ( r, center, ' The triangle''s circumcircle:' )\n\n end\n\n return\nend\n", "meta": {"author": "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_test015.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7808379985868353}} {"text": "function [ row, col, a ] = r8sp_dif2 ( m, n, nz_num )\n\n%*****************************************************************************80\n%\n%% R8SP_DIF2 returns the DIF2 matrix in R8SP format.\n%\n% Example:\n%\n% N = 5\n%\n% 2 -1 . . .\n% -1 2 -1 . .\n% . -1 2 -1 .\n% . . -1 2 -1\n% . . . -1 2\n%\n% Properties:\n%\n% A is banded, with bandwidth 3.\n%\n% A is tridiagonal.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is a special case of the TRIS or tridiagonal scalar matrix.\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is Toeplitz: constant along diagonals.\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A is positive definite.\n%\n% A is an M matrix.\n%\n% A is weakly diagonally dominant, but not strictly diagonally dominant.\n%\n% A has an LU factorization A = L * U, without pivoting.\n%\n% The matrix L is lower bidiagonal with subdiagonal elements:\n%\n% L(I+1,I) = -I/(I+1)\n%\n% The matrix U is upper bidiagonal, with diagonal elements\n%\n% U(I,I) = (I+1)/I\n%\n% and superdiagonal elements which are all -1.\n%\n% A has a Cholesky factorization A = L * L', with L lower bidiagonal.\n%\n% L(I,I) = sqrt ( (I+1) / I )\n% L(I,I-1) = -sqrt ( (I-1) / I )\n%\n% The eigenvalues are\n%\n% LAMBDA(I) = 2 + 2 * COS(I*PI/(N+1))\n% = 4 SIN^2(I*PI/(2*N+2))\n%\n% The corresponding eigenvector X(I) has entries\n%\n% X(I)(J) = sqrt(2/(N+1)) * sin ( I*J*PI/(N+1) ).\n%\n% Simple linear systems:\n%\n% x = (1,1,1,...,1,1), A*x=(1,0,0,...,0,1)\n%\n% x = (1,2,3,...,n-1,n), A*x=(0,0,0,...,0,n+1)\n%\n% det ( A ) = N + 1.\n%\n% The value of the determinant can be seen by induction,\n% and expanding the determinant across the first row:\n%\n% det ( A(N) ) = 2 * det ( A(N-1) ) - (-1) * (-1) * det ( A(N-2) )\n% = 2 * N - (N-1)\n% = N + 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 July 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, 1969,\n% ISBN: 0882756494,\n% LC: QA263.68\n%\n% Morris Newman, John Todd,\n% Example A8,\n% The evaluation of matrix inversion programs,\n% Journal of the Society for Industrial and Applied Mathematics,\n% Volume 6, Number 4, pages 466-476, 1958.\n%\n% John Todd,\n% Basic Numerical Mathematics,\n% Volume 2: Numerical Algebra,\n% Birkhauser, 1980,\n% ISBN: 0817608117,\n% LC: QA297.T58.\n%\n% Joan Westlake,\n% A Handbook of Numerical Matrix Inversion and Solution of \n% Linear Equations,\n% John Wiley, 1968,\n% ISBN13: 978-0471936756,\n% LC: QA263.W47.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer NZ_NUM, the number of nonzero elements in\n% the matrix.\n%\n% Output, integer ROW(NZ_NUM), COL(NZ_NUM), the row and \n% column indices of the nonzero elements.\n%\n% Output, real A(NZ_NUM), the nonzero elements of the matrix.\n%\n row = zeros(nz_num,1);\n col = zeros(nz_num,1);\n a = zeros(nz_num,1);\n\n k = 0;\n for i = 1 : m\n\n if ( 0 < i - 1 )\n k = k + 1;\n row(k) = i;\n col(k) = i - 1;\n a(k) = -1.0;\n end\n\n k = k + 1;\n row(k) = i;\n col(k) = i;\n a(k) = 2.0;\n\n if ( i < n )\n k = k + 1;\n row(k) = i;\n col(k) = i + 1;\n a(k) = -1.0;\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/cg/r8sp_dif2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7808214187210147}} {"text": "function linpack_d_test06 ( )\n\n%*****************************************************************************80\n%\n%% TEST06 tests DGBFA and DGBDI.\n%\n% Discussion:\n%\n% Matrix A is ( 2 -1 0 0 0)\n% (-1 2 -1 0 0)\n% ( 0 -1 2 -1 0)\n% ( 0 0 -1 2 -1)\n% ( 0 0 0 -1 2)\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% Local Parameters:\n%\n% N is the number of equations.\n%\n% ML is the number of subdiagonals,\n% MU the number of superdiagonals.\n%\n% LDA is the leading dimension of the array used to store the\n% matrix, which must be at least 2*ML+MU+1.\n%\n n_max = 128;\n ml = 1;\n mu = 1;\n lda = 2*ml+mu+1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST06\\n' );\n fprintf ( 1, ' For a general banded matrix,\\n' );\n fprintf ( 1, ' DGBFA factors the matrix,\\n' );\n fprintf ( 1, ' DGBDI computes the determinant as\\n' );\n fprintf ( 1, ' det = MANTISSA * 10^EXPONENT\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Find the determinant of the -1,2,-1 matrix\\n' );\n fprintf ( 1, ' for N = 2, 4, 8, 16, 32, 64, 128.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (For this matrix, det ( A ) = N + 1.)\\n' );\n%\n% Set the matrix A.\n%\n m = ml + mu + 1;\n fprintf ( 1, ' The bandwidth of the matrix is %d\\n', m );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Mantissa Exponent\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n for n_log = 1 : 7\n\n n = 2 * n;\n\n a(1:lda,1:n) = 0.0;\n\n for j = 1 : n\n a(m-1,j) = -1.0;\n a(m,j) = 2.0;\n a(m+1,j) = -1.0;\n end\n\n [ a, ipivot, info ] = dgbfa ( a, lda, n, ml, mu );\n\n if ( info ~= 0 )\n fprintf ( 1, ' Error! DGBFA returns INFO = %d\\n', info );\n return\n end\n\n det = dgbdi ( a, lda, n, ml, mu, ipivot );\n\n fprintf ( 1, ' %6d %14f %14f\\n', n, det(1), det(2) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/linpack_d_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7808214137555721}} {"text": "function g = p16_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P16_G evaluates the gradient for problem 16.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 May 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n f1 = 1.5 - x(1) * ( 1.0 - x(2) );\n f2 = 2.25 - x(1) * ( 1.0 - x(2) * x(2) );\n f3 = 2.625 - x(1) * ( 1.0 - x(2) * x(2) * x(2) );\n\n df1dx1 = - ( 1.0 - x(2) );\n df1dx2 = x(1);\n df2dx1 = - ( 1.0 - x(2) * x(2) );\n df2dx2 = 2.0 * x(1) * x(2);\n df3dx1 = - ( 1.0 - x(2) * x(2) * x(2) );\n df3dx2 = 3.0 * x(1) * x(2) * x(2);\n\n g(1) = 2.0 * ( f1 * df1dx1 + f2 * df2dx1 + f3 * df3dx1 );\n g(2) = 2.0 * ( f1 * df1dx2 + f2 * df2dx2 + f3 * df3dx2 );\n\n return\nend\n", "meta": {"author": "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/p16_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7807999517987969}} {"text": "function w = simplex_projection(v, b)\n% Simplex_Projection Projects point onto simplex of specified radius.\n%\n% w = simplex_projection(v, b) returns the vector w which is the solution\n% to the following constrained minimization problem:\n%\n% min ||w - v||_2\n% s.t. sum(w) <= b, w >= 0.\n%\n% That is, performs Euclidean projection of v to the positive simplex of\n% radius b.\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of OLPS: http://OLPS.stevenhoi.org/\n% Original authors: John Duchi (jduchi@cs.berkeley.edu)\n% Contributors: Bin LI, Steven C.H. Hoi\n% Change log: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif (b < 0)\n error('Radius of simplex is negative: %2.3f\\n', b);\nend\nv = (v > 0) .* v;\nu = sort(v,'descend');\nsv = cumsum(u);\nrho = find(u > (sv - b) ./ (1:length(u))', 1, 'last');\ntheta = max(0, (sv(rho) - b) / rho);\nw = max(v - theta, 0);\n", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/Strategy/simplex_projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7807970314957277}} {"text": "function R = randrot(n, N)\n% Generates uniformly random rotation matrices.\n%\n% function R = randrot(n, N)\n%\n% R is a n-by-n-by-N matrix such that each slice R(:, :, i) is an\n% orthogonal matrix of size n of determinant +1 (i.e., a matrix in SO(n)).\n% By default, N = 1.\n% Complexity: N times O(n^3).\n% Theory in Diaconis and Shahshahani 1987 for the uniformity on O(n);\n% With details in Mezzadri 2007,\n% \"How to generate random matrices from the classical compact groups.\"\n% To ensure matrices in SO(n), we permute the two first columns when\n% the determinant is -1.\n%\n% See also: randskew\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sept. 25, 2012.\n% Contributors: \n% Change log: \n\n if nargin < 2\n N = 1;\n end\n \n if n == 1\n R = ones(1, 1, N);\n return;\n end\n \n R = zeros(n, n, N);\n \n for i = 1 : N\n \n % Generated as such, Q is uniformly distributed over O(n), the set\n % of orthogonal matrices.\n A = randn(n);\n [Q, RR] = qr(A);\n Q = Q * diag(sign(diag(RR))); %% Mezzadri 2007\n \n % If Q is in O(n) but not in SO(n), we permute the two first\n % columns of Q such that det(new Q) = -det(Q), hence the new Q will\n % be in SO(n), uniformly distributed.\n if det(Q) < 0\n Q(:, [1 2]) = Q(:, [2 1]);\n end\n \n R(:, :, i) = Q;\n \n end\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/manifolds/rotations/randrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.780797031190207}} {"text": "function a = carry ( n, alpha )\n\n%*****************************************************************************80\n%\n%% CARRY returns the CARRY matrix.\n%\n% Discussion:\n%\n% We assume that arithmetic is being done in base ALPHA. We are adding\n% a column of N digits base ALPHA, as part of adding N random numbers.\n% We know the carry digit, between 0 and N-1, that is being carried into the\n% column sum (the incarry digit), and we want to know the probability of\n% the various carry digits 0 through N-1 (the outcarry digit) that could\n% be carried out of the column sum.\n%\n% The carry matrix summarizes this data. The entry A(I,J) represents\n% the probability that, given that the incarry digit is I-1, the\n% outcarry digit will be J-1.\n%\n% Formula:\n%\n% A(I,J) = ( 1 / ALPHA )^N * sum ( 0 <= K <= J-1 - floor ( I-1 / ALPHA ) )\n% (-1)^K * C(N+1,K) * C(N-I+(J-K)*ALPHA, N )\n%\n% Example:\n%\n% ALPHA = 10, N = 4\n%\n% 0.0715 0.5280 0.3795 0.0210\n% 0.0495 0.4840 0.4335 0.0330\n% 0.0330 0.4335 0.4840 0.0495\n% 0.0210 0.3795 0.5280 0.0715\n%\n% Square Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is a Markov matrix.\n%\n% A is centrosymmetric: A(I,J) = A(N+1-I,N+1-J).\n%\n% LAMBDA(I) = 1 / ALPHA^(I-1)\n%\n% det ( A ) = 1 / ALPHA^((N*(N-1))/2)\n%\n% The eigenvectors do not depend on ALPHA.\n%\n% A is generally not normal: A' * A /= A * A'.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% John Holte,\n% Carries, Combinatorics, and an Amazing Matrix,\n% The American Mathematical Monthly,\n% February 1997, pages 138-149.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer ALPHA, the numeric base being used in the addition.\n%\n% Output, real A(N,N), the matrix.\n%\n alpha = floor ( alpha );\n\n for i = 1 : n\n for j = 1 : n\n\n temp = 0.0;\n s = -1.0;\n\n for k = 0 : j - 1 - floor ( ( i - 1 ) / alpha )\n s = - s;\n c1 = r8_choose ( n + 1, k );\n c2 = r8_choose ( n - i + ( j - k ) * alpha, n );\n temp = temp + s * c1 * c2;\n end\n\n a(i,j) = temp / alpha^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/test_mat/carry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7806817399649585}} {"text": "function S=tria(A)\n%%TRIA Square root matrix triangularization. Given a rectangular square\n% root matrix, obtain a lower-triangular square root matrix that is\n% square.\n%\n%INPUTS: A A numRowXnumCol matrix that is generally not square.\n%\n%OUTPUTS: S A lower-triangular matrix such that S*S'=A*A'. If\n% numCol>=numRow, then S is a square numRowXnumRow matrix.\n% Otherwise, S is a numRowXnumCol matrix.\n%\n%This is the tria function needed for various steps in the cubature Kalman\n%filter and the square root Kalman filter. It is described in [1]. It has\n%been slightly modified from the paper so that the diagonal elements remain\n%positive.\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%July 2012 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n [~,R]=qr(A',0);\n S=R';\n \n %Make the diagonal elements all positive.\n sel=diag(S)<0;\n S(:,sel)=-S(:,sel);\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/tria.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7806817200099426}} {"text": "function r=rotpl2ro(u,v,t)\n%ROTPL2RO find matrix to rotate in the plane containing u and v r=[u,v,t]\n% Inputs:\n%\n% U(n,1) and V(n,1) define a plane in n-dimensional space\n% T is the rotation angle in radians from U towards V. If T\n% is omitted it will default to the angle between U and V\n%\n% Outputs:\n%\n% R(n,n) Rotation matrix\n\n%\n% Copyright (C) Mike Brookes 2007\n% Version: $Id: rotpl2ro.m,v 1.1 2007/11/21 16:50:32 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\nu=u(:);\n n=length(u);\nv=v(:);\nl=sqrt(u'*u);\nif l==0, error('input u is a zero vector'); end\nu=u/l; % normalize\nq=v-v'*u*u; % q is orthogonal to x\nl=sqrt(q'*q);\nif l==0 % u and v are colinear or v=zero\n [m,i]=max(abs(u));\n q=zeros(n,1);\n q(1+mod(i(1),n))=1; % choose next available dimension\n q=q-q'*u*u; % q is orthogonal to x\n l=sqrt(q'*q);\nend\nq=q/l; % normalize\nif nargin<3\n [s,c]=atan2sc(v'*q,v'*u);\n r=eye(n)+(c-1)*(u*u'+q*q')+s*(q*u'-u*q');\nelse\n r=eye(n)+(cos(t)-1)*(u*u'+q*q')+sin(t)*(q*u'-u*q');\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/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/rotpl2ro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7806717800545597}} {"text": "function [theta,alpha,e]=tls(Z)\n% tls\n% Computes tls estimate of hyperplane parameters\n% [theta, alpha] = tls ( Z)\n% Z is of form (p1'; p2'; ..) where pi is p-by-1 (dimension p)\n% Computed hyperplane is of form theta' * p = alpha with alpha>0\n\n%* Author: Ranjith Unnikrishnan *\n%* Carnegie Mellon University, Vision and Mobile Robotics Laboratory *\n%* THE MATERIAL EMBODIED IN THIS SOFTWARE IS PROVIDED TO YOU \"AS-IS\" *\n%* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, *\n%* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR *\n%* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL CARNEGIE MELLON *\n%* UNIVERSITY BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, *\n%* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY *\n%* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, *\n%* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF *\n%* THIRD PARTIES, WHETHER OR NOT CARNEGIE MELLON UNIVERSITY HAS BEEN *\n%* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON *\n%* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE *\n%* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. *\n%\n\n\np=size(Z,2);\nn=size(Z,1);\ncentroid=mean(Z,1);\nZ=Z-repmat(centroid,n,1);\n[U,S,V]=svd(Z'*Z);\ntheta=U(:,p);\nalpha=theta'*centroid';\n\nif(alpha<0)\n theta=-theta;\n alpha=-alpha;\nend\n\ne=median( abs(Z*theta - alpha +centroid*theta));\nreturn;\n", "meta": {"author": "zhixy", "repo": "Laser-Camera-Calibration-Toolbox", "sha": "f0bd1b984c51dea79840c344c1fec8cb3d088730", "save_path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox", "path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox/Laser-Camera-Calibration-Toolbox-f0bd1b984c51dea79840c344c1fec8cb3d088730/src/tls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7806717796436357}} {"text": "function geometry_test200 ( )\n\n%*****************************************************************************80\n%\n%% TEST200 tests SPHERE_TRIANGLE_SIDES_TO_ANGLES.\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 r = 10.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST200\\n' );\n fprintf ( 1, ' SPHERE_TRIANGLE_SIDES_TO_ANGLES takes the sides of a\\n' );\n fprintf ( 1, ' spherical triangle and determines the angles.\\n' );\n\n as = 121.0 + ( 15.4 / 60.0 );\n bs = 104.0 + ( 54.7 / 60.0 );\n cs = 65.0 + ( 42.5 / 60.0 );\n\n as = degrees_to_radians ( as );\n bs = degrees_to_radians ( bs );\n cs = degrees_to_radians ( cs );\n\n as = r * as;\n bs = r * bs;\n cs = r * cs;\n%\n% Get the spherical angles.\n%\n [ a, b, c ] = sphere_triangle_sides_to_angles ( r, as, bs, cs );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A = %8f (radians)\\n', a );\n a = radians_to_degrees ( a );\n fprintf ( 1, ' A = %8f (degrees)\\n', a );\n a = 117.0 + ( 58.0 / 60.0 );\n fprintf ( 1, ' Correct = %8f (radians)\\n', a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' B = %8f (radians)\\n', b );\n b = radians_to_degrees ( b );\n fprintf ( 1, ' B = %8f (degrees)\\n', b );\n b = 93.0 + ( 13.8 / 60.0 );\n fprintf ( 1, ' Correct = %8f (radians)\\n', b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' C = %8f (radians)\\n', c );\n c = radians_to_degrees ( c );\n fprintf ( 1, ' C = %8f (degrees)\\n', c );\n c = 70.0 + ( 20.6 / 60.0 );\n fprintf ( 1, ' Correct = %8f (radians)\\n', c );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/geometry_test200.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7806717636052142}} {"text": "% Maximum volume inscribed ellipsoid in a polyhedron \n% Section 8.4.1, Boyd & Vandenberghe \"Convex Optimization\"\n% Original version by Lieven Vandenberghe\n% Updated for CVX by Almir Mutapcic - Jan 2006\n% (a figure is generated)\n%\n% We find the ellipsoid E of maximum volume that lies inside of\n% a polyhedra C described by a set of linear inequalities.\n%\n% C = { x | a_i^T x <= b_i, i = 1,...,m } (polyhedra)\n% E = { Bu + d | || u || <= 1 } (ellipsoid) \n%\n% This problem can be formulated as a log det maximization\n% which can then be computed using the det_rootn function, ie,\n% maximize log det B\n% subject to || B a_i || + a_i^T d <= b, for i = 1,...,m\n\n% problem data\nn = 2;\npx = [0 .5 2 3 1];\npy = [0 1 1.5 .5 -.5];\nm = size(px,2);\npxint = sum(px)/m; pyint = sum(py)/m;\npx = [px px(1)];\npy = [py py(1)];\n\n% generate A,b\nA = zeros(m,n); b = zeros(m,1);\nfor i=1:m\n A(i,:) = null([px(i+1)-px(i) py(i+1)-py(i)])';\n b(i) = A(i,:)*.5*[px(i+1)+px(i); py(i+1)+py(i)];\n if A(i,:)*[pxint; pyint]-b(i)>0\n A(i,:) = -A(i,:);\n b(i) = -b(i);\n end\nend\n\n% formulate and solve the problem\ncvx_begin\n variable B(n,n) symmetric\n variable d(n)\n maximize( det_rootn( B ) )\n subject to\n for i = 1:m\n norm( B*A(i,:)', 2 ) + A(i,:)*d <= b(i);\n end\ncvx_end\n\n% make the plots\nnoangles = 200;\nangles = linspace( 0, 2 * pi, noangles );\nellipse_inner = B * [ cos(angles) ; sin(angles) ] + d * ones( 1, noangles );\nellipse_outer = 2*B * [ cos(angles) ; sin(angles) ] + d * ones( 1, noangles );\n\nclf\nplot(px,py)\nhold on\nplot( ellipse_inner(1,:), ellipse_inner(2,:), 'r--' );\nplot( ellipse_outer(1,:), ellipse_outer(2,:), 'r--' );\naxis square\naxis off\nhold off\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch08_geometric_probs/max_vol_ellip_in_polyhedra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7805736794488453}} {"text": "function a = sylvester_kac ( n )\n\n%*****************************************************************************80\n%\n%% SYLVESTER_KAC returns the SYLVESTER_KAC matrix.\n%\n% Formula:\n%\n% If J = I - 1\n% A(I,J) = N + 1 - I\n% If J = I + 1\n% A(I,J) = I\n%\n% Example:\n%\n% N = 5,\n%\n% 0 1 0 0 0\n% 4 0 2 0 0\n% 0 3 0 3 0\n% 0 0 2 0 4\n% 0 0 0 1 0\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is tridiagonal.\n%\n% If N is odd, the eigenvalues are:\n% -(N-1), -(N-3), ..., -2, 0, 2, ... (N-3), (N-1).\n%\n% If N is even, the eigenvalues are:\n% -(N-1), -(N-3), ..., -1, +1, ..., (N-3), (N-1).\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% Reference:\n%\n% Paul Clement,\n% A class of triple-diagonal matrices for test purposes,\n% SIAM Review,\n% Volume 1, 1959, pages 50-52.\n%\n% Olga Taussky, John Todd,\n% Another Look at a Matrix of Mark Kac,\n% Linear Algebra and its Applications,\n% Volume 150, 1991, pages 341-360.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n - 1\n a(i,i+1) = i;\n a(i+1,i) = n - i;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/sylvester_kac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.7805672328170472}} {"text": "function kl = cross_entropy(p, q, symmetric)\n% CROSS_ENTROPY Compute the Kullback-Leibler divergence between two discrete prob. distributions\n% kl = cross_entropy(p, q, symmetric)\n%\n% If symmetric = 1, we compute the symmetric version. Default: symmetric = 0;\n\ntiny = exp(-700);\nif nargin < 3, symmetric = 0; end\np = p(:);\nq = q(:);\nif symmetric\n kl = (sum(p .* log((p+tiny)./(q+tiny))) + sum(q .* log((q+tiny)./(p+tiny))))/2;\nelse\n kl = sum(p .* log((p+tiny)./(q+tiny)));\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/KPMtools/cross_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768541530198, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7805621430324116}} {"text": "function [ c, sigma ] = covariance_to_correlation ( n, k )\n\n%*****************************************************************************80\n%\n%% COVARIANCE_TO_CORRELATION: correlation matrix from a covariance matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real K(N,N), the covariance matrix.\n%\n% Output, real C(N,N), the correlation matrix.\n%\n% Output, real SIGMA(N), the standard deviations.\n%\n tol = sqrt ( eps );\n%\n% K must be symmetric.\n%\n error_frobenius = r8mat_is_symmetric ( n, n, k );\n\n if ( tol < error_frobenius )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COVARIANCE_TO_CORRELATION - Fatal error!\\n' );\n fprintf ( 1, ' Input matrix K fails symmetry test with error %g\\n', error_frobenius );\n error ( 'COVARIANCE_TO_CORRELATION - Fatal error!' );\n end\n%\n% It must be the case that K(I,J)^2 <= K(I,I) * K(J,J).\n%\n error_max = 0.0;\n for i = 1 : n\n for j = i + 1 : n\n error_max = max ( error_max, k(i,j)^2 - k(i,i) * k(j,j) );\n end\n end\n\n if ( tol < error_max )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COVARIANCE_TO_CORRELATION - Fatal error!\\n' );\n fprintf ( 1, ' Input matrix K fails K(I,J)^2 <= K(I,I)*K(J,J)\\n' );\n error ( 'COVARIANCE_TO_CORRELATION - Fatal error!' );\n end\n%\n% Get the diagonal.\n%\n sigma = zeros ( n, 1 );\n for i = 1 : n\n sigma(i) = k(i,i);\n end\n%\n% Ensure the diagonal is positive.\n%\n sigma_min = min ( sigma(1:n) );\n\n if ( sigma_min <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COVARIANCE_TO_CORRELATION - Fatal error!\\n' );\n fprintf ( 1, ' Input matrix K has nonpositive diagonal entry = %g\\n', sigma_min );\n error ( 'COVARIANCE_TO_CORRELATION - Fatal error!' );\n end\n%\n% Convert from variance to standard deviation.\n%\n sigma(1:n) = sqrt ( sigma(1:n) );\n%\n% Form C.\n%\n c(1:n,1:n) = diag ( 1.0 ./ sigma(1:n) ) * k(1:n,1:n) * diag ( 1.0 ./ sigma(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/correlation/covariance_to_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7805448536000751}} {"text": "function varargout = quantumstates(varargin)\n%QUANTUMSTATES Compute and plot Schroedinger eigenstates.\n% This program computes and plots eigenvalues lambda and eigenfunctions u\n% for the equation Lu = lambda*u, where L is the Schroedinger operator\n% defined by Lu(x) = -h^2*u\"(x) + V(x)*u(x). Here h is a small parameter\n% and the potential function V is given as a Chebfun. The domain of the\n% problem is the domain of V, with boundary conditions u=0 at both ends.\n%\n% Inputs:\n%\n% QUANTUMSTATES(V) plots 10 eigenstates for h=0.1\n% QUANTUMSTATES(V, n) plots n eigenstates for h=0.1\n% QUANTUMSTATES(V, h), h noninteger, plots 10 eigenstates for given h\n% QUANTUMSTATES(V, n, h) plots n eigenstates for given h\n% QUANTUMSTATES(..., 'noplot') produces no plot\n%\n% Outputs:\n% \n% D = QUANTUMSTATES(...) returns a vector D of eigenvalues\n% [U, D] = QUANTUMSTATES(...) returns a quasimatrix U of eigenfunctions\n% and a diagonal matrix of eigenvalues\n%\n% Examples:\n%\n% x = chebfun('x', [-3, 3]);\n% V = x.^2; % harmonic oscillator, or\n% V = abs(x); % absolute value, or\n% V = (x.^2-1).^4; % double well\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n% Nick Trefethen, January 2012\n\n%% Parsing of inputs:\nnoplot = strcmpi(varargin{nargin}, 'noplot'); % check for no plot\nnargin1 = nargin; % no of input args\nif ( noplot )\n nargin1 = nargin1 - 1; \nend \nV = varargin{1}; % potential function\nn = 10; % default no of states\nh = 0.1; % default constant\nif ( nargin1 == 3 )\n n = varargin{2}; \n h = varargin{3};\nend\nif ( nargin1 == 2 )\n v2 = varargin{2};\n if ( v2 == round(v2) )\n n = v2;\n else\n h = v2; \n end\nend\n\n%% Eigenvalue computation:\n[xmin, xmax] = domain(V); % domain of problem\n% Create a CHEBOP with Dirichlet BCs\nL = chebop([xmin, xmax]);\nL.lbc = 0; L.rbc = 0;\nL.op = @(x,u) -h^2*diff(u,2) + V.*u; % Schroedinger operator\n[U, D] = eigs(L, n, 'sr'); % compute evals/efuns\nd = diag(D); % vector of evals\n[d, ii] = sort(d); % sort them\nU = U(:,ii); \n\n%% Outputs:\nif ( nargout == 2 )\n varargout = {U, diag(d)};\nelse\n varargout = {d};\nend\n\nif ( noplot )\n % If we're not plotting, then we return.\n return\nend\n\n%% Plot:\n\nholdState = ishold;\n\n% Plot the potential function:\nLW = 'linewidth'; lw = 1;\nplot(V, 'k', LW, lw, 'jumpline', '-k'), hold on \ns = sprintf('h = %4g %d eigenstates', h, n);\ntitle(s, 'fontsize', 12)\n\n% Vertical limits:\nymax = max(d); \nymin = min(V); \nydiff = ymax - ymin; \nymax = ymax + .2*ydiff; \nymin = ymin - 0*ydiff; \n\n% V values at endpoints:\nVxmin = feval(V, xmin); \nVxmax = feval(V, xmax);\nif ( ymax > Vxmin ) % The potential \n plot(xmin*[1 1], [ymax, Vxmin], 'k', LW, lw) % V(x) effectively\nend % goes to infinity\nif ( ymax > Vxmax ) % at the endpoints,\n plot(xmax*[1 1], [ymax Vxmax], 'k', LW, lw) % so we make the\nend % plot show this.\ndx = .05*(xmax - xmin); \ndy = .25*ydiff/max(5, n);\n\n% Plot the eigenfunction, lifted by the corresponding eigenvalue:\nW = dy*U;\nW = num2cell(W);\nfor j = 1:n\n umm = minandmax(W{j});\n if ( umm(2) < -umm(1) )\n W{j} = -W{j}; \n end\n W{j} = W{j} + d(j);\nend\nW = horzcat(W{:});\nplot(W, LW, lw)\n\n% Plot V(x) again (so that black ends up on top):\nplot(V, 'k', LW, lw, 'jumpline', '-k')\nif ( ymax > Vxmin )\n plot(xmin*[1, 1], [ymax, Vxmin], 'k', LW, lw)\nend \nif ( ymax > Vxmax )\n plot(xmax*[1, 1], [ymax Vxmax], 'k', LW, lw) \nend\n\n% Set axis:\naxis([xmin - dx, xmax + dx, ymin - dy, ymax]), drawnow\n\nif ( ~holdState )\n % Stop holding:\n hold off\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/quantumstates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7805448460054314}} {"text": "function [xc,yc,radius] = fit_circle_to_points(x,y)\n\nx = x(:);\ny = y(:);\n\n% solve for parameters a, b, and c in the least-squares sense by\n% using the backslash operator\nabc = [x y ones(numel(x),1)] \\ -(x.^2+y.^2);\na = abc(1); b = abc(2); c = abc(3);\n\n% calculate the location of the center and the radius\nxc = -a/2;\nyc = -b/2;\nradius = sqrt((xc^2+yc^2)-c);\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/fit_circle_to_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7804953649578537}} {"text": "classdef matrix < handle\n\n methods(Static)\n function result = is_square(A)\n [m, n] = size(A);\n result = (m == n);\n end\n\n function result = is_symmetric(A)\n result = spx.matrix.is_square(A);\n if ~result\n return;\n end\n result = all(all(A==A.'));\n end\n\n function result = is_hermitian(A)\n result = spx.matrix.is_square(A);\n if ~result\n return;\n end\n result = all(all(A==A'));\n end\n\n function result = is_positive_definite(A)\n result = spx.matrix.is_hermitian(A);\n if ~result\n return;\n end\n % Perform Cholesky decomposition of A\n [R, p] = chol(A);\n result = (p == 0);\n end\n\n function result = is_orthogonal(A)\n G = A' * A;\n [m, n] = size(G);\n idx = eye(m, n);\n G = abs(G(~idx));\n result = all(G <= 1e-12);\n end\n\n function result = is_identity(A)\n [m, n] = size(A);\n if m ~= n\n result = false;\n return;\n end\n I = eye(m);\n diff = abs(A - I);\n result = all(all(diff <= 1e-12));\n end\n \n function result = is_orthonormal(A)\n if ~isreal(A)\n result = false;\n return;\n end\n G = A' * A;\n m = size(G, 1);\n I = eye(m);\n diff = abs(G - I);\n result = all(all(diff <= 1e-12));\n end\n\n function X = off_diagonal_elements(X)\n % Returns a column vector of off diagonal elements\n [m, n] = size(X);\n idx = eye(m, n);\n X = X(~idx);\n end\n\n function X = off_diagonal_matrix(X)\n % Returns the matrix of off diagonal elements\n [m, n] = size(X);\n idx = eye(m, n);\n X = (1 - idx).* X;\n end\n\n function X = off_diag_upper_tri_elements(X)\n % Returns the upper triangular off diagonal elements in a vector\n [m, n] = size(X);\n idx = tril(ones(m, n));\n X = X(~idx);\n end\n\n function X = off_diag_upper_tri_matrix(X)\n % Returns the upper triangular off diagonal elements in a matrix\n [m, n] = size(X);\n idx = tril(ones(m, n));\n X = (1 - idx).* X;\n end\n\n function result = nonzero_density(X)\n % Density of nonzero entries in the matrix\n result = nnz(X) / numel(X);\n end\n\n function [ result ] = is_diagonally_dominant( A, strict)\n %ISDIAGONALLYDOMINANT Returns if A is a diagonally dominant\n %matrix\n if ~exist('strict', 'var')\n strict = true;\n end\n A = abs(A);\n % Extract the diagonal\n d = diag(A);\n % Set the diagonal elements to 0\n A(logical(eye(size(A)))) = 0;\n % Now sum over the rows\n s = sum(A, 2);\n % We now check whether \n if strict\n result = all(d > s);\n else\n result = all(d >= s);\n end\n end\n\n function [ A ] = make_diagonally_dominant( A, strict )\n %MAKEDIAGONALLYDOMINANT Makes a matrix diagonally dominant\n if ~exist('strict', 'var')\n strict = true;\n end\n B = abs(A);\n % Set the diagonal elements to 0\n B(logical(eye(size(B)))) = 0;\n % Now sum over the rows\n s = sum(B, 2);\n if strict\n d = s + 1;\n else\n d = s;\n end\n % Extract the diagonal elements of A\n dd = diag(A);\n % Identify the ones which are not dominant\n requiredChanges = abs(dd) < d;\n % Assign the updated values\n dd(requiredChanges) = d(requiredChanges);\n % Update the matrix\n A(logical(eye(size(A)))) = dd;\n end\n\n function compare(A, B)\n % Compares two matrices\n C = abs(A - B);\n max_diff = max(max(abs(C)));\n fprintf('Maximum difference: %.4e\\n', max_diff);\n end\n\n function df = dof_lowrank(m, n, r)\n % Returns the degrees of freedom of a low rank matrix\n df = r * (m + n - r);\n end\n\n\n end\n\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/+spx/matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7804892012283229}} {"text": "function out = proj_psd(X)\n%PROJ_PSD computes the orthogonal projection onto the cone of positive semidefinite matrics \n% (psd cone) {X: X psd }\n%\n% Usage: \n% out = PROJ_PSD(X)\n% ===========================================\n% INPUT:\n% X - matrix to be projected\n% ===========================================\n% Assumptions:\n% X is symmetric\n% ===========================================\n% Output:\n% out - projection matrix\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nif (nargin < 1)\n error ('usage: proj_psd(X)') ;\nend\n\neps = 1e-10 ; % defalut value for eps : 1e-10\nif ((size(X,1) ~= size(X,2)) || (norm( X - X') > eps))\n error('usage: proj_psd(X) - X should be a symmetric matrix') ;\nend\n\nX = 0.5 * (X + X');\n\n[V,D] = eig(X) ;\n\nout = V * max(D,0) *V' ;\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/proj_psd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7804826850188122}} {"text": "function node_xyz = sphere01_triangle_project ( a_xyz, b_xyz, c_xyz, f1, ...\n f2, f3 )\n\n%*****************************************************************************80\n%\n%% SPHERE01_TRIANGLE_PROJECT projects from plane to spherical triangle.\n%\n% Discussion:\n%\n% We assume that points A, B and C lie on the unit sphere, and they\n% thus define a spherical triangle.\n%\n% They also, of course, define a planar triangle.\n%\n% Let (F1,F2,F3) be the barycentric coordinates of a point in this \n% planar triangle.\n%\n% This function determines the coordinates of the point in the planar\n% triangle identified by the barycentric coordinates, and returns the\n% coordinates of the projection of that point onto the unit sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A_XYZ(3), B_XYZ(3), C_XYZ(3), the coordinates\n% of the points A, B, and C.\n%\n% Input, integer F1, F2, F3, the barycentric coordinates\n% of a point in the triangle ABC. Normally, these coordinates would\n% be real numbers, and would sum to 1. For convenience, we allow these\n% to be integers which must be divided by F1+F2+F3.\n%\n% Output, real NODE_XYZ(3), the coordinates of the \n% point on the unit sphere which is the projection of the point on the plane\n% whose barycentric coordinates with respect to A, B, and C is\n% (F1,F2,F3)/(F1+F2+F3).\n%\n\n%\n% Destroy all row vectors!\n%\n a_xyz = a_xyz(:);\n b_xyz = b_xyz(:);\n c_xyz = c_xyz(:);\n\n node_xyz(1:3,1) = ...\n ( ( f1 ) * a_xyz(1:3) ...\n + ( f2 ) * b_xyz(1:3) ...\n + ( f3 ) * c_xyz(1:3) ) ...\n / ( f1 + f2 + f3 );\n\n node_norm = r8vec_norm ( 3, node_xyz(1:3,1) );\n\n node_xyz(1:3,1) = node_xyz(1:3,1) / node_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/sphere_triangle_quad/sphere01_triangle_project.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7804821536999117}} {"text": "%% Mesh Smoothing and Optimization\n% \n%% Improve geometric mesh quality\n% \n% The function [node,elem] = optmesh(node,elem) will optimize the shape\n% regularity of triangles in the input mesh (node,elem) and outputs a\n% better mesh (node,elem). \n\nclear all; close all;\nload airfoilperturb\nfigure(1); subplot(1,2,1); \nshowmesh(node,elem); title('original mesh');\nfigure(2); subplot(1,2,1); \nshowmeshquality(node,elem); axis([0 1 0 2700]);\n[node,elem] = optmesh(node,elem);\nfigure(1); subplot(1,2,2); \nshowmesh(node,elem); title('smoothed mesh');\nfigure(2); subplot(1,2,2); \nshowmeshquality(node,elem); axis([0 1 0 2700]);\n%%\n% We explain algorithms implemented in optimesh.m in the following.\n\n%% ODT-based mesh smoothing\n%\n% In the function <../../../mesh/html/meshsmoothing.html meshsmoothing>, we move one node at a time inside its\n% patch, which consists of all triangles surrounding this node, such that\n% the interpolation error to a quadratic function is minimized. The\n% function |meshsmoothing| will keep the topology of the input mesh, i.e.,\n% the node index and connectivity of nodes are unchanged.\n%\n% In the simplest case, the scheme is to move the node to the average of\n% circumenters of triangles in the local patch. Details can be found in the\n% paper . \ntheta = [-2*pi/3 -pi/3 0 pi/3 2*pi/3 pi]';\nnode = [cos(theta), sin(theta)];\nnode(end+1,:) = 0;\nelem = delaunayn(node);\nnode(end,:) = rand(1,2)*0.4;\nfigure(1); subplot(1,2,1);\nshowmesh(node,elem); findnode(node,'all','noindex');\nc = circumcenter(node,elem);\nhold on; plot(c(:,1),c(:,2),'r.','MarkerSize',16)\nnode(end,:) = mean(c);\nplot(node(end,1),node(end,2),'b.','MarkerSize',16)\nfigure(1); subplot(1,2,2);\nshowmesh(node,elem); findnode(node,'all','noindex');\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/doc/meshoptdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7804821411882887}} {"text": "% Create a spectrum with a linear phase, a given delay in samples\n%\n% Description\n% If the spectrum length is even, the Nyquist's phase is managed as follow:\n% sign(real(exp((delay*1i*pi))))\n%\n% Inputs\n% delay : [samples]\n% fftlen : length of the fft\n%\n% Outputs\n% shift : the delay-spectrum\n%\n% Example\n% S = fft(...);\n% D = delay2spec(12, 1024);\n% S = S.*D; % shift the time signal by 12 samples to the left\n%\n% Copyright (c) 2008 Ircam/CNRS-UMR9912-STMS\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction shift = delay2spec(delay, dftlen)\n if delay==0\n shift = ones(1,dftlen);\n else\n % odd length\n if mod(dftlen,2)==1\n shift = exp((delay*2i*pi./dftlen).*(1:(dftlen-1)/2));\n shift = [1, shift(1:end), conj(shift(end:-1:1))];\n\n % even length\n else\n shift = exp((delay*2i*pi./dftlen).*(1:dftlen/2));\n shift = [1, shift(1:end-1), sign(real(shift(end))), conj(shift(end-1:-1:1))];\n end\n end\nreturn\n\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/misc/delay2spec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7804639453902007}} {"text": "function X = kr(U,varargin)\n%KR Khatri-Rao product.\n% kr(A,B) returns the Khatri-Rao product of two matrices A and B, of \n% dimensions I-by-K and J-by-K respectively. The result is an I*J-by-K\n% matrix formed by the matching columnwise Kronecker products, i.e.\n% the k-th column of the Khatri-Rao product is defined as\n% kron(A(:,k),B(:,k)).\n%\n% kr(A,B,C,...) and kr({A B C ...}) compute a string of Khatri-Rao \n% products A o B o C o ..., where o denotes the Khatri-Rao product.\n%\n% See also kron.\n\n% Version: 21/10/10\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n\nif ~iscell(U), U = [U varargin]; end\nK = size(U{1},2);\nif any(cellfun('size',U,2)-K)\n error('kr:ColumnMismatch', ...\n 'Input matrices must have the same number of columns.');\nend\nJ = size(U{end},1);\nX = reshape(U{end},[J 1 K]);\nfor n = length(U)-1:-1:1\n I = size(U{n},1);\n A = reshape(U{n},[1 I K]);\n X = reshape(bsxfun(@times,A,X),[I*J 1 K]);\n J = I*J;\nend\nX = reshape(X,[size(X,1) K]);\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/BCPF/Algorithms/kr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8652240964782012, "lm_q1q2_score": 0.7803634933212948}} {"text": "function [ u, it_num ] = multigrid_poisson_1d ( n, a, b, ua, ub, force, exact )\n\n%*****************************************************************************80\n% \n%% MULTIGRID_POISSON_1D solves a 1D PDE using the multigrid method.\n%\n% Discussion:\n%\n% This routine solves a 1D boundary value problem of the form\n%\n% - U''(X) = F(X) for A < X < B,\n%\n% with boundary conditions U(A) = UA, U(B) = UB.\n%\n% The multigrid method is used. \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by William Hager.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% William Hager,\n% Applied Numerical Linear Algebra,\n% Prentice-Hall, 1988,\n% ISBN13: 978-0130412942,\n% LC: QA184.H33.\n%\n% Parameters:\n%\n% Input, integer N, the number of intervals.\n% N must be a power of 2.\n%\n% Input, real A, B, the left and right endpoints of the region.\n%\n% Input, real UA, UB, the left and right boundary values.\n%\n% Input, function value = FORCE ( x ), the name of the function \n% which evaluates the right hand side.\n%\n% Input, function value = EXACT ( x ), the name of the function \n% which evaluates the exact solution.\n%\n% Output, integer IT_NUM, the number of iterations.\n%\n% Output, real U(N+1), the computed solution.\n%\n\n%\n% Determine if we have enough storage.\n%\n k = i4_log_2 ( n );\n\n if ( n ~= 2^k )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MULTIGRID_POISSON_1D - Fatal error!\\n' );\n fprintf ( 1, ' N is not a power of 2.\\n' );\n error ( 'MULTIGRID_POISSON_1D - Fatal error!' );\n end\n\n nl = n + n + k - 2;\n\n uu = zeros ( nl, 1 );\n r = zeros ( nl, 1 );\n%\n% Initialization.\n%\n it = 4;\n it_num = 0;\n tol = 0.0001;\n utol = 0.7;\n m = n;\n% \n% Set the nodes.\n%\n x = ( linspace ( a, b, n + 1 ) )';\n%\n% Set the right hand side.\n%\n r = zeros ( n + 1, 1 );\n r(1) = ua;\n r(2:n) = force ( x(2:n) ) / n / n;\n r(n+1) = ub;\n%\n% L points to first entry of solution.\n% LL points to penultimate entry.\n%\n l = 1;\n ll = n;\n% \n% Gauss-Seidel iteration\n%\n d1 = 0.0;\n j = 0;\n\n while ( 1 )\n\n d0 = d1;\n j = j + 1;\n [ uu(l:ll+1), d1 ] = gauss_seidel ( n + 1, r(l:ll+1), uu(l:ll+1) );\n it_num = it_num + 1;\n%\n% Do at least 4 iterations at each level.\n%\n if ( j < it )\n\n continue\n%\n% Enough iterations, satisfactory decrease, on finest grid, exit.\n%\n elseif ( d1 < tol && n == m )\n\n break\n%\n% Enough iterations, satisfactory convergence, go finer.\n%\n elseif ( d1 < tol )\n\n uu(l-1-n-n:l-1) = ctof ( n + 1, uu(l:ll+1), n + n + 1, uu(l-1-n-n:l-1) );\n\n n = n + n;\n ll = l - 2;\n l = l - 1 - n;\n j = 0;\n%\n% Enough iterations, slow convergence, 2 < N, go coarser.\n%\n elseif ( utol * d0 <= d1 && 2 < n )\n\n [ uu(l+n+1:l+n+1+(n/2)), r(l+n+1:l+n+1+(n/2)) ] = ...\n ftoc ( n + 1, uu(l:ll+1), r(l:ll+1), (n/2)+1 );\n\n n = n / 2;\n l = ll + 2;\n ll = ll + n + 1;\n j = 0;\n\n end\n\n end\n\n u(1:n+1) = uu(1:n+1);\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/multigrid_poisson_1d/multigrid_poisson_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8705972583359806, "lm_q1q2_score": 0.780273995467692}} {"text": "function [xi,w]=seventhOrder2DCubPoints()\n%%SEVENTHORDER2DCUBPOINTS Generate seventh-order cubature points\n% for integration over a 2-dimensional cube with bounds of \n% (-1,-1), (-1,1), (1,1), and (1,-1).\n%\n%INPUTS: None\n%\n%OUTPUTS: xi This is a 2XnumCubPoints set of points for the standard\n% square.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard square (4).\n%\n%This function implements the points given in [1] (12 points).\n%\n%EXAMPLE:\n%We compare a 6th-order moment computed using these cubature points\n%to one computed using monomialIntCube (a 7th order moment would have just\n%been 0). The results are the same within typical finite precision limits.\n% [xi,w]=seventhOrder2DCubPoints();\n% alpha=[2;4];\n% theMoment=findMomentFromSamp(alpha,xi,w);\n% intVal=monomialIntCube(alpha);\n% RelErr=(theMoment-intVal)/intVal\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=[0.92582009977255146156656677658399952253, 0, 0.24197530864197530864197530864197530864;\n 0, 0.92582009977255146156656677658399952253, 0.24197530864197530864197530864197530864;\n-0.92582009977255146156656677658399952253, 0, 0.24197530864197530864197530864197530864;\n 0, -0.92582009977255146156656677658399952253, 0.24197530864197530864197530864197530864;\n 0.8059797829185987437078561813507442463, 0.8059797829185987437078561813507442463, 0.23743177469063023421810525931129352533;\n 0.8059797829185987437078561813507442463, -0.8059797829185987437078561813507442463, 0.23743177469063023421810525931129352533;\n -0.8059797829185987437078561813507442463, 0.8059797829185987437078561813507442463, 0.23743177469063023421810525931129352533;\n -0.8059797829185987437078561813507442463, -0.8059797829185987437078561813507442463, 0.23743177469063023421810525931129352533;\n 0.3805544332083156563791063590863941355, 0.3805544332083156563791063590863941355, 0.52059291666739445713991943204673116603;\n 0.3805544332083156563791063590863941355, -0.3805544332083156563791063590863941355, 0.52059291666739445713991943204673116603;\n -0.3805544332083156563791063590863941355, 0.3805544332083156563791063590863941355, 0.52059291666739445713991943204673116603;\n -0.3805544332083156563791063590863941355, -0.3805544332083156563791063590863941355, 0.52059291666739445713991943204673116603];\nw=M(:,3);\nxi=M(:,1:2)';\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Cube_Space/Square/seventhOrder2DCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7802739915505597}} {"text": "function value = parallelipiped_volume_3d ( x, y, z )\n\n%*****************************************************************************80\n%\n%% PARALLELIPIPED_VOLUME_3D returns the volume of a parallelipiped in 3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(4), Y(4), Z(4), the coordinates of one corner\n% of the parallelipiped, and its 3 immediate neighbors.\n%\n% Output, real PARALLELIPIPED_VOLUME_3D, the volume of\n% the parallelipiped.\n%\n value = abs ( ...\n ( z(2) - z(1) ) * ( y(4) * x(3) - y(3) * x(4) ) + ...\n ( z(3) - z(1) ) * ( x(4) * y(2) - x(2) * y(4) ) + ...\n ( z(4) - z(1) ) * ( x(2) * y(3) - x(3) * y(2) ) + ...\n ( z(3) - z(2) ) * ( y(4) * x(1) - y(1) * x(4) ) + ...\n ( z(4) - z(2) ) * ( x(3) * y(1) - x(1) * y(3) ) + ...\n ( z(4) - z(3) ) * ( x(1) * y(2) - x(2) * y(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/stroud/parallelipiped_volume_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7802293186107899}} {"text": "function phi = basis_mn_tet10 ( t, n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_MN_TET10: all bases at N points for a TET10 element.\n%\n% Discussion:\n%\n% The routine is given the coordinates of the vertices of a tetrahedron.\n%\n% It works directly with these coordinates, and does not refer to a\n% reference element.\n%\n% P1 through P4 are vertices.\n%\n% P1 <= P5 <= P2\n% P2 <= P6 <= P3\n% P1 <= P7 <= P3\n% P1 <= P8 <= P4\n% P2 <= P9 <= P4\n% P3 <= P10 <= P4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Olgierd Zienkiewicz,\n% The Finite Element Method,\n% Sixth Edition,\n% Butterworth-Heinemann, 2005,\n% ISBN: 0750663200,\n% LC: TA640.2.Z54.\n%\n% Parameters:\n%\n% Input, real T(3,4), the coordinates of the vertices.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real P(3,N), the points where the basis functions\n% are to be evaluated.\n%\n% Output, real PHI(10,N), the value of the basis functions\n% at the evaluation points.\n%\n phi_linear(1:4,1:n) = basis_mn_tet4 ( t, n, p );\n\n phi( 1,1:n) = ( 2.0 * phi_linear(1,1:n) - 1.0 ) .* phi_linear(1,1:n);\n phi( 2,1:n) = ( 2.0 * phi_linear(2,1:n) - 1.0 ) .* phi_linear(2,1:n);\n phi( 3,1:n) = ( 2.0 * phi_linear(3,1:n) - 1.0 ) .* phi_linear(3,1:n);\n phi( 4,1:n) = ( 2.0 * phi_linear(4,1:n) - 1.0 ) .* phi_linear(4,1:n);\n phi( 5,1:n) = 4.0 * phi_linear(1,1:n) .* phi_linear(2,1:n);\n phi( 6,1:n) = 4.0 * phi_linear(2,1:n) .* phi_linear(3,1:n);\n phi( 7,1:n) = 4.0 * phi_linear(1,1:n) .* phi_linear(3,1:n);\n phi( 8,1:n) = 4.0 * phi_linear(1,1:n) .* phi_linear(4,1:n);\n phi( 9,1:n) = 4.0 * phi_linear(2,1:n) .* phi_linear(4,1:n);\n phi(10,1:n) = 4.0 * phi_linear(3,1:n) .* phi_linear(4,1:n);\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem3d_pack/basis_mn_tet10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7802293171292475}} {"text": "function price = CrankNicolsonFD_BlackScholes_func( S_0, K, r, T, sigma, call, dS, dt, Smax, Smin)\n% Description: Crank-Nicolson PDE Finite Difference method to price European Option in Black Scholes Model\n% Author: Justin Kirkby\nM = round((Smax - Smin)/dS); % grid points\nN = round(T/dt); % time steps\n\ndS = (Smax - Smin) / M; % readjust\ndt = T / N; % readjust\n\nvals = zeros(M+1, N+1);\nvS = linspace(Smin, Smax, M+1)';\nvI = vS / dS;\nvJ = 0:N;\n\n% Boundary Conditions\nif call == 1 % call option\n vals(:, N+1) = max(vS - K, 0); \n vals(1, :) = 0;\n vals(M+1, :) = Smax - K*exp(-r*dt*(N - vJ)); \nelse % put option\n vals(:, N+1) = max(K - vS, 0); \n vals(1, :) = K*exp(-r*dt*(N - vJ));\n vals(M+1, :) = 0; \nend\n\n% Tridiagonal Coefficients\na = 0.25 * dt * (sigma^2 *(vI.^2) - r*vI);\nb = -dt*0.5*(sigma^2*(vI.^2) + r);\nc = 0.25*dt*(sigma^2*(vI.^2) + r*vI);\n\nM1 = -diag(a(3:M), -1) + diag(1 - b(2:M)) - diag(c(2:M-1),1);\n[L,U] = lu(M1);\nM2 = diag(a(3:M), -1) + diag(1 + b(2:M)) + diag(c(2:M-1),1);\n\n% Solve systems (backward in time)\nfor j = N:-1:1\n vals(2:M,j) = U \\ (L \\ (M2*vals(2:M,j+1)));\nend\n\nprice = interp1(vS, vals(:,1), S_0);\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/PDE_FiniteDifference/BlackScholes/CrankNicolsonFD_BlackScholes_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731169394881, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7802262638336481}} {"text": "function logistic\n% Logistic growth \n% using MATLAB for analytical solution \n%\n% $Ekkehard Holzbecher $Date: 2006/04/20 $\n%--------------------------------------------------------------------------\nT = 10; % maximum time\nr = 1; % rate \nkappa = 1; % capacity\nc0 = 0.01; % initial value\n\n%----------------------execution-------------------------------------------\n\nt = linspace (0,T,100);\ne = exp(r*t);\nc = c0*kappa*e./(kappa+c0*(e-1));\n\n%---------------------- graphical output ----------------------------------\n\nplot (t,c); grid;\nxlabel ('time'); legend ('population');\ntitle ('logistic growth');\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15646-environmental-modeling/logistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7801894688950218}} {"text": "function [lat,lon,h]=xyz2ell3(X,Y,Z,a,b,e2)\n% XYZ2ELL3 Converts cartesian coordinates to ellipsoidal.\n% Uses direct algorithm in B.R. Bowring, \"The accuracy of\n% geodetic latitude and height equations\", Survey\n% Review, v28 #218, October 1985, pp.202-206. Vectorized.\n% See also XYZ2ELL, XYZ2ELL2.\n% Version: 2011-02-19\n% Useage: [lat,lon,h]=xyz2ell3(X,Y,Z,a,b,e2)\n% [lat,lon,h]=xyz2ell3(X,Y,Z)\n% Input: X \\\n% Y > vectors of cartesian coordinates in CT system (m)\n% Z /\n% a - ref. ellipsoid major semi-axis (m); default GRS80\n% b - ref. ellipsoid minor semi-axis (m); default GRS80\n% e2 - ref. ellipsoid eccentricity squared; default GRS80\n% Output: lat - vector of ellipsoidal latitudes (radians)\n% lon - vector of ellipsoidal longitudes (radians)\n% h - vector of ellipsoidal heights (m)\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nif nargin ~= 3 & nargin ~= 6\n warning('Incorrect number of input arguments');\n return\nend\nif nargin == 3\n [a,b,e2]=refell('grs80');\nend\n\nlon=atan2(Y,X);\ne=e2*(a/b)^2;\np=sqrt(X.*X+Y.*Y);\nr=sqrt(p.*p+Z.*Z);\nu=atan(b.*Z.*(1+e.*b./r)./(a.*p));\nlat=atan((Z+e.*b.*sin(u).^3)./(p-e2.*a.*cos(u).^3));\nv=a./sqrt(1-e2.*sin(lat).^2);\nh=p.*cos(lat)+Z.*sin(lat)-a*a./v;\n", "meta": {"author": "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/xyz2ell3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7801894635729117}} {"text": "% Exercise 4.47: Maximum determinant PSD matrix completion\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Almir Mutapcic - Jan 2006\n%\n% Given a symmetric matrix A in R^(n-by-n) with some entries unspecified\n% we find its completion such that A is positive semidefinite and\n% it has a maximum determinant out of all possible completions.\n% This problem can be formulated as a log det (and det_rootn) problem.\n%\n% This is a numerical instance of the specified book exercise.\n\n% problem size\nn = 4;\n\n% create and solve the problem\ncvx_begin\n % A is a PSD symmetric matrix (n-by-n)\n variable A(n,n) semidefinite;\n\n % constrained matrix entries.\n A(1,1) == 3; %#ok\n A(2,2) == 2; %#ok\n A(3,3) == 1; %#ok\n A(4,4) == 5; %#ok\n % Note that because A is symmetric, these off-diagonal\n % constraints affect the corresponding element on the\n % opposite side of the diagonal.\n A(1,2) == .5; %#ok\n A(1,4) == .25; %#ok\n A(2,3) == .75; %#ok\n\n % find the solution to the problem\n maximize( log_det( A ) )\n % maximize( det_rootn( A ) )\ncvx_end\n\n% display solution\nfprintf('Matrix A with maximum determinant (%g) is:\\n', det(A));\ndisp(A)\ndisp('Its eigenvalues are:')\ndisp(eig(A))\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch04_cvx_opt_probs/max_det_psd_completion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7801894553041879}} {"text": "function [bestEpsilon bestF1] = selectThreshold(yval, pval)\n%SELECTTHRESHOLD Find the best threshold (epsilon) to use for selecting\n%outliers\n% [bestEpsilon bestF1] = SELECTTHRESHOLD(yval, pval) finds the best\n% threshold to use for selecting outliers based on the results from a\n% validation set (pval) and the ground truth (yval).\n%\n\nbestEpsilon = 0;\nbestF1 = 0;\nF1 = 0;\n\nstepsize = (max(pval) - min(pval)) / 1000;\nfor epsilon = min(pval):stepsize:max(pval)\n \n % ====================== YOUR CODE HERE ======================\n % Instructions: Compute the F1 score of choosing epsilon as the\n % threshold and place the value in F1. The code at the\n % end of the loop will compare the F1 score for this\n % choice of epsilon and set it to be the best epsilon if\n % it is better than the current choice of epsilon.\n % \n % Note: You can use predictions = (pval < epsilon) to get a binary vector\n % of 0's and 1's of the outlier predictions\n\n tp = sum( ((pval bestF1\n bestF1 = F1;\n bestEpsilon = epsilon;\n end\nend\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex8/selectThreshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.780100891711359}} {"text": "function result = part_sf_majorize ( n, nparta, a, npartb, b )\n\n%*****************************************************************************80\n%\n%% PART_SF_MAJORIZE determines if partition A majorizes partition B.\n%\n% Discussion:\n%\n% The partitions must be in standard form.\n%\n% If A, with NPARTA parts, and B, with NPARTB parts, are both partitions\n% of the same positive integer N, then we say that A majorizes B if,\n% for every index K from 1 to N, it is true that\n%\n% sum ( 1 <= I <= K ) B(I) <= sum ( 1 <= I <= K ) A(I)\n%\n% where entries of A beyond index NPARTA, and of B beyond BPARTB\n% are assumed to be 0. We say that A strictly majorizes B if\n% A majorizes B, and for at least one index K the inequality is strict.\n%\n% For any two partitions of N, it is possible that A majorizes B,\n% B majorizes A, both partitions majorize each other (in which case\n% they are equal), or that neither majorizes the other.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Jack vanLint, Richard Wilson,\n% A Course in Combinatorics,\n% Cambridge, 1992,\n% ISBN: 0-521-42260-4,\n% LC: QA164.L56.\n%\n% Parameters:\n%\n% Input, integer N, the integer to be partitioned.\n% N must be positive.\n%\n% Input, integer NPARTA, the number of parts in partition A.\n% 1 <= NPARTA <= N.\n%\n% Input, integer A(NPARTA), contains partition A in standard\n% form. A(1) through A(NPARTA) contain nonzero integers which sum to N.\n%\n% Input, integer NPARTB, the number of parts in partition B.\n% 1 <= NPARTB <= N.\n%\n% Input, integer B(NPARTB), contains partition B in standard\n% form. B(1) through B(NPARTB) contain nonzero integers which sum to N.\n%\n% Output, integer RESULT, the result of the comparison.\n% -2, A and B are incomparable, would have been -1.\n% -1, A < B, (A is strictly majorized by B),\n% 0, A = B, (A and B are identical),\n% +1, A > B, (A strictly majorizes B),\n% +2, A and B are incomparable, would have been +1.\n%\n\n%\n% Check.\n%\n ierror = part_sf_check ( n, nparta, a );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PART_SF_MAJORIZE - Fatal error!\\n' );\n fprintf ( 1, ' The input array A is illegal.\\n' );\n error ( 'PART_SF_MAJORIZE - Fatal error!' );\n end\n\n ierror = part_sf_check ( n, npartb, b );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PART_SF_MAJORIZE - Fatal error!\\n' );\n fprintf ( 1, ' The input array B is illegal.\\n' );\n error ( 'PART_SF_MAJORIZE - Fatal error!' );\n end\n\n result = 0;\n suma = 0;\n sumb = 0;\n\n for i = 1 : min ( nparta, npartb )\n\n if ( i <= nparta )\n suma = suma + a(i);\n end\n\n if ( i <= npartb )\n sumb = sumb + b(i);\n end\n\n if ( result == -1 )\n\n if ( sumb < suma )\n result = -2;\n return\n end\n\n elseif ( result == 0 )\n\n if ( suma < sumb )\n result = -1;\n elseif ( sumb < suma )\n result = +1;\n end\n\n elseif ( result == + 1 )\n\n if ( suma < sumb )\n result = +2;\n return\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/part_sf_majorize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8840392741081574, "lm_q1q2_score": 0.7801008795795854}} {"text": "% Newton下山法 当初值选择不当时 调整下山因子lamda\nclear;\nformat long;\ntol = 1e-5;\nN = 100;\nx0 = 0.6;\nlamda = 1;\nf = @(x) x^3 - x - 1; %f(x)表达式\ndf = @(x) 3*x^2 - 1;\nfprintf('f(x)的初值: %d\\n', abs(f(x0)));\nfor k = 1 : N\n x1 = x0 - f(x0)/ df(x0);\n while abs(f(x1)) > abs(f(x0))\n lamda = lamda / 2; % 下山因子减半\n fprintf('下山因子减半后的值: %d\\n', lamda);\n x1 = x0 - lamda * f(x0) / df(x0);\n end\n fprintf('本次迭代f(x)的值: %d\\n', abs(f(x1)));\n if abs(x1 - x0) < tol\n fprintf('迭代次数: %d\\n', k);\n fprintf('方程的正根: %10.8f\\n', x1);\n break;\n end\n x0 = x1;\nend\nif k == N\n fprintf('迭代方法失败\\n');\nend", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第五章 方程求根的迭代法/example_4_7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.7799830396362244}} {"text": "function value = angle_deg_2d ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% ANGLE_DEG_2D returns the angle swept out between two rays in 2D.\n%\n% Discussion:\n%\n% Except for the zero angle case, it should be true that\n%\n% ANGLE_DEG_2D(P1,P2,P3) + ANGLE_DEG_2D(P3,P2,P1) = 360.0\n%\n% P1\n% /\n% /\n% /\n% /\n% P2--------->P3\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), P3(2,1), define the rays\n% P1 - P2 and P3 - P2 which in turn define the angle.\n%\n% Output, real VALUE, the angle swept out by the rays, measured\n% in degrees. 0 <= VALUE < 360. If either ray has zero length,\n% then VALUE is set to 0.\n%\n p(1,1) = ( p3(1,1) - p2(1,1) ) * ( p1(1,1) - p2(1,1) ) ...\n + ( p3(2,1) - p2(2,1) ) * ( p1(2,1) - p2(2,1) );\n\n p(2,1) = ( p3(1,1) - p2(1,1) ) * ( p1(2,1) - p2(2,1) ) ...\n - ( p3(2,1) - p2(2,1) ) * ( p1(1,1) - p2(1,1) );\n\n if ( p(1,1) == 0.0 & p(2,1) == 0.0 )\n value = 0.0;\n return\n end\n\n value = atan2 ( p(2,1), p(1,1) );\n\n if ( value < 0.0 )\n value = value + 2.0 * pi;\n end\n\n value = radians_to_degrees ( 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/geometry/angle_deg_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7798966454890399}} {"text": "function phy = simplex_unit_to_general ( dim_num, point_num, t, ref )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_UNIT_TO_GENERAL maps the unit simplex to a general simplex.\n%\n% Discussion:\n%\n% Given that the unit simplex has been mapped to a general simplex\n% with vertices T, compute the images in T, under the same linear\n% mapping, of points whose coordinates in the unit simplex are REF.\n%\n% The vertices of the unit simplex are listed as suggested in the\n% following:\n%\n% (0,0,0,...,0)\n% (1,0,0,...,0)\n% (0,1,0,...,0)\n% (0,0,1,...,0)\n% (...........)\n% (0,0,0,...,1)\n%\n% Thanks to Andrei (\"spiritualworlds\") for pointing out a mistake in the\n% previous implementation of this routine, 02 March 2008.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer POINT_NUM, the number of points to transform.\n%\n% Input, real T(DIM_NUM,DIM_NUM+1), the vertices of the\n% general simplex.\n%\n% Input, real REF(DIM_NUM,POINT_NUM), points in the\n% reference triangle.\n%\n% Output, real PHY(DIM_NUM,POINT_NUM), corresponding points\n% in the physical triangle.\n%\n\n%\n% The image of each point is initially the image of the origin.\n%\n% Insofar as the pre-image differs from the origin in a given vertex\n% direction, add that proportion of the difference between the images\n% of the origin and the vertex.\n%\n for dim = 1 : dim_num \n\n phy(dim,1:point_num) = t(dim,1);\n\n for vertex = 2 : dim_num + 1\n\n phy(dim,1:point_num) = phy(dim,1:point_num) ...\n + ( t(dim,vertex) - t(dim,1) ) * ref(vertex-1,1:point_num);\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/simplex_gm_rule/simplex_unit_to_general.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7798966288276472}} {"text": "function s = polyline_arclength_nd ( dim_num, n, p )\n\n%*****************************************************************************80\n%\n%% POLYLINE_LENGTH_ND computes the length of a polyline in ND.\n%\n% Discussion:\n%\n% A polyline of order M is the geometric structure consisting of\n% the M-1 line segments that lie between successive elements of a list\n% of M points.\n%\n% An ordinary line segment is a polyline of order 2.\n% The letter \"V\" is a polyline of order 3.\n% The letter \"N\" is a polyline of order 4, and so on.\n%\n% DIST(I+1,I) = sqrt ( sum ( 1 <= J <= DIM_NUM ) ( X(I+1) - X(I) )**2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real P(DIM_NUM,N), the points.\n%\n% Output, real S(N), the arclength coordinates\n% of each point. The first point has S(1) = 0 and the \n% last point has S(N) = arclength of the entire polyline.\n%\n s(1) = 0.0;\n\n for i = 2 : n\n\n s(i) = s(i-1) + sqrt ( sum ( ( p(1:dim_num,i) - p(1:dim_num,i-1) ).^2 ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polyline_arclength_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7798928057267874}} {"text": "% MORLET_2D_PYRAMID computes the 2-D elliptic Morlet filter given a set of \n% parameters in spatial domain\n%\n% Usage\n% gab = MORLET_2D_PYRAMID(N, M, sigma, slant, xi, theta, offset)\n%\n% Input\n% N (numeric): width of the filter\n% M (numeric): height of the filter\n% sigma (numeric): standard deviation of the envelope\n% slant (numeric): excentricity of the elliptic envelope\n% (the smaller slant, the larger angular resolution)\n% xi (numeric): the frequency peak\n% theta (numeric): orientation in radians of the filter\n% offset (numeric): 2-by-1 Vvector index of the row and column of the\n% center of the filter (if offset is [0,0] the filter is centered in\n% [1,1])\n%\n% Output\n% gab (numeric): N-by-M matrix representing the gabor filter in spatial\n% domain.\n%\n% Description\n% Compute a Morlet wavelet in spatial domain. \n%\n% Morlet wavelets have a 0 DC component.\n%\n% See also\n% GABOR_2D, MORLET_2D_NODC\n\n\nfunction gab = morlet_2d_pyramid(N, M, sigma, slant, xi, theta, offset)\n\n\tif ~exist('offset', 'var')\n\t\toffset = [floor(N/2), floor(M/2)];\n\tend\n\t\n\t[x , y] = meshgrid(1:M, 1:N);\n\n\tx = x - offset(2) - 1;\n\ty = y - offset(1) - 1;\n\t\n\tRth = rotation_matrix_2d(theta);\n\tA = Rth\\ [1/sigma^2, 0 ; 0 slant^2/sigma^2] * Rth ;\n\ts = x.* ( A(1,1)*x + A(1,2)*y) + y.*(A(2,1)*x + A(2,2)*y ) ;\n\t\n\t%normalize sucht that the maximum of fourier modulus is 1\n\tgaussian_envelope = exp( - s/2);\n\toscilating_part = gaussian_envelope .* exp(1i*(x*xi*cos(theta) + y*xi*sin(theta)));\n\tK = sum(oscilating_part(:)) ./ sum(gaussian_envelope(:));\n\tgabc = oscilating_part - K.*gaussian_envelope;\n\t\n\tgab=1/(2*pi*sigma^2/slant^2)*(gabc);\n\t\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/filters/morlet_2d_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7798928039120465}} {"text": "function h = fspecial3(type, sz, param)\n% FSPECIAL3 Create predefined 3-dimensional filters\n%\n% H = FSPECIAL3(TYPE, SZ, PARAM)\n%\n% H is a 3-dimensional (3D) filter of TYPE:\n%\n% 'gaussian' Rotationally symmetric Gaussian low-pass filter (default)\n% PARAM: standard deviation in each dimension (default\n% PARAM = [1.0 1.0 1.0])\n%\n% SZ is a vector with the size of the output filter in each dimension, in\n% order [rows, columns, slices]. By default, SZ = [3 3 3]. Sizes have to\n% be odd numbers so that the filter can be centered around 0.\n%\n% See also: fspecial.\n\n% Author: Ramon Casero \n% Copyright © 2011 University of Oxford\n% Version: 0.1.0\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n% check arguments\nerror(nargchk(0, 3, nargin, 'struct'));\nerror(nargoutchk(0, 1, nargout, 'struct'));\n\n% defaults\nif (nargin < 1 || isempty(type))\n type = 'gaussian';\nend\nif (nargin < 2 || isempty(sz))\n sz = [3 3 3];\nend\nif (nargin < 3 || isempty(param))\n switch type\n case 'gaussian'\n param = [1.0 1.0 1.0];\n otherwise\n error('Filter type not implemented')\n end\nend\n\n% check that sizes are odd numbers\nif (any(~rem(sz,2)))\n error('Sizes have to be odd numbers')\nend\n\n% filter size to each side of 0\nl = floor(sz/2);\n\n% compute filter\nswitch type\n \n case 'gaussian'\n \n % filter domain\n [gr, gc, gs] = ndgrid(-l(1):l(1), -l(2):l(2), -l(3):l(3));\n \n % compute gaussian function\n gr = gr / param(1);\n gc = gc / param(2);\n gs = gs / param(3);\n h = exp(-(gr.*gr + gc.*gc + gs.*gs)*.5);\n \n % normalize filtered intensity\n h = h / sum(h(:));\n\n otherwise\n \n error('Filter type not implemented')\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/FiltersToolbox/fspecial3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7798928021216961}} {"text": "% EX_COLLOCATION_LAPLACE_RING: solve the Laplace problem with a NURBS discretization by isogeometric collocation\n\n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_ring.txt';\n\n% Type of boundary conditions for each side of the domain\nproblem_data.nmnn_sides = [1 2];\nproblem_data.drchlt_sides = [3 4];\n \n% Physical parameters\nproblem_data.c_diff = @(x, y) ones(size(x)); % Only used in Galerkin, not in collocation\n \n% Source and boundary terms\nproblem_data.f = @(x, y) exp(x).*((x.^2 + y.^2 - 1).*sin(x.*y) - 2*y.*cos(x.*y));\nproblem_data.g = @test_ring_mixed_bc_g_nmnn;\nproblem_data.h = @(x, y, ind) exp(x).*sin(x.*y);\n \n% Exact solution (optional)\nproblem_data.uex = @(x, y) exp(x) .* sin (x.*y);\nproblem_data.graduex = @(x, y) cat (1, ...\n reshape ( exp(x).*(sin(x.*y) + y.*cos(x.*y)), [1, size(x)]), ...\n reshape (exp(x).*x.*cos(x.*y), [1, size(x)]));\n \n% Discretization parameters (p and h)\nmethod_data.degree = [4 4]; % Degree of the splines in each direction\nmethod_data.regularity = [3 3]; % Regularity of the splines, should be at least C^1.\nmethod_data.nsub = [9 9]; % Divide each subinterval of the original knot span in nsub subintervals\nmethod_data.pts_case = 1; % Collocation points. 1: Greville abscissae, 2: clustered superconvergent points\n\n% Solve with collocation method\n[geometry, msh_coll, space_coll, u_coll] = solve_laplace_collocation (problem_data, method_data);\n\n% Solve with Galerkin, for comparison\nmethod_data.nquad = method_data.degree + 1;\n[~, msh_gal, space_gal, u_gal] = solve_laplace_iso (problem_data, method_data);\n\n% Plot of solution\nvtk_pts = {linspace(0, 1, 20), linspace(0, 1, 20)};\nfigure; \n[eu, F] = sp_eval (u_coll, space_coll, geometry, vtk_pts);\n[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));\nsubplot (1,3,1)\nsurf (X, Y, eu)\ntitle ('Collocation solution'), axis tight\n[eu, F] = sp_eval (u_gal, space_gal, geometry, vtk_pts);\n[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));\nsubplot (1,3,2)\nsurf (X, Y, eu)\ntitle ('Galerkin solution'), axis tight\nsubplot (1,3,3)\nsurf (X, Y, problem_data.uex (X,Y))\ntitle ('Exact solution'), axis tight\n\n% Compute errors of collocation and Galerkin. Since it involves quadrature,\n% it is computed using the mesh and space objects from the Galerkin method.\ndisp ('Error in H1 and L2 norms, for isogeometric collocation')\n[error_h1_coll, error_l2_coll] = sp_h1_error (space_gal, msh_gal, u_coll, problem_data.uex, problem_data.graduex);\ndisp([error_l2_coll error_h1_coll])\n\ndisp ('Error in H1 and L2 norms, for isogeometric Galerkin')\n[error_h1_gal, error_l2_gal] = sp_h1_error (space_gal, msh_gal, u_gal, problem_data.uex, problem_data.graduex);\ndisp ([error_l2_gal error_h1_gal])\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/ex_collocation_laplace_ring_mixed_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7798927967994258}} {"text": "function qwgw_test05 ( )\n\n%*****************************************************************************80\n%\n%% TEST05 tests QWGW for the generalized Laguerre weight.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n\n%\n% The quadrature interval is [0,+oo).\n% Set the number of points.\n%\n a = 0.0;\n n = 5;\n%\n% Set the weight function parameter.\n%\n alpha = 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST05:\\n' );\n fprintf ( 1, ' Compute points and weights for Gauss quadrature\\n' );\n fprintf ( 1, ' with the generalized Laguerre weight w(x) = x^alpha * exp(-x).\\n' );\n fprintf ( 1, ' Order N = %d\\n', n );\n fprintf ( 1, ' ALPHA = %g\\n', alpha );\n fprintf ( 1, ' Interval = [0,+oo)\\n' );\n%\n% Set the recursion coefficients.\n%\n aj = zeros ( n, 1 );\n bj = zeros ( n, 1 );\n\n for j = 1 : n\n aj(j) = alpha + 2 * j - 1;\n end\n\n for j = 1 : n - 1\n bj(j) = j * ( alpha + j );\n end\n bj(n) = 0.0;\n\n bj(1:n) = sqrt ( bj(1:n) );\n\n mu0 = gamma ( alpha + 1 )\n%\n% Compute the points and weights.\n%\n [ x, w ] = sgqf ( n, aj, bj, mu0 );\n\n r8vec_print ( n, x, ' Abscissas:' );\n r8vec_print ( n, w, ' Weights:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_golub_welsch/qwgw_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7798787577090251}} {"text": "function [m, a] = polycenter(x,y)\n% POLYCENTER Compute center of mass and area of polygon\n%\n% [M, A] = POLYCENTER(X, Y)\n%\n% M is a 2-vector with the coordinates of the center of mass of a\n% polygon.\n%\n% A is the polygon area.\n%\n% X, Y are vectors with the coordinates of the polygon vertices.\n\n% Author: Ramon Casero\n% Copyright © 2010 University of Oxford\n% Version: 0.1.0\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n% check arguments\nerror( nargchk( 2, 2, nargin, 'struct' ) );\nerror( nargoutchk( 0, 2, nargout, 'struct' ) );\n\n% compute polygon area\na = polyarea( x, y );\n\n% close polygon, if open\nif (x(1) ~= x(end)) && (y(1) ~= y(end))\n x = x( [1:end 1] );\n y = y( [1:end 1] );\nend\n\n% compute x-coordinate of the centroid\nm(1) = sum( ...\n ( x( 1:end-1 ) + x( 2:end ) ) .* ( ...\n x( 1:end-1 ) .* y( 2:end ) - x( 2:end ) .* y( 1:end-1 ) ) ...\n ) / 6 / a;\n\n% compute y-coordinate of the centroid\nm(2) = sum( ...\n ( y( 1:end-1 ) + y( 2:end ) ) .* ( ...\n x( 1:end-1 ) .* y( 2:end ) - x( 2:end ) .* y( 1:end-1 ) ) ...\n ) / 6 / a;\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/PointsToolbox/polycenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7798787541318039}} {"text": "function [A,F]=pisar(xt,sin_num)\n\n% PISAR Pisarenko Harmonic Decomposition\n% \n% PISAR(XT,SIN_NUM) Subplots the input signal (Xt) and the\n% signal generated by the Pisarenko Harmonic Decomposition \n% algorithm for a sum of SIN_NUM sinusoid waves.\n% \n% [A F]=PISAR(XT,SIN_NUM) Generates SIN_NUM sinusoids, where the A\n% column-vector represents the amplitudes and the column-vector F\n% represents the normalized frequencies of those sinusoids.\n% \n% Considerations:\n% XT must be a column vector;\n% For best results -- SIN_NUM << length of XT\n%\n% Plese send any comments to palafox@ieee.org\n% \t\t\t Luis E. Palafox Maestre\n%\n\n[N t]=size(xt);\nrxx=xcorr(xt,'biased');\nrxx=rxx(N:(2*sin_num)+N);\n\n%Frequencies estimation\nRxx=toeplitz(rxx);\nev=eig(Rxx);\n[S i]=min(ev);\n[V D]=eig(Rxx);\na=V(:,i);\nrts=roots(a);\nw_est=[];\nfor i=1:sin_num\n w_est(i)= abs(angle(rts(2*i)));\nend\nF=(w_est/(2*pi))';\n\n%Amplitudes estimation\nmcos=[];\nfor n=1:sin_num\n vcos=[];\n for i=1:sin_num\n vcos=[vcos cos(n*w_est(i))];\n end\n mcos=[mcos; vcos];\nend\nrxx=rxx(2:sin_num+1);\nrxx=2*rxx;\nA=inv(mcos)*rxx;\nA=A.^(1/2);\n\nif nargout==0,\n xe=[];\n for n=1:N\n xe(n)=0;\n for i=1:sin_num\n xe(n)= xe(n)+(A(i)*cos(w_est(i)*n));\n end\n end\n f=figure;\n subplot(2,1,1);\n plot(xt);\n title('Input Signal')\n xlabel('n');\n ylabel('x(n)');\n subplot(2,1,2);\n plot(xe);\n title('Estimated Signal');\n xlabel('n');\n ylabel('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/74-pisar-m/pisar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7798787487914716}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n\n%problem 9- autocorrelation of exp(-3t)u(t)\n\nsyms t r\nx=exp(-3*t)*heaviside(t);\nx1=x;\nx_2=subs(x1,t,t-r);\nx2=conj(x_2);\nR=int(x1*x2,t,-inf,inf);\nezplot(R, [-8 8]);\nlegend('R_x(\\tau)');\nylim([0 0.17]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/6/c69i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.779866074546329}} {"text": "function trans = createTranslation3d(varargin)\n%CREATETRANSLATION3D Create the 4x4 matrix of a 3D translation.\n%\n% usage:\n% TRANS = createTranslation3d(DX, DY, DZ);\n% return the translation corresponding to DX and DY.\n% The returned matrix has the form :\n% [1 0 0 DX]\n% [0 1 0 DY]\n% [0 0 1 DZ]\n% [0 0 0 1]\n%\n% TRANS = createTranslation3d(VECT);\n% return the translation corresponding to the given vector [x y z].\n%\n%\n% See also:\n% transforms3d, transformPoint3d, transformVector3d, \n% createRotationOx, createRotationOy, createRotationOz, createScaling3d\n%\n% ---------\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 06/04/2004.\n%\n\n% HISTORY\n% 22/04/2009 rename as createTranslation3d\n\n\nif isempty(varargin)\n % assert translation with null vector\n dx = 0;\n dy = 0;\n dz = 0;\nelseif length(varargin)==1\n % translation vector given in a single argument\n var = varargin{1};\n dx = var(1);\n dy = var(2);\n dz = var(3);\nelse\n % translation vector given in 3 arguments\n dx = varargin{1};\n dy = varargin{2};\n dz = varargin{3};\nend\n\n% create the translation matrix\ntrans = [1 0 0 dx ; 0 1 0 dy ; 0 0 1 dz; 0 0 0 1];\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/createTranslation3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8774767890838837, "lm_q1q2_score": 0.7798652123838277}} {"text": "function value = r8_atanh ( x )\n\n%*****************************************************************************80\n%\n%% R8_ATANH returns the inverse hyperbolic tangent of a number.\n%\n% Discussion:\n%\n% Y = R8_ATANH ( X )\n%\n% implies that\n%\n% X = TANH(Y) = ( EXP(Y) - EXP(-Y) ) / ( EXP(Y) + EXP(-Y) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose inverse hyperbolic\n% tangent is desired. The absolute value of X should be less than\n% or equal to 1.\n%\n% Output, real R8_ATANH, the inverse hyperbolic tangent of X.\n%\n if ( 1.0 <= abs ( x ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_ATANH - Fatal error!\\n' );\n fprintf ( 1, ' ABS(X) must be < 1.\\n' );\n fprintf ( 1, ' Your input is X = %f\\n', x );\n error ( 'R8_ATANH - Fatal error!' );\n end\n\n value = 0.5 * log ( ( 1.0 + x ) / ( 1.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/r8lib/r8_atanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7798571409712518}} {"text": "% Chapter 5 - Fractals and Multifractals.\n% Program_5c - An Iterated Function System.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Barnsley's fern (Figure 5.7).\nfunction Program_5c(~)\n% This function plots Barnsley's fern with N points.\n% The transformations are in the form\n% T(x,y) = (a*x+b*y+c, d*x+e*y+f). \necho on\nN=50000;\nclose all\nP=zeros(N,2);\nP(1,:)=[0.5,0.5]; \n\n% The main loop where the iterations are performed.\nfor k=1:N-1\n\tr=rand;\n\tif r<.05;\n\t\tP(k+1,:)=T(P(k,:),0,0,0,0,.2,0);\n\telseif r<.86;\n\t\tP(k+1,:)=T(P(k,:),.85,.05,0,-.04,.85,1.6);\n\telseif r<.93;\n\t\tP(k+1,:)=T(P(k,:),.2,-.26,0,.23,.22,1.6);\n\telse\n\t\tP(k+1,:)=T(P(k,:),-.15,.28,0,.26,.24,.44);\n\tend\nend\n\nplot(P(:,1),P(:,2),'.','MarkerSize',1);\naxis([-2.5 3.5 0 11]);\nset(gca,'Position',[0 0 1 1])\n\n% The transformation T\nfunction F=T(P,a,b,c,d,e,f)\nF=zeros(1,2);\nF(1)=a*P(1)+b*P(2)+c;\nF(2)=d*P(1)+e*P(2)+f;\n\n% End of Program_5c.", "meta": {"author": "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_5c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7798571334788348}} {"text": "% Numerical solution of polynomial systems by hom4ps Homotopy method \n% \n% Syntax: >> [S, var] = psolve( P ) \n% \n% Input: P --- (cell array) the polynomial system to be solved\n% For example: \n% >> P = {'-x^5+y^5-3*y-1','5*y^4-3','-20*x+y-z'}\n% \n% Output: S --- (matrix) numerical solutions (as columns of S)\n% var --- (cell array) the array of variables\n% For example, output\n% S = \n% -0.8264 + 0.6004i -0.6092 - 1.0165i\n% -0.8801 + 0.0000i -0.0000 - 0.8801i\n% 15.6482 -12.0086i 12.1831 +19.4496i\n%\n% var = {'x','y','z'}\n% means there are two numerical solutions \n% (x,y,z) = \n% (-0.8264+0.6004i, -0.8801+0.0000i, 15.6482-12.0086i)\n% (-0.6092-1.0165i, -0.8801+0.0000i, 12.1831+19.4496i)\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/psolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7798351707285194}} {"text": "function variance = quasigeometric_variance ( a, b )\n\n%*****************************************************************************80\n%\n%% QUASIGEOMETRIC_VARIANCE returns the variance of the Quasigeometric PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the probability of 0 successes.\n% 0.0 <= A <= 1.0.\n%\n% Input, real B, the depreciation constant.\n% 0.0 <= B < 1.0.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = ( 1.0 - a ) * ( a + b ) / ( 1.0 - b ) / ( 1.0 - b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/quasigeometric_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7797862373062479}} {"text": "function geometry_test0185 ( )\n\n%*****************************************************************************80\n%\n%% TEST0185 tests CIRCLE_PPPR2IMP_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 3;\n p_hi = 10.0;\n p_lo = -10.0;\n test_num = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0185\\n' );\n fprintf ( 1, ' CIRCLE_PPPR2IMP_3D is given 3D points P1, P2, P3,\\n' );\n fprintf ( 1, ' and a radius R,\\n' );\n fprintf ( 1, ' and determines the centers C of two circles\\n' );\n fprintf ( 1, ' of the given radius, passing through P1 and P2\\n' );\n fprintf ( 1, ' and lying in the plane of P1, P2 and P3.\\n' );\n\n seed = 123456789;\n\n for test = 1 : test_num\n\n [ p1, seed ] = r8vec_uniform ( dim_num, p_lo, p_hi, seed );\n [ p2, seed ] = r8vec_uniform ( dim_num, p_lo, p_hi, seed );\n [ p3, seed ] = r8vec_uniform ( dim_num, p_lo, p_hi, seed );\n\n r_lo = sqrt ( sum ( ( p1(1:dim_num) - p2(1:dim_num) ).^2 ) );\n r_hi = r_lo + 5.0;\n [ r, seed ] = r8_uniform ( r_lo, r_hi, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Radius R = %f\\n', r );\n\n fprintf ( 1, ' Point #1: %f %f %f\\n', p1(1:dim_num) );\n fprintf ( 1, ' Point #2: %f %f %f\\n', p2(1:dim_num) );\n fprintf ( 1, ' Point #3: %f %f %f\\n', p3(1:dim_num) );\n\n [ pc, normal ] = circle_pppr2imp_3d ( p1, p2, p3, r );\n\n fprintf ( 1, ' Center #1: %f %f %f\\n', pc(1:dim_num,1) );\n fprintf ( 1, ' Center #2: %f %f %f\\n', pc(1:dim_num,2) );\n%\n% Check that the points are the right distance from the center.\n%\n d11 = sqrt ( sum ( ( p1(1:dim_num) - pc(1:dim_num,1)' ).^2 ) );\n d21 = sqrt ( sum ( ( p2(1:dim_num) - pc(1:dim_num,1)' ).^2 ) );\n d12 = sqrt ( sum ( ( p1(1:dim_num) - pc(1:dim_num,2)' ).^2 ) );\n d22 = sqrt ( sum ( ( p2(1:dim_num) - pc(1:dim_num,2)' ).^2 ) );\n\n fprintf ( 1, ' %f %f %f %f\\n', d11, d21, d12, d22 );\n%\n% Check that the radial vector to the point is perpendicular to NORMAL.\n%\n d11 = normal(1:dim_num) * ( p1(1:dim_num) - pc(1:dim_num,1)' )';\n d21 = normal(1:dim_num) * ( p2(1:dim_num) - pc(1:dim_num,1)' )';\n d12 = normal(1:dim_num) * ( p1(1:dim_num) - pc(1:dim_num,2)' )';\n d22 = normal(1:dim_num) * ( p2(1:dim_num) - pc(1:dim_num,2)' )';\n\n fprintf ( 1, ' %f %f %f %f\\n', d11, d21, d12, d22 );\n\n end\n\n return\nend\n", "meta": {"author": "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_test0185.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7797152539325631}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Price European options under Regime Switching Diffusion Models using Monte Carlo simulation\n% Author: Justin Kirkby\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\n\naddpath('../')\n\n% ---------------------\n% Contract/Market Params\n% ---------------------\ncall = 1; %For call use 1 (else, its a put)\nS_0 = 100; %Initial price\nr = .05; %Interest rate\nq = .00; %dividend yield\nT = 1; %Time (in years)\nKvec = S_0*[.85 .90 .95 1 1.05 1.10 1.15 1.20 1.25 1.30 1.35 1.5 1.6]; % strikes to price\n\n% ---------------------\n% Regime Switching Diffusion Params\n% ---------------------\n% Transition Matrix (dictates how the regimes transition)\nQ = [-1 0.5 0.5;\n 0.5 -1 0.5; \n 0.5 0.5 -1]; \n\ndrift_vec = [r-q r-q r-q]; % Drift in each state\nsigma_vec = [0.15 0.25 0.35]; % Volatility in each state\n\ninitial_state = 1;\n\n% ---------------------\n% Sim Params\n% ---------------------\nN_sim = 5*10^5;\nM = 500;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmethod = 2; % 1 = Euler, biased; 2 = Unbiased\n\ntic\nif method == 1\n Spath = Simulate_RegimeSwitching_Diffusion_func( N_sim, M, T, S_0, drift_vec, sigma_vec, Q, initial_state);\n\nelse\n Spath = Simulate_RegimeSwitching_Diffusion_Unbiased( N_sim, T, S_0, drift_vec, sigma_vec, Q, initial_state);\nend\ntime = toc\n\nhistogram(Spath)\n\ndisc = exp(-r*T);\n[prices, stdErrs] = Price_MC_European_Strikes_func(Spath, disc, call, Kvec )\n\nplot(Kvec, prices)\nylabel('price')\nxlabel('strike')\ngrid on;\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Monte_Carlo/European/Script_European_RegimeSwitching.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7797152530187902}} {"text": "function fx = p07_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P07_FUN evaluates the integrand for problem 7.\n%\n% Discussion:\n%\n% The integrand is singular at x = 0.\n%\n% Interval:\n%\n% 0 <= x <= 1\n%\n% Integrand:\n%\n% 1 / sqrt ( x )\n%\n% Antiderivative:\n%\n% 2 * sqrt ( x )\n%\n% Exact Integral:\n%\n% 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% David Kahaner,\n% Comparison of Numerical Quadrature Formulas,\n% in Mathematical Software, edited by John R Rice,\n% Academic Press, 1971\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n fx = 1.0 ./ sqrt ( x );\n%\n% Replace \"Inf\" value at 0 by 0.\n%\n i = find ( x == 0.0 );\n fx(i) = 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_int/p07_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.7797081107307539}} {"text": "function node=orthdisk(c0,c1,r,ndiv)\n%\n% node=orthdisk(c0,c1,r,ndiv)\n%\n% Defining a 3D disk that is orthogonal to the vector c1-c0 \n%\n% author: Qianqian Fang (fangq nmr.mgh.harvard.edu)\n%\n% input:\n% c0: a 1x3 vector for the origin\n% c1: a 1x3 vector to define a direction vector c1-c0\n% r: the radius of the disk that is orthogonal to c1-c0, passing through c0\n% ndiv: division count to approximate a circle by a polygon, if ignored, ndiv=20\n%\n% output:\n% node: the 3D vertices of the disk\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nlen=sqrt(sum((c0-c1).*(c0-c1)));\nv0=c1-c0;\n\nif(nargin<=2)\n r=1;\nend\nif(nargin<=3)\n ndiv=20;\nend\n\ndt=2*pi/ndiv;\ntheta=dt:dt:2*pi;\ncx=r*cos(theta);\ncy=r*sin(theta);\npp=[cx(:) cy(:) zeros(ndiv,1)];\nnode=rotatevec3d(pp,v0)+repmat(c0(:)',size(pp,1),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/iso2mesh/orthdisk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7797080885565091}} {"text": "function out = angles(n)\n%ANGLES Return the angles of the Chebyshev points of 1st kind in [-1, 1].\n% CHEBTECH1.ANGLES(N) returns ACOS(X), where X are the N Chebyshev points of\n% the 1st kind in [-1, 1].\n%\n% See also POINTS, CHEBPTS, LENGTH.\n%\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nout = (n-.5:-1:.5).'*pi/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/@chebtech1/angles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.779680827152647}} {"text": "function [g,tfr]=psech(L,p2,p3,p4)\n%PSECH Sampled, periodized hyperbolic secant\n% Usage: g=psech(L);\n% g=psech(L,tfr);\n% g=psech(L,s,'samples);\n% [g,tfr]=psech( ... );\n%\n% Input parameters:\n% L : Length of vector.\n% tfr : ratio between time and frequency support.\n% Output parameters:\n% g : The periodized hyperbolic cosine.\n%\n% `psech(L,tfr)` computes samples of a periodized hyperbolic secant.\n% The function returns a regular sampling of the periodization\n% of the function $sech(\\pi\\cdot x)\n%\n% The returned function has norm equal to 1.\n%\n% The parameter *tfr* determines the ratio between the effective support\n% of *g* and the effective support of the DFT of *g*. If $tfr>1$ then *g*\n% has a wider support than the DFT of *g*.\n%\n% `psech(L)` does the same setting $tfr=1$.\n%\n% `psech(L,s,'samples')` returns a hyperbolic secant with an effective\n% support of *s* samples. This means that approx. 96% of the energy or 74%\n% or the area under the graph is contained within *s* samples. This is\n% equivalent to `psech(L,s^2/L)`.\n%\n% `[g,tfr] = psech( ... )` additionally returns the time-to-frequency\n% support ratio. This is useful if you did not specify it (i.e. used\n% the `'samples'` input format).\n%\n% The function is whole-point even. This implies that `fft(psech(L,tfr))`\n% is real for any *L* and *tfr*.\n%\n% If this function is used to generate a window for a Gabor frame, then\n% the window giving the smallest frame bound ratio is generated by\n% `psech(L,a*M/L)`.\n%\n% Examples:\n% ---------\n%\n% This example creates a `psech` function, and demonstrates that it is\n% its own Discrete Fourier Transform:::\n%\n% g=psech(128);\n%\n% % Test of DFT invariance: Should be close to zero.\n% norm(g-dft(g))\n% \n% The next plot shows the `psech` in the time domain compared to the Gaussian:::\n%\n% plot((1:128)',fftshift(pgauss(128)),...\n% (1:128)',fftshift(psech(128)));\n% legend('pgauss','psech');\n% \n% The next plot shows the `psech` in the frequency domain on a log\n% scale compared to the Gaussian:::\n%\n% hold all;\n% magresp(pgauss(128),'dynrange',100);\n% magresp(psech(128),'dynrange',100);\n% legend('pgauss','psech');\n% \n% The next plot shows `psech` in the time-frequency plane:::\n% \n% sgram(psech(128),'tc','nf','lin');\n%\n% See also: pgauss, pbspline, pherm\n%\n% References: jast02-1\n\ncomplainif_argnonotinrange(nargin,1,4,mfilename);\n\nif nargin==1\n tfr=1;\nend;\n\nif size(L,1)>1 || size(L,2)>1\n error('L must be a scalar');\nend;\n\nif rem(L,1)~=0\n error('L must be an integer.')\nend;\n\nswitch(nargin)\n case 1\n tfr=1;\n cent=0;\n case 2\n tfr=p2;\n cent=0;\n case 3\n if ischar(p3)\n switch(lower(p3))\n case {'s','samples'}\n tfr=p2^2/L;\n otherwise\n error('Unknown argument %s',p3);\n end;\n cent=0;\n else\n tfr=p2;\n cent=p3;\n end;\n case 4\n tfr=p2^2/L;\n cent=p4;\nend;\n\nsafe=12;\n\ng=zeros(L,1);\nsqrtl=sqrt(L);\n\nw=tfr;\n\n% Outside the interval [-safe,safe] then sech(pi*x) is numerically zero.\nnk=ceil(safe/sqrt(L/sqrt(w)));\n\nlr=(0:L-1).';\nfor k=-nk:nk \n g=g+sech(pi*(lr/sqrtl-k*sqrtl)/sqrt(w));\nend;\n\n% Normalize it.\ng=g*sqrt(pi/(2*sqrt(L*w)));\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/fourier/psech.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7796808234880096}} {"text": "function [zp,exitFlag]=nearestPointInEllipsoid(z,A,p,gammaVal,method,varargin)\n%%NEARESTPOINTONELLIPSOID Given an ellipsoid such that a point zp on the\n% surface of the ellipsoid satisfies the equation\n% (z-zp)'*A*(z-zp)=gammaVal find the point on or inside the\n% ellipsoid that is closest to another point p. This function\n% differs from nearestPointOnEllipsoid in that it will return the\n% original point if the point is inside of the ellipsoid.\n%\n%INPUTS: z The numDimX1 center of the ellipsoid.\n% A A numDimXnumDim symmetric, positive definite matrix that\n% specifies the size and shape of the ellipse or ellipsoid, where\n% a point zp is on the ellipse/ellipsoid if\n% (zp-z)'*A*(zp-z)=gammaVal.\n% p A numDimX1 point.\n% gammaVal The threshold for declaring a point to be in the ellipsoid. If\n% this parameter is omitted or an empty matrix is passed, the\n% default value of 1 is used.\n% method Two algorithms are available to solve the problem. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is passed.\n% Determine whether the point is in the ellipse; if so, return\n% it. Otherwise, call the function nearestPointOnEllipsoid.\n% 1 Solve the problem by refomrulating it as a quadratic\n% programming problem with quadratic constrains and use the\n% constrainedLSSpher function.\n% varargin When using method 0, this just just be 'epsVal' followed by a\n% number to set the epsVal parameter of the\n% nearestPointOnEllipsoid function, if it is used. Otherwise, if\n% method =1, this is any parameters that one wishes to pass to the\n% fzero function. These are generally comma-separated things, such\n% as 'TolX',1e-12. \n%\n%OUTPUTS: zp The numDimX1 point on the ellipse that is closest to p. If the\n% algorithm fails, then an empty matrix is returned.\n% exitFlag The exit flag from the fzero function, if used. Otherwise, if\n% the point is inside of the ellipsoid, this is 0.\n%\n%If we say that B=A/gammaVal, then points on the surface of the ellipsoid\n%satisfy the equation\n%(zp-z)'*B*(zp-z)<=1\n%We want to minimize the squared distance\n%s^2=(zp-p)'*(zp-p)\n%Subject to the point being on the ellipsoid. Let L be the lower-triangular\n%Cholesky decomposition of B and say that\n%y=L'*(zp-z)\n%which is equivalent to\n%zp=z+inv(L)'*y\n%Then the constraint for a point being on the ellipsoid is y'*y<=1 and,\n%after dropping constant terms, the squared distance that we want to\n%minimize becomes\n%(inv(L)'*y+z-p)'*(inv(L)'*y+z-p)\n%Thus, the problem is a quadratic programming problem with a quadratic\n%constraint (that y is unit magnitude). If method=1, then this problem is\n%solved using the constrainedLSSpher function.\n%\n%EXAMPLE 1:\n%This is a 2D example that can be easily plotted. The point is outside the\n%ellipse.\n% A=[0.1,0;\n% 0,10];\n% z=[0;10];\n% p=[6;10];\n% M=[0.413074198133900, 0.910697373904216;\n% -0.910697373904216, 0.413074198133900];%A rotation matrix\n% A=M*A*M';\n% [zp,exitCode]=nearestPointInEllipsoid(z,A,p);\n% figure(1)\n% clf\n% hold on\n% axis([-6,6,-6+10,6+10])\n% axis square\n% drawEllipse(z,A,1,'g','linewidth',2)\n% plot([p(1),zp(1)],[p(2),zp(2)],'--c')\n% scatter(p(1),p(2),'ok','linewidth',2)\n% scatter(zp(1),zp(2),'xr','linewidth',2)\n%\n%EXAMPLE 2:\n%This is another 2D example. In this instance, the point is inside the\n%ellipse, so the point itself is the closest point on or in the ellipse.\n% A=[1,0;\n% 0,5];\n% z=[0;10];\n% p=[0.5;10];\n% [zp,exitCode]=nearestPointInEllipsoid(z,A,p);\n% figure(1)\n% clf\n% hold on\n% axis([-6,6,-6+10,6+10])\n% axis square\n% drawEllipse(z,A,1,'g','linewidth',2)\n% plot([p(1),zp(1)],[p(2),zp(2)],'--c')\n% scatter(p(1),p(2),'ok','linewidth',2)\n% scatter(zp(1),zp(2),'xr','linewidth',2)\n%\n%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(gammaVal))\n gammaVal=1; \nend\n\nif(nargin<5||isempty(method))\n method=0; \nend\n\nswitch(method)\n case 0%Use the polynomial method.\n opts.epsVal=[];\n opts=addCelListToStruct(opts,varargin);\n epsVal=opts.epsVal;\n \n diff=(z-p);\n if(diff'*A*diff-gammaVal<=0)\n exitFlag=0;\n zp=z;\n return;\n else\n zp=nearestPointOnEllipsoid(z,A,p,gammaVal,epsVal);\n if(~isempty(zp))\n exitFlag=1;\n else\n exitFlag=-1;\n end\n end\n case 1%Use the constrainedLSSpher function rather than the polynomial\n %method.\n B=A/gammaVal;\n L=chol(B,'lower');\n\n A=inv(L)';\n b=p-z;\n\n [y,~,exitFlag]=constrainedLSSpher(A,b,1,varargin{:});\n \n if(exitFlag==0)\n exitFlag=1; \n end\n \n if(~isempty(y))\n zp=z+A*y;\n else\n zp=[];\n end\n otherwise\n error('Unknown method specified.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/nearestPointInEllipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7796808090079823}} {"text": "function kl = kldivGaussian(mean1, cov1, mean2, cov2)\n\n% KLDIVGAUSSIAN Give the KL divergence between two Gaussians.\n% FORMAT\n% DESC returns the Kullback-Leibler divergence between two\n% Gaussians with given means and covariances.\n% ARG mean1 : mean of the first Gaussian.\n% ARG cov1 : covariance of the first Gaussian.\n% ARG mean2 : mean of the second Gaussian.\n% ARG cov2 : covariance of the second Gaussian.\n%\n% SEEALSO : logdet, pdinv\n%\n% COPYRIGHT : Neil D. Lawrence, 2005\n\n% NDLUTIL\n\n[invCov2, U] = pdinv(cov2);\nlogDet2 = logdet(cov2, U);\nlogDet1 = logdet(cov1);\nN = size(cov1, 1);\nmeanDiff = mean1 - mean2;\nif size(meanDiff, 1) == 1\n meanDiff = meanDiff';\nend\nkl = -0.5*(logDet1 - logDet2 - trace(cov1*invCov2) ...\n + N - meanDiff'*invCov2*meanDiff);\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/kldivGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551505674445, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7796678085413334}} {"text": "function x = beta_inv(p, a, b)\n% PURPOSE: inverse of the cdf (quantile) of the beta(a,b) distribution\n%--------------------------------------------------------------\n% USAGE: x = beta_inv(p,a,b)\n% where: p = vector of probabilities\n% a = beta distribution parameter, a = scalar\n% b = beta distribution parameter b = scalar\n% NOTE: mean [beta(a,b)] = a/(a+b), variance = ab/((a+b)*(a+b)*(a+b+1))\n%--------------------------------------------------------------\n% RETURNS: x at each element of p for the beta(a,b) distribution\n%--------------------------------------------------------------\n% SEE ALSO: beta_d, beta_pdf, beta_inv, beta_rnd\n%--------------------------------------------------------------\n\n% Anders Holtsberg, 18-11-93\n% Copyright (c) Anders Holtsberg\n% documentation modified by LeSage to\n% match the format of the econometrics toolbox\n\nif (nargin ~= 3)\n error('Wrong # of arguments to beta_inv');\nend\n \nif any(any((a<=0)|(b<=0)))\n error('beta_inv parameter a or b is nonpositive');\nend\nif any(any(abs(2*p-1)>1))\n error('beta_inv: A probability should be 0<=p<=1');\nend\n\nx = a ./ (a+b);\ndx = 1;\nwhile any(any(abs(dx)>256*eps*max(x,1)))\n dx = (betainc(x,a,b) - p) ./ beta_pdf(x,a,b);\n x = x - dx;\n x = x + (dx - x) / 2 .* (x<0);\nend\n \n\n \n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/OldVersions/v2dot0/Auxiliary/beta_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7796163967999735}} {"text": "function d = det3(A)\n\n% det3 - 3x3 determinant\n%\n% d = det3(A);\n%\n% A is a [3 3 n] matrix, d is a vector of size d where\n% d(i)=det(A(:,:,i)).\n%\n% It computes explicitely the det by expanding along the 1st columns 2x2\n% determinant. Faster than recursive loops.\n%\n% Note: works also for 2x2 det.\n% Note: for higher order det, use loop\n%\n% Copyright (c) 2008 Gabriel Peyre\n\nif size(A,1)==2 && size(A,2)==2\n %% 2x2 Det %%\n d = A(1,1,:).*A(2,2,:) - A(1,2,:).*A(2,1,:);\nelseif size(A,1)==3 && size(A,2)==3\n %% 3x3 Det %%\n d = A(1,1,:).*( A(2,2,:).*A(3,3,:) - A(2,3,:).*A(3,2,:) ) - ...\n A(1,2,:).*( A(2,1,:).*A(3,3,:) - A(2,3,:).*A(3,1,:) ) + ...\n A(1,3,:).*( A(2,1,:).*A(3,2,:) - A(2,2,:).*A(3,1,:) );\nelse\n n = size(A,3);\n d = zeros(n,1);\n for i=1:n\n d(i) = det(A(:,:,i));\n end\nend\nd = d(:);\n", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_misc/det3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7795623489666357}} {"text": "function [BFtest] = BFtest(X,alpha)\n%Brown-Forsythe's Test for Homogeneity of Variances.\n%[In the Brown-Forsythe's test the data are transforming to yij = abs[xij - median(xj)]\n%and uses the F distribution performing an one-way ANOVA using y as the \n%dependent variable. The Brown-Frosythe statistic is corrected for artificial zeros \n%occurring in odd sized samples.\n%\n% Syntax: function [BFtest] = BFtest(X,alpha) \n% \n% Inputs:\n% X - data matrix (Size of matrix must be n-by-2; data=column 1, sample=column 2). \n% alpha - significance level (default = 0.05).\n% Outputs:\n% - Sample variances vector.\n% - Whether or not the homoscedasticity was met.\n%\n% Example: From the example 10.1 of Zar (1999, p.180), to test the Brown-Forsythe's\n% homoscedasticity of data with a significance level = 0.05.\n%\n% Diet\n% ---------------------------------\n% 1 2 3 4\n% ---------------------------------\n% 60.8 68.7 102.6 87.9\n% 57.0 67.7 102.1 84.2\n% 65.0 74.0 100.2 83.1\n% 58.6 66.3 96.5 85.7\n% 61.7 69.8 90.3\n% ---------------------------------\n% \n% Data matrix must be:\n% X=[60.8 1;57.0 1;65.0 1;58.6 1;61.7 1;68.7 2;67.7 2;74.0 2;66.3 2;69.8 2;\n% 102.6 3;102.1 3;100.2 3;96.5 3;87.9 4;84.2 4;83.1 4;85.7 4;90.3 4];\n%\n% Calling on Matlab the function: \n% BFtest(X)\n%\n% Answer is:\n%\n% The number of samples are: 4\n%\n% ----------------------------\n% Sample Size Variance\n% ----------------------------\n% 1 5 9.3920\n% 2 5 8.5650\n% 3 4 7.6567\n% 4 5 8.3880\n% ----------------------------\n% \n% Brown-Forsythe's Test for Equality of Variances F=0.0831, df1= 3, df2=15\n% Probability associated to the F statistic = 0.9682\n% The associated probability for the F test is larger than 0.05\n% So, the assumption of homoscedasticity was met. \n%\n\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n%\n% April 19, 2003.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A. and R. Hernandez-Walls. (2003). BFtest: Brown-Forsythe's test for homogeneity of \n% variances. A MATLAB file. [WWW document]. URL http://www.mathworks.com/matlabcentral/fileexchange/\n% loadFile.do?objectId=3412&objectType=FILE\n%\n% References:\n% \n% Brown, M. B. and Forsythe, A. B. (1974), Robust Tests for \n% the Equality of Variances. Journal of the American \n% Statistical Association, 69:364-367.\n% Zar, J. H. (1999), Biostatistical Analysis (2nd ed.).\n% NJ: Prentice-Hall, Englewood Cliffs. p. 180. \n%\n\nif nargin < 2,\n alpha = 0.05;\nend \n\nY=X;\nk=max(Y(:,2));\nfprintf('The number of samples are:%2i\\n\\n', k);\n\n%Brown-Forsythe's Procedure.\nn=[];s2=[];Z=[];\nindice=Y(:,2);\nfor i=1:k\n Ye=find(indice==i);\n eval(['Y' num2str(i) '=Y(Ye,1);']);\n eval(['mdY' num2str(i) '=median(Y(Ye,1));']);\n eval(['n' num2str(i) '=length(Y' num2str(i) ') ;']);\n eval(['s2' num2str(i) '=(std(Y' num2str(i) ').^2) ;']);\n eval(['Z' num2str(i) '= abs((Y' num2str(i) ') - mdY' num2str(i) ');']);\n eval(['xn= n' num2str(i) ';']);\n eval(['xs2= s2' num2str(i) ';']);\n eval(['x= Z' num2str(i) ';']);\n n=[n;xn];s2=[s2;xs2];Z=[Z;x];\nend\n\nfprintf('-----------------------------\\n');\ndisp(' Sample Size Variance')\nfprintf('-----------------------------\\n');\nfor i=1:k\n fprintf(' %d %2i %.4f\\n',i,n(i),s2(i))\nend\nfprintf('-----------------------------\\n');\ndisp(' ')\n\nY=[Z Y(:,2)];\n\n%Correction for artificial zeros occurring in odd sized samples.\nfor i=1:k\n Ye=find(Y(:,2)==i);\n ncero=find((Y(:,1)==0)&(Y(:,2)==i));\n Y(ncero,1)=999;\n Y(ncero,1)=min(Y(Ye,1));\nend\n\n%Analysis of variance procedure.\nC=(sum(Y(:,1)))^2/length(Y(:,1)); %correction term.\nSST=sum(Y(:,1).^2)-C; %total sum of squares.\ndfT=length(Y(:,1))-1; %total degrees of freedom.\n\nindice=Y(:,2);\nfor i=1:k\n Ye=find(indice==i);\n eval(['A' num2str(i) '=Y(Ye,1);']);\nend\n\nA=[];\nfor i=1:k\n eval(['x =((sum(A' num2str(i) ').^2)/length(A' num2str(i) '));']);\n A=[A,x];\nend\n\nSSA=sum(A)-C; %sample sum of squares.\ndfA=k-1; %sample degrees of freedom.\nSSE=SST-SSA; %error sum of squares.\ndfE=dfT-dfA; %error degrees of freedom.\nMSA=SSA/dfA; %sample mean squares.\nMSE=SSE/dfE; %error mean squares.\nF=MSA/MSE; %Brown-Forsythe's F-statistic.\nv1=dfA;df1=v1;\nv2=dfE;df2=v2;\n\nP = 1 - fcdf(F,v1,v2); %probability associated to the F-statistic. \n\nfprintf('Brown-Forsythe''s Test for Equality of Variances F=%3.4f, df1=%2i, df2=%2i\\n', F,df1,df2);\nfprintf('Probability associated to the F statistic = %3.4f\\n', P);\n\nif P >= alpha;\n fprintf('The associated probability for the F test is equal or larger than% 3.2f\\n', alpha);\n fprintf('So, the assumption of homoscedasticity was met.\\n');\nelse\n fprintf('The associated probability for the F test is smaller than% 3.2f\\n', alpha);\n fprintf('So, the assumption of homoscedasticity was not met.\\n');\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3510-homvar/BFtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7795117169817234}} {"text": "function [Ns ach_rcu ach_dt ach_gal conv normapx_val] = plot_all(delta, epsil);\n\nif (nargin < 1) || isempty(delta)\n\tdelta = 0.11;\nend\nif (nargin < 2) || isempty(epsil)\n\tepsil = 1e-3;\nend\n\nNs = 50:50:2000;\nNs_cap = [Ns(1) Ns(end)];\ncap = 1 + delta.*log2(delta) + (1-delta).*log2(1-delta);\nCapr = cap + Ns_cap*0;\n\n\nnormapx_val = normapx(Ns, delta, epsil);\nconv = converse(Ns, delta,epsil);\nach_gal = gallager_ach(Ns, delta, epsil);\nach_dt = dt_ach(Ns, delta, epsil);\n\n% Compute RCU bound\nach_rcu = [];\nfor idx=1:length(Ns);\n\tn=Ns(idx);\n\t% provide good bracket for speeding up\n\tplow = max(ach_gal(idx),ach_dt(idx));\n\tpup = conv(idx);\n\tach_rcu(idx) = rcu_ach(n, delta, epsil, plow, pup);\nend;\n\n\n%% normal approximation\nfigure;\nplot(Ns_cap, Capr, 'r--', Ns, conv./Ns, 'r', Ns, normapx_val./Ns, 'k-', Ns, ach_rcu./Ns, 'b', Ns, ach_dt./Ns, 'b--', ...\n\tNs, ach_gal./Ns, 'b-.');\nxlabel('Blocklen, n'); ylabel('Rate, R'); ylim([0 1.05*cap]);\ntitle(sprintf('Bounds for the BSC(%g), P_{e,max} = %g', delta, epsil));\nlegend('Capacity', 'Converse', 'Normal approximation', 'RCU achievability', 'DT achievability', 'Gallager achievability', 'Location', 'SouthEast');\ngrid on\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/bsc/plot_all.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7794524355688135}} {"text": "function x=fhtnat(data)\n% The function implement the 1D natural(Hadamard) ordered fast Hadamard transform,\n% wchich can be used in signal processing, pattern recongnition and Genetic alogorithms.\n% This algorithm uses a Cooley-Tukey type signal flow graph and is implemented in N log2 N\n% additions and subtractions. Data sequence length must be an integer power of 2.\n% \n% The inverse transform is the same as the forward transform except for the multiplication factor N.\n% \n% Example:\n% x=[1 2 1 1];\n% W=fhtnat(x);\n% \n% Author: Gylson Thomas\n% e-mail: gylson_thomas@yahoo.com\n% Asst. Professor, Electrical and Electronics Engineering Dept.\n% MES College of Engineering Kuttippuram,\n% Kerala, India, December 2006.\n% copyright 2006.\n% Reference: N.Ahmed, K.R. Rao, \"Orthogonal Transformations for \n% Digital Signal Processing\" Spring Verlag, New York 1975. page-111.\nN = length(data);\nx=data;\nL=log2(N);\nk1=N; k2=1; k3=N/2;\nfor i1=1:L %In-place iterations begins here\n L1=1;\n for i2=1:k2\n for i3=1:k3\n i=i3+L1-1; j=i+k3;\n temp1= x(i); temp2 = x(j); \n x(i) = temp1 + temp2;\n x(j) = temp1 - temp2;\n end\n L1=L1+k1;\n end\n k1 = k1/2; k2 = k2*2; k3 = k3/2;\nend\nx=inv(N)*x; %Delete this line for inverse transform\n\n\nfunction x=fhtdya(data)\n% The function implement the 1D dyadic (Paley) ordered fast Hadamard transform,\n% wchich can be used in signal processing, pattern recongnition and Genetic alogorithms.\n% This algorithm uses a Cooley-Tukey type signal flow graph and is implemented in N log2 N\n% additions and subtractions. Data sequence length must be an integer power of 2.\n% \n% The inverse transform is the same as the forward transform except for the multiplication factor N.\n% \n% Example:\n% x=[1 2 1 1];\n% W=fhtdya(x);\n% \n% Author: Gylson Thomas\n% e-mail: gylson_thomas@yahoo.com\n% Asst. Professor, Electrical and Electronics Engineering Dept.\n% MES College of Engineering Kuttippuram,\n% Kerala, India, December 2006.\n% copyright 2006.\n% Reference: N.Ahmed, K.R. Rao, \"Orthogonal Transformations for \n% Digital Signal Processing\" Spring Verlag, New York 1975. page-111.\n\nN = length(data);\nx=bitrevorder(data);\nL=log2(N);\nk1=N; k2=1; k3=N/2;\nfor i1=1:L %In-place iteration begins here\n L1=1;\n for i2=1:k2\n for i3=1:k3\n i=i3+L1-1; j=i+k3;\n temp1= x(i); temp2 = x(j); \n x(i) = temp1 + temp2;\n x(j) = temp1 - temp2;\n end\n L1=L1+k1;\n end\n k1 = k1/2; k2 = k2*2; k3 = k3/2;\nend\nx=inv(N)*x; %Delete this line for inverse transform\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13247-natural-hadamard-and-dyadic-paley-ordered-fast-hadamard-transform/fht.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7794524247370755}} {"text": "%DEMO_REGRESSION_ADDITIVE1 Regression demonstration with additive model\n%\n% Description\n% A regression demonstration with one input variable and one output\n% variable with Gaussian noise. The output is assumed to be\n% realization of two additive functions and Gaussian noise.\n%\n% The model constructed is following:\n%\n% The observations y are assumed to satisfy\n%\n% y = f + g + e, where e ~ N(0, s^2).\n%\n% f and g are underlying latent functions, which we are\n% interested in. We place a zero mean Gaussian process prior for\n% them, which implies that at the observed input locations\n% latent values have prior\n%\n% f ~ N(0, Kf) and g ~ N(0,Kg)\n%\n% where K is the covariance matrix, whose elements are given as\n% K_ij = k(x_i, x_j | th). The function k(x_i, x_j | th) is\n% covariance function and th its parameters.\n%\n% Since both likelihoods and prior are Gaussian, we obtain a\n% Gaussian marginal likelihood\n%\n% p(y|th) = N(0, Kf + Kg + I*s^2).\n% \n% By placing a prior for parameters, p(th), we can find the\n% maximum a posterior (MAP) estimate for them by maximizing\n%\n% argmax log p(y|th) + log p(th).\n% th\n%\n% After finding MAP estimate or posterior samples of parameters,\n% we can use them to make predictions for the latent functions. \n% For example, the posterior predictive distribution of f is:\n%\n% p(f | y, th) = N(m, S),\n% m = Kf * (Kf + Kg + s^2I)^(-1) * y\n% S = Kf - Kf * (Kf + Kg + s^2I)^(-1) * Kf\n%\n% (We could integrate also over the parameters with, for\n% example, grid integration or MCMC. This is not demonstrated\n% here but it is done exactly similarly as in the\n% demo_regression1.)\n% \n% The demo is organised in four parts:\n% 1) data analysis with full GP model\n% 2) data analysis with FIC approximation\n% 3) data analysis with PIC approximation\n% 4) data analysis with CS+FIC model\n%\n% For more detailed discussion of Gaussian process regression\n% see Rasmussen and Williams (2006) and for a detailed\n% discussion on sparse additive models see Vanhatalo and Vehtari\n% (2008).\n%\n% References:\n%\n% Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian\n% Processes for Machine Learning. The MIT Press.\n%\n% Vanhatalo, J. and Vehtari, A. (2008). Modelling local and global\n% phenomena with sparse Gaussian processes. Proceedings of the 24th\n% Conference on Uncertainty in Artificial Intelligence.\n%\n% See also \n% DEMO_REGRESSION1, DEMO_SPARSEREGRESION\n%\n\n% Copyright (c) 2008-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n%========================================================\n% PART 1 data analysis with full GP model\n%========================================================\n\n% Load the data\nS = which('demo_regression1');\nL = strrep(S,'demo_regression1.m','demodata/maunaloa_data.txt');\ndata=load(L);\ny = data(:, 2:13);\ny=y';\ny=y(:);\nx = [1:1:length(y)]';\nx = x(y>0); % Remove contaminated observations\ny = y(y>0);\navgy = mean(y);\ny = y-avgy;\nxt = [0:0.5:565]';\n\n[n,nin] = size(x);\n% Now 'x' consist of the inputs and 'y' of the output. \n% 'n' and 'nin' are the number of data points and the \n% dimensionality of 'x' (the number of inputs).\n\n% ---------------------------\n% --- Construct the model ---\n% \n% First create squared exponential and piecewise polynomial 2\n% covariance functions and Gaussian noise structures and set\n% priors for their parameters (if SuiteSparse is not\n% installed, use gpcf_sexp instead of gpcf_ppcs2)\npl1 = prior_t('s2', 100, 'nu', 10);\npl2 = prior_t('s2', 10, 'nu', 10);\npm1 = prior_sqrtt('s2',300);\npm2 = prior_sqrtt('s2',10);\npn = prior_logunif();\ngpcf1 = gpcf_sexp('lengthScale', 100, 'magnSigma2', 200, 'lengthScale_prior', pl1, 'magnSigma2_prior', pm1);\nif exist('ldlchol')\n gpcf2 = gpcf_ppcs2('nin', nin, 'lengthScale', 5, 'magnSigma2', 5, 'lengthScale_prior', pl2, 'magnSigma2_prior', pm2);\nelse\n warning('GPstuff:SuiteSparseMissing',...\n ['SuiteSparse is not properly installed. (in BECS try ''use suitesparse'')\\n' ...\n 'Using gpcf_sexp (non-compact support) instead of gpcf_ppcs2 (compact support)']);\n gpcf2 = gpcf_sexp('lengthScale', 5, 'magnSigma2', 1, 'lengthScale_prior', pl2, 'magnSigma2_prior', pm);\nend\nlik = lik_gaussian('sigma2', 0.1, 'sigma2_prior', pn);\n\n% Create the GP structure\ngp = gp_set('lik', lik, 'cf', {gpcf1, gpcf2}, 'jitterSigma2', 1e-9) \n\n% -----------------------------\n% --- Conduct the inference ---\n%\n% --- MAP estimate -----------\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'opt',opt);\n\n% Make predictions. Below Ef_full is the predictive mean and Varf_full\n% the predictive variance.\n[Eft_full, Varft_full, lpyt_full, Eyt_full, Varyt_full] = gp_pred(gp, x, y, xt, 'yt', ones(size(xt)));\n[Eft_full1, Varft_full1] = gp_pred(gp, x, y, xt, 'predcf', 1);\n[Eft_full2, Varft_full2] = gp_pred(gp, x, y, xt, 'predcf', 2);\n\n% Plot the prediction and data\nfigure\nsubplot(2,1,1)\nhold on\nplot(x,y,'.', 'MarkerSize',7)\nplot(xt,Eyt_full,'k', 'LineWidth', 2)\nplot(xt,Eyt_full-2.*sqrt(Varyt_full),'g--')\nplot(xt,Eyt_full+2.*sqrt(Varyt_full),'g--')\naxis tight\ncaption1 = sprintf('Full GP: l_1= %.2f, s^2_1 = %.2f, \\n l_2= %.2f, s^2_2 = %.2f \\n s^2_{noise} = %.2f', gp.cf{1}.lengthScale, gp.cf{1}.magnSigma2, gp.cf{2}.lengthScale, gp.cf{2}.magnSigma2, gp.lik.sigma2);\ntitle(caption1)\nlegend('Data point', 'predicted mean', '2\\sigma error',4)\n\nsubplot(2,1,2)\n[AX, H1, H2] = plotyy(xt, Eft_full2, xt, Eft_full1);\nset(H2,'LineStyle','--')\nset(H2, 'LineWidth', 2)\n%set(H1, 'Color', 'k')\nset(H1,'LineStyle','-')\nset(H1, 'LineWidth', 0.8)\ntitle('The long and short term trend')\n\n%========================================================\n% PART 2 data analysis with FIC approximation\n%========================================================\n\n% Here we conduct the same analysis as in part 1, but this time \n% using FIC approximation. Notice that both covariance components \n% utilize the inducing inputs. This leads to problems since the \n% number of inducing inputs is too small to capture the short term \n% variation. In CS+FIC (later model) the compact support function \n% does not utilize the inducing inputs and for this reason it is\n% able to capture also the fast variations.\n\n% Place inducing inputs evenly\nXu = [min(x):24:max(x)+10]';\n\n% Create the FIC GP structure\ngp_fic = gp_set('type', 'FIC', 'lik', lik, 'cf', {gpcf1,gpcf2}, 'jitterSigma2', 1e-9, 'X_u', Xu)\n\n% -----------------------------\n% --- Conduct the inference ---\n\n% --- MAP estimate using modified Newton algorithm ---\n\n% Now you can choose, if you want to optimize only parameters or \n% optimize simultaneously parameters and inducing inputs. Note that \n% the inducing inputs are not transformed through logarithm when packed\n\n%gp_fic = gp_set(gp_fic, 'infer_params', 'covariance+likelihood+inducing'); % optimize parameters and inducing inputs\ngp_fic = gp_set(gp_fic, 'infer_params', 'covariance+likelihood'); % optimize only parameters\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_fic=gp_optim(gp_fic,x,y,'opt',opt);\n\n% Make the prediction\n[Eft_fic, Varft_fic, lpyt_fic, Eyt_fic, Varyt_fic] = gp_pred(gp_fic, x, y, xt, 'yt', ones(size(xt)));\n\n% Plot the solution of FIC\nfigure\n%subplot(4,1,1)\nhold on\nplot(x,y,'.', 'MarkerSize',7)\nplot(xt,Eyt_fic,'k', 'LineWidth', 2)\nplot(xt,Eyt_fic-2.*sqrt(Varyt_fic),'g--', 'LineWidth', 2)\nplot(gp_fic.X_u, -30, 'rx', 'MarkerSize', 5, 'LineWidth', 2)\nplot(xt,Eyt_fic+2.*sqrt(Varyt_fic),'g--', 'LineWidth', 2)\naxis tight\ncaption2 = sprintf('FIC: l_1= %.2f, s^2_1 = %.2f, \\n l_2= %.2f, s^2_2 = %.2f \\n s^2_{noise} = %.2f', gp_fic.cf{1}.lengthScale, gp_fic.cf{1}.magnSigma2, gp_fic.cf{2}.lengthScale, gp_fic.cf{2}.magnSigma2, gp_fic.lik.sigma2);\ntitle(caption2)\nlegend('Data point', 'predicted mean', '2\\sigma error', 'inducing input','Location','Northwest')\n\n\n%========================================================\n% PART 3 data analysis with PIC approximation\n%========================================================\n\n% set the data points into clusters\nedges = linspace(-1,max(x)+1,20);\ntot=0; \nfor i=1:length(edges)-1\n trindex{i} = find(x>edges(i) & x 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\nif iscell(P); S = size(P{1},1); else S = size(P,1); end;\nif discount <= 0 || discount > 1\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1]')\n disp('--------------------------------------------------------')\nelseif size(Vprev,1) ~= S\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Vprev must have the same dimension as P')\n disp('--------------------------------------------------------')\nelse\n \n if iscell(P)\n A = length(P);\n for a=1:A \n Q(:,a) = PR(:,a) + discount*P{a}*Vprev;\n end\n else\n A = size(P,3);\n for a=1:A\n Q(:,a) = PR(:,a) + discount*P(:,:,a)*Vprev;\n end\n end\n [V, policy] = max(Q,[],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/25786-markov-decision-processes-mdp-toolbox/MDPtoolbox/mdp_bellman_operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7793834617542947}} {"text": "function op = smooth_logsumexp(sigma)\n% SMOOTH_LOGSUMEXP The function log(sum(exp(x)))\n% returns a smooth function to calculate\n% log( sum( exp(x) ) )\n%\n% SMOOTH_LOGSUMEXP( SIGMA ) is a scaled version\n% that calclates sigma*log(sum(exp(x/sigma)), for sigma > 0.\n% As sigma --> 0, this becomes a good approximation\n% of max(x).\n% The Lipschitz constant of the gradient is 1/sigma.\n% By default, sigma = 1.\n%\n% For a fancier version (with offsets),\n% see also smooth_logLLogistic.m\n\nif nargin < 1 || isempty(sigma), sigma = 1; end\nop = @(x)smooth_logsumexp_impl(x,sigma);\n\nfunction [ v, g ] = smooth_logsumexp_impl( x, sigma )\n\n% Even for moderate values of x/sigma, exp(x/sigma)\n% will overflow before we have a chance to take\n% its logarithm. So we subtract off the max value\n% and treat it separately:\n\nc = max(x);\nexpx = exp((x-c)/sigma);\nsum_expx = sum(expx(:));\nv = sigma*log(sum_expx) + c;\n\nif nargout > 1,\n g = expx ./ sum_expx;\n % (the factor of e^{-c} cancels from both the numerator\n % and denominator)\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/smooth_logsumexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7791814271075218}} {"text": "function [ x, seed ] = sech_sample ( a, b, seed )\n\n%*****************************************************************************80\n%\n%% SECH_SAMPLE samples the Hyperbolic Secant PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 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% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = a + b * log ( tan ( 0.5 * pi * cdf ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/sech_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529791457032, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7791600657763084}} {"text": "function quad = fejer2_integrate_fast ( f, n )\n\n%*****************************************************************************80\n%\n%% FEJER2_INTEGRATE_FAST approximates an integral using a Fejer type 2 rule.\n%\n% Discussion:\n%\n% The function is integrated over the interval [-1,1].\n%\n% The abscissas of the rule of order N are\n%\n% x(1:n) = cos ( ( 0:n-1 ) / n )\n%\n% The computation should be very efficient in MATLAB.\n%\n% Modified:\n%\n% 08 October 2006\n%\n% Author:\n%\n% Joerg Waldvogel\n%\n% Reference:\n%\n% Charles Clenshaw, Alan Curtis,\n% A Method for Numerical Integration on an Automatic Computer,\n% Numerische Mathematik,\n% Volume 2, Number 1, December 1960, pages 197-205.\n%\n% Lloyd Trefethen,\n% Is Gauss Quadrature Better than Clenshaw-Curtis?,\n% SIAM Review,\n% Volume 50, Number 1, 2008, pages 67-87.\n%\n% Joerg Waldvogel,\n% Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules\n% BIT Numerical Mathematics\n% Volume 43, Number 1, pages 1-18, 2003.\n%\n% Parameters:\n%\n% Input, function F, an expression, or the name of a function \n% to integrate.\n%\n% Input, integer N, the order of the rule to use.\n% N must be at least 1.\n%\n% Output, real QUAD, the approximate integral of the function F\n% over the interval [-1,1], using the quadrature rule.\n%\n if ( n == 1 )\n\n x = 0.0;\n w = 2.0;\n quad = w * feval ( f, x );\n\n else\n\n N = [ 1 : 2 : n-1 ]';\n L = length ( N );\n m = n - L;\n v0 = [ 2./N./(N-2); 1/N(end); zeros(m,1) ];\n v2 = -v0(1:end-1) - v0(end:-1:2);\n w = ifft ( v2 );\n \n x = cos ( pi * ( 0:n-1)' / n );\n fx = feval ( f, x ) ;\n\n quad = w' * 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/quadrule_fast/fejer2_integrate_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7791408713151349}} {"text": "function [Y,MX] = logfsgram(X, N, SR, WIN, NOV, FMIN, BPO)\n% [Y,MX] = logfsgram(X, N, SR, WIN, NOV, FMIN, BPO)\n% Calculate a log-frequency spectrogram\n% X is input signal; N is parent FFT window; SR is the source samplerate.\n% WIN is actual window length within FFT, NOV is number of overlapping \n% points between successive windows.\n% Optional FMIN is the lowest frequency to display (80Hz);\n% BPO is the number of bins per octave (12).\n% MX returns the nlogbin x nfftbin mapping matrix;\n% sqrt(MX'*(Y.^2)) is an approximation to the original FFT\n% spectrogram that Y is based on, suitably blurred by going \n% through the log-F domain.\n% 2004-03-30 dpwe@ee.columbia.edu $Header: /homes/dpwe/matlab/columbiafns/RCS/logfsgram.m,v 1.3 2004/04/01 22:39:02 dpwe Exp $\n\nif nargin < 2\n N = 1024;\nend\nif nargin < 3\n SR = 8000;\nend\nif nargin < 4\n WIN = [];\nend\nif nargin < 5\n NOV = [];\nend\nif nargin < 6\n FMIN = 80;\nend\nif nargin < 7\n BPO = 12;\nend\n\nif isempty(WIN)\n WIN = N;\nend\nif isempty(NOV)\n NOV = WIN/2;\nend\n\n% Calculate underlying STFT\nXX = specgram(X,N,SR,WIN,NOV);\n\n% Construct mapping matrix\n\n% Ratio between adjacent frequencies in log-f axis\nfratio = 2^(1/BPO);\n\n% How many bins in log-f axis\nnbins = floor( log((SR/2)/FMIN) / log(fratio) );\n\n% Freqs corresponding to each bin in FFT\nfftfrqs = [0:(N/2)]*(SR/N);\nnfftbins = N/2+1;\n\n% Freqs corresponding to each bin in log F output\nlogffrqs = FMIN * exp(log(2)*[0:(nbins-1)]/BPO);\n\n% Bandwidths of each bin in log F\nlogfbws = logffrqs * (fratio - 1);\n\n% .. but bandwidth cannot be less than FFT binwidth\nlogfbws = max(logfbws, SR/N);\n\n% Controls how much overlap there is between adjacent bands\novfctr = 0.5475; % Adjusted by hand to make sum(mx'*mx) close to 1.0\n\n% Weighting matrix mapping energy in FFT bins to logF bins\n% is a set of Gaussian profiles depending on the difference in \n% frequencies, scaled by the bandwidth of that bin\nfreqdiff = ( repmat(logffrqs',1,nfftbins) - repmat(fftfrqs,nbins,1) )./repmat(ovfctr*logfbws',1,nfftbins);\nmx = exp( -0.5*freqdiff.^2 );\n% Normalize rows by sqrt(E), so multiplying by mx' gets approx orig spec back\nmx = mx ./ repmat(sqrt(2*sum(mx.^2,2)), 1, nfftbins);\n\n% Perform mapping in magnitude-squared (energy) domain\ny = sqrt( mx * (abs(XX).^2) );\n\n% so, we lost phase information...\n\nif nargout < 1\n imagesc([0 length(X)/SR],[1 nbins],20*log10(y));\n axis xy\n xlabel('Time');\n ylabel('Frequency');\n yt = get(gca,'YTick');\n for i = 1:length(yt)\n ytl{i} = sprintf('%.0f',logffrqs(yt(i)));\n end\n set(gca,'YTickLabel',ytl);\nelse\n Y = y;\n MX = mx;\nend\n", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/tools/labrosa/logfsgram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7790493931732536}} {"text": "%% Gaussian Process Regression example from the gpml toolbox\nclear all;\n%% Generate some data\n\nnbSamples = 100;\nepsilon = 0.2;\nX = linspace(0,50,nbSamples);\ny = sin(X*0.2) + normrnd(0,0.2,1,nbSamples);\n\nX = X(:);\ny = y(:);\n\n% Make hole in Data\n\nid = (X > 20 & X < 30);\nX(id) = [];\ny(id) = [];\n\n% Plot data\noptions = [];\noptions.points_size = 10;\noptions.title = 'noisy sinusoidal data'; \n\nif exist('h1','var') && isvalid(h1), delete(h1);end\nh1 = ml_plot_data([X(:),y(:)],options);\n\n%% Train GP [gpml toolbox]\n\nmeanfunc = {@meanZero};\ncovfunc = {@covSEiso}; \n\nell = 10; % kernel width of RBF covariance function.\nsf = 1; % signal variance (not measurement noise)\nsn = 0.0001; % measurement noise\n\n\nhyp = [];\nhyp.cov = log([ell; sf]);\nhyp.lik = log(sn);\n\n\n% Test GP [gpml toolbox]\n\nX_test = linspace(0,50,200)';\n\n\n[m,s2] = gp(hyp, @infExact, meanfunc, covfunc, @likGauss, X, y, X_test);\n\nif exist('h2','var') && isvalid(h2), delete(h2);end\nh2 = figure;\n\nf = [m+2*sqrt(s2); flipdim(m-2*sqrt(s2),1)];\nfill([X_test; flipdim(X_test,1)], f, [7 7 7]/8);\nhold on;\n\noptions = [];\noptions.no_figure = true;\noptions.points_size = 10;\nml_plot_data([X(:),y(:)],options);\n\n\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/examples/regression/GPR_gpml_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7790493832825442}} {"text": "function Z = ECGModel(X,Phasemn)\n% Z = ECGModel(X,Phaemn)\n% Overview: Generate Synthetic ECG beat using parameters defined in X over phase\n% defined in the Phasemn variable.\n%\n% Inputs:\n% X - contains the amplitude (alphai), standard deviation (bi) and phase (tetai) for\n% each Gaussian function used for generating the synthetic ECG beat.\n% \n% Phasemn - array contains the phase points over which synthetic\n% ECG beat is generated.\n%\n% Outputs:\n% Z - synthetic ECG beat generated using Gaussian parameter estimates.\n%\n% Open Source ECG Toolbox, version 1.0, November 2006\n% Released under the GNU General Public License\n% Copyright (C) 2006 Reza Sameni\n% Sharif University of Technology, Tehran, Iran -- LIS-INPG, Grenoble, France\n% reza.sameni@gmail.com\n% Last modified:\n% on 11/30/2020 by Ismail Sadiq\n%\n% TODO: Return the analytic Jacobians to accelerate the convergence of the\n% nonlinear least squares solver. Added on Feb. 2019\n%\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details. 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 02110-1301, USA.\n\nL = (length(X)/3);\n\nalphai = X(1:L);\nbi = X(L+1:2*L);\ntetai = X(2*L+1:3*L);\n\nZ = zeros(size(Phasemn));\nfor j = 1:length(alphai),\n dtetai = rem(Phasemn - tetai(j) + pi,2*pi)-pi;\n Z = Z + alphai(j) .* exp(-dtetai .^2 ./ (2*bi(j) .^ 2));\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/ECGBeatFitterAlgo/ECGModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7788416317482574}} {"text": "function [D,B]=distance_wei(L)\n%DISTANCE_WEI Distance matrix\n%\n% D = distance_wei(L);\n% [D,B] = distance_wei(L);\n%\n% The distance matrix contains lengths of shortest paths between all\n% pairs of nodes. An entry (u,v) represents the length of shortest path \n% from node u to node v. The average shortest path length is the \n% characteristic path length of the network.\n%\n% Input: L, Directed/undirected connection-length matrix.\n% *** NB: The length matrix L isn't the weights matrix W (see below) ***\n%\n% Output: D, distance (shortest weighted path) matrix\n% B, number of edges in shortest weighted path matrix\n%\n% Notes:\n% The input matrix must be a connection-length matrix, typically\n% obtained via a mapping from weight to length. For instance, in a\n% weighted correlation network higher correlations are more naturally\n% interpreted as shorter distances and the input matrix should\n% consequently be some inverse of the connectivity matrix. \n% The number of edges in shortest weighted paths may in general \n% exceed the number of edges in shortest binary paths (i.e. shortest\n% paths computed on the binarized connectivity matrix), because shortest \n% weighted paths have the minimal weighted distance, but not necessarily \n% the minimal number of edges.\n% Lengths between disconnected nodes are set to Inf.\n% Lengths on the main diagonal are set to 0.\n%\n% Algorithm: Dijkstra's algorithm.\n%\n%\n% Mika Rubinov, UNSW/U Cambridge, 2007-2012.\n% Rick Betzel and Andrea Avena, IU, 2012\n\n%Modification history\n%2007: original (MR)\n%2009-08-04: min() function vectorized (MR)\n%2012: added number of edges in shortest path as additional output (RB/AA)\n%2013: variable names changed for consistency with other functions (MR)\n\nn=length(L);\nD=inf(n);\nD(1:n+1:end)=0; %distance matrix\nB=zeros(n); %number of edges matrix\n\nfor u=1:n\n S=true(1,n); %distance permanence (true is temporary)\n L1=L;\n V=u;\n while 1\n S(V)=0; %distance u->V is now permanent\n L1(:,V)=0; %no in-edges as already shortest\n for v=V\n T=find(L1(v,:)); %neighbours of shortest nodes\n [d,wi]=min([D(u,T);D(u,v)+L1(v,T)]);\n D(u,T)=d; %smallest of old/new path lengths\n ind=T(wi==2); %indices of lengthened paths\n B(u,ind)=B(u,v)+1; %increment no. of edges in lengthened paths\n end\n\n minD=min(D(u,S));\n if isempty(minD)||isinf(minD), %isempty: all nodes reached;\n break, %isinf: some nodes cannot be reached\n end;\n\n V=find(D(u,:)==minD);\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/bct/distance_wei.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7788416283471393}} {"text": "function mean = beta_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% BETA_MEAN returns the mean of the Beta PDF.\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 A, B, the parameters of the PDF.\n% 0.0D+00 < A,\n% 0.0D+00 < B.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a / ( a + b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/beta_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7788416280916465}} {"text": "function [w,A] = train_blr(X,y,var,Sigma_p)\n%TRAIN_BLR Train Bayesian Linear Regression\n%\n% Bayesian Linear Regression, we seek to learn a regression function \n% where the relation between the predictor variable, y and the domain X\n% is linear in the parameters whilst assuming a prior probability\n% distribtion over the parameters\n%\n% y = f(x) + \\epsilon, \\epsilon ~ N(0,var) (regression model) (1)\n% \n% y = x' * w with w ~ N(0,\\Sigma_p) (2)\n%\n% input ----------------------------------------------------------------\n%\n% o X: (N x D), N samples of dimension D\n%\n% o y: (D x 1), target value\n%\n% o Sigma_p: (D x D), Prior Covariance matrix on the weights\n%\n% output ----------------------------------------------------------------\n%\n% o w: (D x 1), weight vectors of equation (1)-(2)\n%\n%\n%\nN = size(X,1);\n\n% (D x 1)\n% (D x D) (D x N) * (N x 1) \n% ((D x N) * (N x D) + (D x D))\nX = [X,ones(N,1)]; % add bias\n\nA = (1/var) .* X'*X + inv(Sigma_p);\nw = (1/var) .* (A \\ (X' * y));\n\n\n\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/regression/gp/train_blr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7788310972077984}} {"text": "function F_L = CIECAM02_F_L(L_A)\n%\n%\n% F_L = CIECAM02_F_L(L_A)\n%\n% Input:\n% -L_A: is the luminance of the adapting field in cd/m^2.\n%\n% Output:\n% -F_L: is a predictor a variety of luminance-dependent\n% appearance effect.\n% \n% Copyright (C) 2015 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% The paper describing this technique is:\n% \"The CIECAM02 color appearance model\"\n% \t by Nathan Moroney , Mark D. Fairchild , Robert W. G. Hunt ,\n% Changjun Li , M. Ronnier Luo , Todd Newman\n% in IS&T/SID 10 th Color Imaging Conference\n%\n\nk = 1.0 ./ (5 * L_A + 1.0); %Equation 1\n\nF_L = 0.2 * k.^4 .* (5 * L_A) + ...\n 0.1 * (1.0 - k.^4).^2 .* ((5 * L_A).^(1.0 / 3.0)); %Equation 2\n \nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/util/CIECAM02_F_L.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7788002885383614}} {"text": "function [ x, seed ] = cardioid_sample ( a, b, seed )\n\n%*****************************************************************************80\n%\n%% CARDIOID_SAMPLE samples the Cardioid PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 <= B <= 0.5.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n% A - PI <= X <= A + PI.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = cardioid_cdf_inv ( cdf, a, b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/cardioid_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.7786871724557936}} {"text": "function A = spblockdiags(B,d,m,n)\n% BLOCKDIAGS : Create sparse block diagonal matrices.\n%\n% A = spblockdiags(B,d,m,n). \n%\n% Blockdiags, which generalizes the function \"spdiags\", \n% produces a sparse matrix with specified block diagonals.\n%\n% A is an m*k-by-n*k matrix, or an m-by-n matrix of k-by-k blocks. \n% The nonzero blocks of A are located on p block diagonals. \n% B is a min(m,n)*k-by-p*k matrix whose k-by-k block columns\n% are the block diagonals of A. \n% (Alternatively, B is k-by-p*k, and then A is block Toeplitz.)\n% d is a vector of p integers in the range -m+1 : n-1, \n% specifying which block diagonals in A are to be nonzero.\n% The values of p and k are determined from the dimensions of B and d.\n%\n% For k=1 this is exactly the same as A = spdiags(B,d,m,n); see spdiags \n% for examples of use. For k>1 this is conceptually the same as spdiags,\n% but k-by-k blocks replace matrix elements everywhere.\n%\n% For example, the following code sets A to the n^2-by-n^2 matrix of \n% the Laplacian on an n-by-n square grid; the matrix is block tridiagonal, \n% and the nonzero blocks themselves are tridiagonal or the identity.\n%\n% a = spblockdiags ([-1 4 -1], -1:1, n, n);\n% I = speye (n, n);\n% A = spblockdiags ([-I a -I], -1:1, n, n);\n%\n% John Gilbert, Xerox PARC, 17 April 1991.\n% Viral Shah, UCSB, 12 April 2006.\n% Copyright (c) 1990-1996 by Xerox Corporation. All rights reserved.\n% HELP COPYRIGHT for complete copyright and licensing notice.\n\nif nargin ~= 4\n error ('Usage: A = blockdiags(B,d,m,n)');\nend\n\nk = length(d);\n[nrB,ncB] = size(B);\np = ncB/k;\n\n% Check for reasonable input.\n\nif any(size(m)>1) | any(size(n)>1)\n error ('blockdiags(B,d,m,n): m or n not scalar');\nend\nif min(size(d)~=1) \n error ('blockdiags(B,d,m,n): d not a vector');\nend\nif any(rem(size(B),p))\n error ('blockdiags(B,d,m,n): block size does not divide size of B');\nend\n\nA = sparse (m*p, n*p);\n\nfor i=1:k\n S = spdiags (ones(m,1), d(i), m, n);\n block = B(:, [(i-1)*p+1:i*p]);\n if isscalar(block)\n A = A + block .* S;\n else\n A = A + kron (S, block);\n end\nend\n\nreturn;", "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/spblockdiags.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.7786789381312099}} {"text": "function [Hes,R] = VAorthog(Z,n,varargin) % Vand.+Arnoldi orthogonalization\n%VAORTHOG Vandermonde with Arnoldi orthogonalization.\n%\n% This code comes from Brubeck and Trefethen, \"Lightning Stokes solver\", arXiv 2020.\n% For the mathematics, see Brubeck, Nakatsukasa, and Trefethen, \"Vandermonde with\n% Arnoldi\", SIAM Review, 2021.\n%\n% Input: Z = column vector of sample points\n% n = degree of polynomial (>= 0)\n% Pol = cell array of vectors of poles (optional)\n% Output: Hes = cell array of Hessenberg matrices (length 1+length(Pol))\n% R = matrix of basis vectors\nM = length(Z); Pol = []; if nargin == 3, Pol = varargin{1}; end\n% First orthogonalize the polynomial part\nQ = ones(M,1); H = zeros(n+1,n);\nfor k = 1:n \n q = Z.*Q(:,k);\n for j = 1:k, H(j,k) = Q(:,j)'*q/M; q = q - H(j,k)*Q(:,j); end \n H(k+1,k) = norm(q)/sqrt(M); Q(:,k+1) = q/H(k+1,k);\nend\nHes{1} = H; R = Q;\n% Next orthogonalize the pole parts, if any\nwhile ~isempty(Pol)\n pol = Pol{1}; Pol(1) = [];\n np = length(pol); H = zeros(np,np-1); Q = ones(M,1);\n for k = 1:np \n q = Q(:,k)./(Z-pol(k));\n for j = 1:k, H(j,k) = Q(:,j)'*q/M; q = q - H(j,k)*Q(:,j); end \n H(k+1,k) = norm(q)/sqrt(M); Q(:,k+1) = q/H(k+1,k);\n end\n Hes{length(Hes)+1} = H; R = [R Q(:,2: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/VAorthog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7786275856545523}} {"text": "function y = beta_lpdf(x,a,b)\n%BETA_LPDF Beta log-probability density function (lpdf).\n%\n% Y = BETA_LPDF(X,A,B) Returns the log of the Beta pdf with\n% parameters A and B, at the values in X.\n%\n% The size of Y is the common size of the input arguments. A scalar input \n% functions as a constant matrix of the same size as the other inputs. \n%\n% Default value for A and B is 1.\n\n% Copyright (c) 2005 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n a = 1;\nend\n\nif nargin < 2;\n b = 1;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny= (a-1).*log(x) +(b-1).*log(1-x) -betaln(a,b);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/dist/beta_lpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.778517847277953}} {"text": "%CAMPOSE4\tCamera pose estimation from 4 coplanar points.\n%\n%\tT = CAMPOSE4(D, ci)\n%\t[T, UV0] = CAMPOSE4(D, ci)\n%\n% Input is a table of data points, D, with each row of the form [X Y u v]\n% where (X, Y) are the world coordinate of the planar points with respect\n% to some coordinate system whose origin lies within the plane, \n% and (u, v) are the corresponding image plane coordinate.\n%\n% ci is a structure of camera intrinsic parameters that must contain\n% focal length (f), and pixel sizes (sx, sy).\n%\n% Output is a homogeneous transformation, T, of the camera's pose with \n% respect to the coordinate frame of the planar points. \n% The optional result, UV0, is the coordinate of the principal point (in \n% distance units).\n%\n% from Ganapathy \"Camera Location Determination Problem\",\n% Bell Labs Tech. Memo 11358-841102-20-TM, Nov 2 1984\n%\n% SEE ALSO: CAMPOSE4, CAMCALP, CAMERA, CAMCALT, INVCAMCAL\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nfunction [T, uv0] = campose4(uvXY, ci)\n\n\tt = camcald4(uvXY);\n k(1) = ci.f / ci.sx;\n k(2) = ci.f / ci.sy;\n% K = [k1 k2] contains the X and Y-direction scale\n% factors: k1 = kx * F, k2 = ky * F, where F is the focal length.\n%\n\n\tlam1 = t(1,1)*t(3,2) - t(1,2)*t(3,1);\n\tlam2 = t(2,1)*t(3,2) - t(2,2)*t(3,1);\n\tif abs(lam1) < 1e-8,\n\t\tlam1 = 0;\n\tend\n\tif abs(lam2) < 1e-8,\n\t\tlam2 = 0;\n\tend\n\n\tif (lam1 == 0) & (lam2 == 0),\n\t\tr2 = (k(1)^2 + k(2)^2) / sqrt(t(1,1)^2 + t(1,2)^2 + t(2,1)^2 + t(2,2)^2);\n\t\tr = sqrt(r2);\n\t\tdisp('Problem with solution: lam1 = lam2 = 0');\n\t\ti = 1;\n\t\tf = 0;\n\t\tc = 0;\n\t\tg = 0;\n\t\th = 0;\n\t\t\n\t\tu0 = ci.u0;\n\t\tv0 = ci.v0;\n\telse\n\t\tr2 = (t(3,1)^2 + t(3,2)^2)/( (lam1/k(1))^2 + (lam2/k(2))^2 );\n\t\tr = sqrt(r2);\n \n\t\ti2 = 1 - r2*(t(3,1)^2 + t(3,2)^2);\n\t\ti = sqrt(i2);\n\t\tf = -lam1/k(1)*r2;\n\t\tc = lam2/k(2)*r2;\n\n\t\tu0 = (t(1,1)*t(3,1) + t(1,2)*t(3,2) + k(1)*c*i/r2) / (t(3,1)^2 + t(3,2)^2);\n\t\tv0 = (t(2,1)*t(3,1) + t(2,2)*t(3,2) + k(2)*f*i/r2) / (t(3,1)^2 + t(3,2)^2);\n\n\t\tg = t(3,1)*r;\n\t\th = t(3,2)*r;\n\tend\n\n\ta = (t(1,1)*r - u0*g) / k(1);\n\tb = (t(1,2)*r - u0*h) / k(1);\n\td = (t(2,1)*r - v0*g) / k(2);\n\te = (t(2,2)*r - v0*h) / k(2);\n\tp = (t(1,3)*r - u0*r) / k(1);\n\tq = (t(2,3)*r - v0*r) / k(2);\n\n\tR = [a b c;d e f;g h i];\n\tP = [p q r];\n\n\tT = [R P'; 0 0 0 1];\n\tuv0 = [u0 v0];\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/campose4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7785178377020064}} {"text": "%% This function applies Canny Operator to an input\n%% image and can be used for edge detection.\n\n\n%%% input arguments\n%% image = String representing input file.\n%% si = Size of Gaussian Kernel used for antialiasing the input image and calculating\n%% gaussian derivatives.\n%% sigma = Standard deviation of Gaussian function.\n%% thresh = upper threshold used for thresholding in Canny method.\n\n%%% output Arguments\n%% gnh = output Image.\n\n%%% References :- DIGITAL IMAGE PROCESSING Third Edition,\n%% Rafael C. Gonzalez\n%% Richard E. Woods\n\n\n\n\nfunction gnh= canny(image,si,sigma,thresh)\n%% input argument check.\n\nerror(nargchk(4,4,nargin));\nif(thresh>1)\n error('Thresh value should be between 0 and 1');\nend\nI=imread(image);\nif(size(I,3)==3)\nI=rgb2gray(I);\nend\nfigure,imagesc(I),impixelinfo,title('Original Image'),colormap('gray');\nlthresh=0.4*thresh;\nuthresh=thresh;\nif(uthresh>1.0)\n uthresh=1;\nend\n%% Antialias the image by convolving with gaussian filter\n\nh=fspecial('gaussian',si,sigma);\nI=im2double(I);\nI=imfilter(I,h,'conv');\nfigure,imagesc(I),impixelinfo,title('Original Image after Convolving with gaussian'),colormap('gray');\n%% Compute Gaussian derivatives\n\n x=-si:1:si;\n y=-si:1:si;\ngaussx=-(x/(sigma*sigma)).*exp(-(x.*x+y.*y)/(2*sigma*sigma));\ngaussy=gaussx';\nIx=imfilter(I,gaussx,'conv');\nIy=imfilter(I,gaussy,'conv');\n%% Compute magnitude and orientation of gradient vector.\n\nMag=sqrt(Ix .^ 2 + Iy .^ 2);\nMagmax=max(Mag(:));\nMag=Mag/Magmax;\nfigure,imagesc(Mag),impixelinfo,title('Magnitude of gradient Vectors'),colormap('gray');\ngnl=zeros(size(I,1),size(I,2));\ngnh=zeros(size(I,1),size(I,2));\nangle=atand(Iy./Ix);\nfigure,quiver(20*Ix,20*Iy,0),title('Orientation of gradient vectors'),colormap('gray');\n%% Apply non maxima suppression and thresholding. The orientation of gradient vecctor is\n%% resolved into four directions.\n\nfor y=2:1:size(I,1)-1\n for x=2:1:size(I,2)-1\n if(((angle(y,x)>=-22.5)&&(angle(y,x)<22.5))||((angle(y,x)<-157.5))||(angle(y,x)>157.5))\n if((Mag(y,x)>Mag(y,x+1)) && (Mag(y,x)>Mag(y,x-1)))\n if(Mag(y,x)>=lthresh)\n if(Mag(y,x)>=uthresh)\n gnh(y,x)=1;\n else\n gnl(y,x)=1;\n end\n end\n end\n end\n if(((angle(y,x)>=-112.5)&&(angle(y,x)<-67.5))||((angle(y,x)>=67.5)&&(angle(y,x)<112.5)))\n if((Mag(y,x)>Mag(y+1,x)) && (Mag(y,x)>Mag(y-1,x)))\n if(Mag(y,x)>=lthresh)\n if(Mag(y,x)>=uthresh)\n gnh(y,x)=1;\n else\n gnl(y,x)=1;\n end\n end\n end\n end\n if(((angle(y,x)>=-67.5)&&(angle(y,x)<-22.5))||((angle(y,x)>=112.5)&&(angle(y,x)<157.5)))\n if((Mag(y,x)>Mag(y-1,x+1)) && (Mag(y,x)>Mag(y+1,x-1)))\n if(Mag(y,x)>=lthresh)\n if(Mag(y,x)>=uthresh)\n gnh(y,x)=1;\n else\n gnl(y,x)=1;\n end\n end\n end\n end\n if(((angle(y,x)>=-157.5)&&(angle(y,x)<-112.5))||((angle(y,x)>=22.5)&&(angle(y,x)<67.5)))\n if((Mag(y,x)>Mag(y+1,x+1)) && (Mag(y,x)>Mag(y-1,x-1)))\n if(Mag(y,x)>=lthresh)\n if(Mag(y,x)>=uthresh)\n gnh(y,x)=1;\n else\n gnl(y,x)=1;\n end\n end\n end\n end\n end\nend\nfigure,imagesc(gnh),impixelinfo,title('Image after thresholding'),colormap('gray');\n%% Apply Connectivity Analysis.\n\n[row,col]=find(gnh>0);\n for t=1:1:size(col)\n if(gnl(row(t)+1,col(t))>0)\n gnh(row(t)+1,col(t))=1;\n gnl(row(t)+1,col(t))=0;\n end\n if(gnl(row(t),col(t)+1)>0)\n gnh(row(t),col(t)+1)=1;\n gnl(row(t),col(t)+1)=0;\n end\n if(gnl(row(t)+1,col(t)+1)>0)\n gnh(row(t)+1,col(t)+1)=1;\n gnl(row(t)+1,col(t)+1)=0;\n end\n if(gnl(row(t)-1,col(t)-1)>0)\n gnh(row(t)-1,col(t)-1)=1;\n gnl(row(t)-1,col(t)-1)=0;\n end\n if(gnl(row(t)+1,col(t)-1)>0)\n gnh(row(t)+1,col(t)-1)=1;\n gnl(row(t)+1,col(t)-1)=0;\n end\n if(gnl(row(t)-1,col(t)+1)>0)\n gnh(row(t)-1,col(t)+1)=1;\n gnl(row(t)-1,col(t)+1)=0;\n end\n if(gnl(row(t)-1,col(t))>0)\n gnh(row(t)-1,col(t))=1;\n gnl(row(t)-1,col(t))=0;\n end\n if(gnl(row(t),col(t)-1)>0)\n gnh(row(t),col(t)-1)=1;\n gnl(row(t),col(t)-1)=0;\n end\n end\n %% Display output Image.\n \nfigure,imagesc(gnh),impixelinfo,title('Image after Applying Connectivity Analysis'),colormap('gray');\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/30621-canny-edge-detection/canny.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7785178280366556}} {"text": "function [r,t,p]=spear(x,y)\n%Syntax: [r,t,p]=spear(x,y)\n%__________________________\n%\n% Spearman's rank correalation coefficient.\n%\n% r is the Spearman's rank correlation coefficient.\n% t is the t-ratio of r.\n% p is the corresponding p-value.\n% x is the first data series (column).\n% y is the second data series, a matrix which may contain one or multiple\n% columns.\n%\n%\n% Reference:\n% Press W. H., Teukolsky S. A., Vetterling W. T., Flannery B. P.(1996):\n% Numerical Recipes in C, Cambridge University Press. Page 641.\n%\n%\n% Example:\n% x = [1 2 3 3 3]';\n% y = [1 2 2 4 3; rand(1,5)]';\n% [r,t,p] = spear(x,y)\n%\n%\n% Products Required:\n% Statistics Toolbox\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% 3 Feb 2002.\n\n\n% x and y must have equal number of rows\nif size(x,1)~=size(y,1)\n error('x and y must have equal number of rows.');\nend\n\n\n% Find the data length\nN = length(x);\n\n% Get the ranks of x\nR = crank(x)';\n\nfor i=1:size(y,2)\n \n % Get the ranks of y\n S = crank(y(:,i))';\n \n % Calculate the correlation coefficient\n r(i) = 1-6*sum((R-S).^2)/N/(N^2-1);\n \nend\n\n% Calculate the t statistic\nif r == 1 | r == -1\n t = r*inf;\nelse\n t=r.*sqrt((N-2)./(1-r.^2));\nend\n\n% Calculate the p-values\np=2*(1-tcdf(abs(t),N-2));\n\n\n\n\n\nfunction r=crank(x)\n%Syntax: r=crank(x)\n%__________________\n%\n% Assigns ranks on a data series x. \n%\n% r is the vector of the ranks\n% x is the data series. It must be sorted.\n%\n%\n% Reference:\n% Press W. H., Teukolsky S. A., Vetterling W. T., Flannery B. P.(1996):\n% Numerical Recipes in C, Cambridge University Press. Page 642.\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% 3 Feb 2002.\n\n\nu = unique(x);\n[xs,z1] = sort(x);\n[z1,z2] = sort(z1);\nr = (1:length(x))';\nr=r(z2);\n\nfor i=1:length(u)\n \n s=find(u(i)==x);\n \n r(s,1) = mean(r(s));\n \nend\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4374-spearman-rank-correlation/spear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8872046041554923, "lm_q1q2_score": 0.7785014345227409}} {"text": "function [d rt]=corenums(A)\n% CORENUMS Compute the core number for each vertex in the graph.\n%\n% [cn rt]=corenums(A) returns the core numbers for each vertex of the graph\n% A along with the removal order of the vertex. The core number is the \n% largest integer c such that vertex v exists in a graph where all \n% vertices have degree >= c. The vector rt returns the removal time \n% for each vertex. That is, vertex vi was removed at step rt[vi].\n%\n% This method works on directed graphs but gives the in-degree core number.\n% To get the out-degree core numbers, call corenums(A').\n%\n% The linear algorithm comes from:\n% Vladimir Batagelj and Matjaz Zaversnik, \"An O(m) Algorithm for Cores \n% Decomposition of Networks.\" Sept. 1 2002.\n%\n% Example:\n% load_gaimc_graph('cores_example'); % the graph A has three components\n% corenums(A)\n%\n\n% See also WCORENUMS\n\n% David F. Gleich\n% Copyright, Stanford University, 2008-2009\n\n% History\n% 2008-04-21: Initial Coding\n\nif isstruct(A), rp=A.rp; ci=A.ci; %ofs=A.offset;\nelse [rp ci]=sparse_to_csr(A); \nend\nn=length(rp)-1;\nnz=length(ci);\n\n% the algorithm removes vertices by computing bucket sort on the degrees of\n% all vertices and removing the smallest.\n\n% compute in-degrees and maximum indegree\nd=zeros(n,1); maxd=0; rt=zeros(n,1);\nfor k=1:nz, newd=d(ci(k))+1; d(ci(k))=newd; if newd>maxd; maxd=newd; end, end\n\n% compute the bucket sort\ndp=zeros(maxd+2,1); vs=zeros(n,1); vi=zeros(n,1); % degree position, vertices\nfor i=1:n, dp(d(i)+2)=dp(d(i)+2)+1; end % plus 2 because degrees start at 0\ndp=cumsum(dp); dp=dp+1;\nfor i=1:n, vs(dp(d(i)+1))=i; vi(i)=dp(d(i)+1); dp(d(i)+1)=dp(d(i)+1)+1; end\nfor i=maxd:-1:1, dp(i+1)=dp(i); end\n\n% start the algorithm\nt=1;\nfor i=1:n\n v = vs(i); dv = d(v); rt(v)=t; t=t+1;\n for rpi=rp(v):rp(v+1)-1\n w=ci(rpi); dw=d(w);\n if dw<=dv, % we already removed w\n else % need to remove edge (v,w), which decreases d(w)\n % swap w with the vertex at the head of its degree\n pw=vi(w); % get the position of w\n px=dp(dw+1); % get the pos of the vertex at the head of dw list\n x=vs(px);\n % swap w, x\n vs(pw)=x; vs(px)=w; vi(w)=px; vi(x)=pw;\n % decrement the degree of w and increment the start of dw\n d(w)=dw-1;\n dp(dw+1)=px+1;\n end\n end\nend\n\n\n \n", "meta": {"author": "luanfujun", "repo": "deep-photo-styletransfer", "sha": "4801fa2dca2e2b52847c377f451246a39eae154a", "save_path": "github-repos/MATLAB/luanfujun-deep-photo-styletransfer", "path": "github-repos/MATLAB/luanfujun-deep-photo-styletransfer/deep-photo-styletransfer-4801fa2dca2e2b52847c377f451246a39eae154a/gen_laplacian/gaimc/corenums.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.7785014310486593}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\nJ = ((1 / (2 * m)) * sum(power((X * theta - y), 2))) + ((lambda / (2 * m)) * sum(power(theta(2 : end), 2)));\nG = (lambda / m) .* theta;\nG(1) = 0;\ngrad = ((1/m) .* X' * (X*theta - y)) + G;\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "UtkarshPathrabe", "repo": "Machine-Learning-Stanford-University-Coursera", "sha": "0e5855855b5ddd475775b75bad69b47c2ebe84ef", "save_path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera", "path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera/Machine-Learning-Stanford-University-Coursera-0e5855855b5ddd475775b75bad69b47c2ebe84ef/Programming Exercises/machine-learning-ex5/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.778437880598975}} {"text": "function output = F1measure(P,R)\n% Calculates the F1 measure with alpah = .5\n% \n% © Siamak Faridani, UC Berkeley, 2/2/2012\n% \n% v 1.0 \n% \n% F = 1/(alpha(1/P)+(1-alpha)(1/R))\n% F1 is when alpha is 0.5\n%\n% (see page 268 of Manning and Schutze)\n%\n% Inputs \n% P: precision\n% R: Recall\n% Outputs\n% F1-measure\n\noutput = 2*(P*R)/(P+R);\n\n\nend", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/nlp lib/funcs/F1measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.77843786875629}} {"text": "function [ mD ] = CalcDistanceMatrixARows( mX )\n% ----------------------------------------------------------------------------------------------- %\n% [ mD ] = CalcDistanceMatrixARows( mX )\n% Calculates the distance matrix for the input data. The distance matrix\n% is a symmetric matrix where 'mD(ii, jj) = dist(mX(ii, :), mX(jj, :));'.\n% This function uses the squared Euclidean Distance for the distance\n% metric.\n% Input:\n% - mX - Data Matrix.\n% Each data sample is a row of the matrix.\n% Structure: Matrix (numVars x varDim).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - mD - Distance Matrix.\n% A symmetric matrix where 'mD(ii, jj) = dist(mX(ii,\n% :), mX(jj, :));'.\n% Structure: Matrix (numVars x numVars).\n% Type: 'Single' / 'Double'.\n% Range: [0, inf).\n% References\n% 1. A\n% Remarks:\n% 1. B\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 01/01/2021 Royi Avital\tRoyiAvital@yahoo.com\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nvSsqX = sum(mX .^ 2, 2);\nmD = vSsqX.'+ vSsqX - (2 * (mX * mX.'));\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/CodeReview/Q254186/CalcDistanceMatrixARows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7783941185262981}} {"text": "function [xInt,t]=findEllipsLineIntersect(xc,A,x0,a,aType)\n%%FINDELLIPSLINEINTERSECT Given the parameters for an ellipsoid (in 2D an\n% ellipse) of the form (x-xc)'*A*(x-xc)=1 and a line either given\n% parameterically as x=x0+a*t or whether x0 and a are two points on\n% the line, find the points of intersection between the ellipsoid and\n% the line.\n%\n%INPUTS: xc The xDimX1 center of the ellipsoid.\n% A The xDimXxDim symmetric matrix defining the above equation for\n% an ellipsoid.\n% x0, a These xDimX1 values define a line and the type of line is given\n% by aType. If aType=0, then the line is parameteric as x=x0+a*t\n% where t is a scalar value. If aType=1, then x0 and a are both\n% points on the line. \n% aType As mentioned above, this specifies how the line is\n% parameterized. The default if omitted or an empty matrix is\n% passed is 0.\n%\n%OUTPUTS: xInt Either xDimX2 (or rarely xDimX1) matrix holding the vector\n% points of intersection of the line and the ellipsoid or an\n% empty matrix if there are no real solutions (the line does\n% not intersect the ellipsoid).\n% t If solutions exist, this is the 2X1 (or rarely 1X1) set of\n% parametric parameters. If aType=0, then these are the t\n% values in the parameteric equation. If aType=1, then these\n% are the t values in the parameteric equation x=x0+(a-x0)*t,\n% in which case values between 0 and 1 indicate that the\n% intersection occured between the two specified points.\n%\n%Start with the equations x=x0+a*t and (x-xc)'*A*(x-xc)=1. Substitite the\n%first into the second and one ends up with a quadratic equation\n%c1*t^2+c2*t+c3=0 with c1=a'*A*a, c2=2*xTilde'*A*a, c3=xTilde'*A*xTile-1\n%where xTilde=x0-xc.\n%\n%EXAMPLE:\n%Find and plot the intersection points of a line an an ellipse. Also\n%consider a line that does not intersect and one sees that nothing is\n%plotted from that, because no solution exists.\n% %The ellipse.\n% xc=[1;2];\n% A=[1,0.5;\n% 0.5,2];\n% %Two points defining a line that does intersect.\n% x01=[0;3];\n% x02=[2;1];\n% %Two points defining a line that does not intersect.\n% x11=[3;3];\n% x12=[3;1];\n% \n% aType=1;\n% xInt0=findEllipsLineIntersect(xc,A,x01,x02,aType);\n% xInt1=findEllipsLineIntersect(xc,A,x11,x12,aType);%This is empty.\n% \n% figure(1)\n% clf\n% hold on\n% drawEllipse(xc,A,1,'linewidth',2)\n% plot([x01(1);x02(1)],[x01(2);x02(2)],'-k','linewidth',2)\n% plot([x11(1);x12(1)],[x11(2);x12(2)],'-k','linewidth',2)\n% \n% numSol0=size(xInt0,2);\n% numSol1=size(xInt1,2);%Should be 0.\n% for k=1:numSol0\n% scatter(xInt0(1,k),xInt0(2,k),400,'.r')\n% end\n% for k=1:numSol1\n% scatter(xInt1(1,k),xInt1(2,k),400,'.g')\n% end\n%\n%July 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(aType))\n aType=0;\nend\n\nif(aType==1)\n %Make it parameteric.\n a=a-x0; \nend\n\nxTilde=x0-xc;\n\nc1=a'*A*a;\nc2=2*xTilde'*A*a;\nc3=xTilde'*A*xTilde-1;\n\nt=roots([c1;c2;c3]);\n\nif(isempty(t)||any(~isreal(t)))\n t=[];\n xInt=[];\n return \nend\n\nxDim=size(x0,1);\nnumSol=length(t);\n\nxInt=zeros(xDim,numSol,1);\nfor curSol=1:numSol\n xInt(:,curSol)=x0+a*t(curSol);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/findEllipsLineIntersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.8670357666736773, "lm_q1q2_score": 0.7783339329508728}} {"text": "function value = r8_si ( x )\n\n%*****************************************************************************80\n%\n%% R8_SI evaluates the sine integral Si of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the sine integral Si evaluated at X.\n%\n persistent nsi\n persistent sics\n persistent xsml\n\n if ( isempty ( nsi ) )\n\n sics = [ ...\n -0.1315646598184841928904275173000457, ...\n -0.2776578526973601892048287660157299, ...\n 0.0354414054866659179749135464710086, ...\n -0.0025631631447933977658752788361530, ...\n 0.0001162365390497009281264921482985, ...\n -0.0000035904327241606042670004347148, ...\n 0.0000000802342123705710162308652976, ...\n -0.0000000013562997692540250649931846, ...\n 0.0000000000179440721599736775567759, ...\n -0.0000000000001908387343087145490737, ...\n 0.0000000000000016669989586824330853, ...\n -0.0000000000000000121730988368503042, ...\n 0.0000000000000000000754181866993865, ...\n -0.0000000000000000000004014178842446, ...\n 0.0000000000000000000000018553690716, ...\n -0.0000000000000000000000000075166966, ...\n 0.0000000000000000000000000000269113, ...\n -0.0000000000000000000000000000000858 ]';\n\n nsi = r8_inits ( sics, 18, 0.1 * r8_mach ( 3 ) );\n xsml = sqrt ( r8_mach ( 3 ) );\n\n end\n\n absx = abs ( x );\n\n if ( absx < xsml )\n value = x;\n elseif ( absx <= 4.0 )\n value = x * ( 0.75 + r8_csevl ( ( x * x - 8.0 ) * 0.125, sics, nsi ) );\n else\n [ f, g ] = r8_sifg ( absx );\n cosx = cos ( absx );\n value = 0.5 * pi - f * cosx - g * sin ( x );\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/r8_si.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7783339194235982}} {"text": "function ch=rayleigh(n_samp,fd,fs)\n\n% ch=rayleigh(n_samp,fd,fs)\n%\n% Create n_samp samples of a Rayleigh channel whose doppler spread is fd\n% and which is sampled at frequency fs.\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas \n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nerror(nargchk(3,3,nargin));\nerror(chk_param(n_samp,'n_samp','scalar','real','integer','>=',1));\nerror(chk_param(fd,'fd','scalar','real','>=',0));\nerror(chk_param(fs,'fs','scalar','real','>',0));\nif (fd>fs/2)\n error('Doppler spread must be smaller than fs/2');\nend\n\n% Special case when requested doppler spread is zero.\nif (fd==0)\n ch=rayleigh(1,0.5,2);\n ch=repmat(ch,1,n_samp);\n return;\nend\n\n% First, a rayleigh channel is created with a doppler frequency of 0.5\n% and a sampling frequency of 2. Then, this channel is interpolated\n% up to the desired sampling frequency.\n\n% Calculate the interpolation factor.\nintp=fs/fd/4;\n\n% Rayleigh transfer function\nrtf=@(f)(abs(f)<.5).*sqrt(1./((pi*0.5)*sqrt(1-(f/(0.5+eps(0.5))).^2)));\n\n% Create the source Rayleigh signal\nn_samp_source=max(2048,ceil(n_samp/intp));\nbb=sqrt(2)*cyc_filt(blnoise(n_samp_source),rtf);\n\n% Now, interpolate up to the desired sampling rate.\nch=interpft(bb,round(n_samp_source*intp));\nch=ch(1:n_samp);\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/rayleigh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7782634874010078}} {"text": "%% RATE OF CONVERGENCE OF WEAK GALERKIN FINITE ELEMENT METHOD\n%\n% This example is to show the rate of convergence of linear finite element\n% approximation of the Poisson equation on the unit square with the\n% following boundary conditions:\n%\n% - Non-empty Dirichlet boundary condition.\n% - Pure Neumann boundary condition.\n% - Robin boundary condition.\n%\n% The basis, data structure and numerical test is summarized in Poissonfemrate.\n%\n% See also PoissonP2femrate, Poissonafemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear variables\n%% Setting\n[node,elem] = squaremesh([0,1,0,1],0.25); \nmesh = struct('node',node,'elem',elem);\noption.L0 = 2;\noption.maxIt = 4;\noption.printlevel = 1;\noption.elemType = 'WG';\n\n%% Non-empty Dirichlet boundary condition.\noption.plotflag = 1;\npde = sincosdata;\nmesh.bdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nfemPoisson(mesh,pde,option);\n\n%% Pure Neumann boundary condition.\noption.plotflag = 0;\npde = sincosNeumanndata;\n% pde = sincosdata;\nmesh.bdFlag = setboundary(node,elem,'Neumann');\nfemPoisson(mesh,pde,option);\n\n%% Pure Robin boundary condition.\noption.plotflag = 0;\npde = sincosRobindata;\nmesh.bdFlag = setboundary(node,elem,'Robin');\nfemPoisson(mesh,pde,option);\n\n%% Conclusion\n%\n% The optimal rate of convergence of the H1-norm (1st order) and L2-norm\n% (2nd order) is observed. No superconvergence for ||DuI-Duh||.\n%\n% MGCG converges uniformly in all cases.", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Poisson/PoissonWGfemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7782224795245114}} {"text": "function [ x, w ] = legendre_set_sqrtx_01 ( n )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_SET_SQRTX_01 sets a Gauss-Legendre rule for SQRT(X) * F(X) on [0,1].\n%\n% Discussion:\n%\n% The integral:\n%\n% Integral ( 0 <= X <= 1 ) SQRT ( X ) * F(X) dX =\n% Integral ( 0 <= Y <= 1 ) 2 * Y**2 * F(Y**2) dY.\n% (using Y = SQRT(X) )\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% 02 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% CRC Press, 30th Edition, 2000, page 696.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n n2 = 2 * n + 1;\n\n [ x2, w2 ] = legendre_set ( n2 );\n\n x = zeros ( n, 1 );\n w = zeros ( n, 1 );\n\n x(1:n,1) = x2(n+2:2*n+1,1).^2;\n\n w(1:n,1) = 2.0 * w2(n+2:2*n+1,1) .* x(1:n,1);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/legendre_set_sqrtx_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7782224734330873}} {"text": "function [ vX, paramLambda ] = SolveLsNormSquaredConst( mA, vB, normSquaredConst, numIterations )\n% ----------------------------------------------------------------------------------------------- %\n%[ vX ] = SolveLsNormConst( mA, vB, normConst )\n% Solves norm constrained Least Squares problem by finding the optimal Dual\n% Variable (paramLambda) of the KKT Conditions by succesively solving\n% Tikhonov Regularized Least Squares problems.\n% The objective Funciton is given by:\n% \\arg \\min_{x} \\frac{1}{2} {\\left\\| A x - b \\right\\|}_{2}^{2}\n% subject to {\\left\\| x \\right\\|}_{2}^{2} \\leq normSquaredConst\n% Input:\n% - mA - Input Matrix.\n% The given matrix of the problem 0.5 || A x - b|| ^ 2.\n% Structure: Vector (Column Vector).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vB - Input Vector.\n% The given vector of the problem 0.5 || A x - b|| ^ 2.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, ...}.\n% - normConst - Norm Constraint.\n% The solution must obey || x || <= normConst.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% Output:\n% - vX - Solution Vector.\n% The optimal solution of the problem 0.5 || A x\n% - b || ^ 2 subject to || x || <= normConst.\n% Structure: Vector (Column Vector).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. See - https://stats.stackexchange.com/questions/401212.\n% Remarks:\n% 1. T\n% TODO:\n% 1. U\n% Release Notes:\n% - 1.0.000 14/04/2019\n% * First realease version.\n% ----------------------------------------------------------------------------------------------- %\n\nparamLambda = 0; %n; A0=U0*S0*V0', where U0 is m*r, V0 is n*r;\n% This is equivalent to compute block lanczos on C=[0,A;A',0];\n% The initial lanczos block should set to be uv0=[U0;V0]/sqrt(2);\n% where r is the rank of A0 and c is the slack positive interger variable;\n%\n% A - m * n matrix (required input)\n% [u0; v0]/sqrt(2) - Initial subspace (required input)\n% k - the number of blocks\n%\n% U S V - partial singular value decomposition\n%\n% Reference: Zhouchen Lin and Siming Wei, A Block Lanczos with Warm Start \n% Technique for Accelerating Nuclear Norm Minimization Algorithms, \n% arxiv: 1012.0365.\n%\n% Bug report: zclin2000@hotmail.com\n%\n\nif nargin < 3\n error('Too few arguments') ;\nend\n\nif nargin < 4\n k = 1;\nelseif k == -1\n k = 1;\nend\n\n\n[m,n]=size(A);\nmark=0;\nif m=n;\n mark=1;\n A=A';\n t=m;\n m=n;\n n=t;\n uv0=[v0; u0]/sqrt(2);\nelse\n uv0=[u0; v0]/sqrt(2);\nend\nr=size(uv0,2);\n% Initialization;\n\n% tridiagolization; \nX(:,:,1)=uv0;\n% AX=multiC(A,uv0,m,n);\nAX = [A*uv0(m+1:m+n,:);A'*uv0(1:m,:)];\nM(:,:,1)=uv0'*AX;\nQ=X(:,:,1);\nBdiag=[];\nMdiag=M(:,:,1);\nl=1;\nstop=0;\ntol=1.e-3;\n\nwhile stop~=1\n if l==1\n R(:,:,l)=AX-uv0*M(:,:,1);\n else\n R(:,:,l)=AX-X(:,:,l)*M(:,:,l)-X(:,:,l-1)*B(:,:,l-1)';\n end\n R_max=max(max(abs(R(:,:,l))));\n \n if R_max<= tol\n stop=1;\n else\n [X(:,:,l+1),B(:,:,l)]=qr(R(:,:,l),0); \n% AX=multiC(A,X(:,:,l+1),m,n);\n% Y(:,:) = X(:,:,l+1);\n AX = [A*X(m+1:m+n,:,l+1);A'*X(1:m,:,l+1)];\n M(:,:,l+1)=X(:,:,l+1)'*AX;\n Q=[Q,X(:,:,l+1)];\n \n % Record the tridiagonal elments;\n Bdiag=blkdiag(Bdiag,B(:,:,l));\n Mdiag=blkdiag(Mdiag,M(:,:,l+1));\n l=l+1;\n if l>=k\n stop=1;\n end\n end\nend\n\n% Now T=Q'CQ is block tridiagonal;\nB0=[zeros(r,l*r);Bdiag,zeros(l*r-r,r)];\nT=Mdiag+B0+B0';\nT=(T+T')/2;\n\n% Compute EVD of T: T=Z*S*Z';\n[Z,S]=eig(T);\n\n% Therefore (QZ)'*C*(QZ)=S\nadd=0;\nQZ=Q*Z(:,l*r:-1:l*r-r+1-add);\nU_temp=QZ(1:m,:)*sqrt(2);\nV_temp=QZ(m+1:m+n,:)*sqrt(2);\ndS=diag(S);\nS=diag(dS(l*r:-1:l*r+1-r-add));\nif mark==1\n U=V_temp;\n V=U_temp;\nelse\n U=U_temp;\n V=V_temp;\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/SVD/BL_SVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7782215833243364}} {"text": "function [fdr,x] = fdrCurve(fit, MODE, sgn)\n\n% [fdr,x] = fdrCurve(fit, [MODE], [sgn])\n%\n% Computes the false discovery rate curve.\n%\n% Input:\n% fit Poisson regression structure from function empNull.\n% MODE Type of FDR\n% 'tail' for tail FDR (default)\n% 'local' for local FDR\n% sgn 1 (default) or -1, for right or left tail in 'FDR' case.\n% Irrelevant in 'fdr' case.\n%\n% Output:\n% fdr 3 column matrix, containing the fdr curve estimate and\n% the upper and lower limits corresponding to the 95% pointwise\n% confidence bands on the empirical distribution of T.\n% x values at which fdr is evaluated\n%\n% See also:\n% fdrEmpNull.m\n\n% HISTORY:\n% 2006.05.08 ASH (armins@hsph.harvard.edu) wrote it.\n%\n\nif ~exist('fit'),\n error('Not enough arguments')\nend\nif ~exist('MODE'),\n MODE = 'tail';\nend\nif ~exist('sgn'),\n sgn = 1;\nend\n\n[x, X, W, y, yhat] = deal(fit.x, fit.X, fit.W, fit.y, fit.yhat);\nK = length(fit.x);\n\nif strcmp(MODE,'tail'),\n S = triu(ones(K,K),1) + diag(ones(1,K))/2;\n if (sgn == -1), S = S'; end\n fdr(:,1) = (S*yhat)./(S*y);\n V = X * inv(X'*W*diag(y)*W*X) * X' * W;\n V = diag(1./(S*yhat)) * S * diag(yhat) * V - diag(1./(S*y));\nelse % local\n fdr(:,1) = yhat./y;\n V = X * inv(X'*W*diag(y)*W*X) * X' * W - diag(1./y);\nend\n\n% Confidence intervals\ncov = V * diag(y) * V';\nv = diag(cov);\nalpha = 0.05;\nfdr(:,2) = fdr(:,1) .* exp(norminv(1-alpha/2) * sqrt(v));\nfdr(:,3) = fdr(:,1) .* exp(-norminv(1-alpha/2) * sqrt(v));\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/fdrCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7781867615566699}} {"text": "function rank = subset_colex_rank ( n, t )\n\n%*****************************************************************************80\n%\n%% SUBSET_COLEX_RANK computes the colexicographic rank of 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 items 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% Output, integer RANK, the rank of the subset.\n%\n\n%\n% Check.\n%\n subset_check ( n, t );\n\n rank = 0;\n\n for i = 1 : n\n\n if ( t(i) == 1 )\n rank = rank + 2^( i - 1 );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/subset_colex_rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7781859156519887}} {"text": "function [ pn, dist ] = shape_point_near_2d ( center, p1, nside, p, pn, dist )\n\n%*****************************************************************************80\n%\n%% SHAPE_POINT_NEAR_2D: nearest point ( regular shape, point ) in 2D.\n%\n% Discussion:\n%\n% The \"regular shape\" is assumed to be an equilateral and equiangular\n% polygon, such as the standard square, pentagon, hexagon, and so on.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CENTER(2,1), the center of the shape.\n%\n% Input, real P1(2,1), the first vertex of the shape.\n%\n% Input, integer NSIDE, the number of sides in the shape.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, real PN(2,1), the point on the shape that is nearest\n% to the given point.\n%\n% Output, real DIST, the distance between the points.\n%\n\n%\n% Determine the angle subtended by a single side.\n%\n sector_angle = 360.0 / nside;\n%\n% How long is the half-diagonal?\n%\n radius = sqrt ( sum ( ( p1(1:2,1) - center(1:2,1) ).^2 ) );\n%\n% If the radius is zero, then the shape is a point and the computation is easy.\n%\n if ( radius == 0.0 )\n pn(1:2,1) = center(1:2,1);\n dist = sqrt ( sum ( ( p(1:2,1) - pn(1:2,1) ).^2 ) );\n return\n end\n%\n% If the test point is at the center, then the computation is easy.\n% The angle subtended by any side is ( 2 * PI / NSIDE ) and the\n% nearest distance is the midpoint of any such side.\n%\n if ( p(1:2,1) == center(1:2,1) )\n angle = pi / nside;\n pd(1,1) = ( p(1,1) - center(1,1) ) * cos ( angle ) ...\n + ( p(2,1) - center(2,1) ) * sin ( angle );\n pd(2,1) = - ( p(1,1) - center(1,1) ) * sin ( angle ) ...\n + ( p(2,1) - center(2,1) ) * cos ( angle );\n pn(1,1) = center(1,1) + pd(1,1) * cos ( angle );\n pn(2,1) = center(2,1) + pd(2,1) * sin ( angle );\n dist = radius * cos ( angle );\n return\n end\n%\n% Determine the angle between the ray to the first corner,\n% and the ray to the test point.\n%\n angle = angle_deg_2d ( p1(1:2,1), center(1:2,1), p(1:2,1) );\n%\n% Determine the sector of the point.\n%\n sector_index = floor ( angle / sector_angle ) + 1;\n%\n% Generate the two corner points that terminate the SECTOR-th side.\n%\n angle2 = ( sector_index - 1 ) * sector_angle;\n angle2 = degrees_to_radians ( angle2 );\n\n pa = vector_rotate_base_2d ( p1, center, angle2 );\n\n angle2 = ( sector_index ) * sector_angle;\n angle2 = degrees_to_radians ( angle2 );\n\n pb = vector_rotate_base_2d ( p1, center, angle2 );\n%\n% Determine the point on the SECTOR-th side of the shape which is\n% nearest.\n%\n [ pn, dist, t ] = segment_point_near_2d ( pa, pb, p );\n\n return\nend\n", "meta": {"author": "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/shape_point_near_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.778067974244097}} {"text": "function demoMertonModel()\n%%DEMOMERTONMODEL Demonstrates scenario simulation of two independent\n% Merton processes using the strongStochTaylorStepJump\n% function. A plot comparing the approximated paths to the true\n% path is generated. In order to demonstrate ideal results, the\n% same collection of driving processes are used for both the\n% true path and the simulations. The first line may be\n% uncommented and modified if reproducible plots are desired.\n%\n%The Merton model is discussed in detail in Chapter 1.7, pages 50-52 and \n%Chapter 9.6, page 414 of [1]. See equations 9.6.3 and 9.6.4 and the\n%discussion on page 414. Note we simplified the jump process term's \n%coefficient to c(y)=psi*y as suggested in Chapter 7.1, page 313. \n%\n%REFERENCES:\n%[1] Platen, Eckhard, and Nicola Bruti-Liberati. Numerical solution of \n% stochastic differential equations with jumps in finance. Vol. 64. \n% Springer Science & Business Media, 2010.\n%\n%July 2019 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %rng(16,'twister'); % Make the example reproducible\n close all;\n\n %Define Parameters\n X0=[1;1]; % Initial path value\n mue=[0.05;0.05]; % Drift mean\n sig=[0.2;0.2]; % Wiener process standard deviations\n psi=[-0.25;-0.25]; % Jump intensity coefficients\n T=10; % End time starting from 0\n lambda=0.3; % Poisson jump frequency for unit time interval\n\n %Define Discretization Coefficients and Derivatives\n % Assume a time invariant SDE of the form: \n % dY_{n+1} = a(Y_n) dt + b(Y_n) dW + c(Y_n) dP\n a = @(x) diag(mue)*x;\n B = @(x) diag(sig)*diag(x);\n c = @(x) diag(psi)*x;\n pBpy = cat(3,sig(1)*[1 0; 0 0],sig(2)*[0 0; 0 1]);\n pcpy = diag(psi);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%% Exact Solution %%%%%%%%%%%%%%%%%%%%%\n %The Merton model is discussed in detail on p.50-52 and p.414 of [1].\n % We simplified the compound jump process to have constant jump size.\n % See equations 9.6.3 and 9.6.4.\n\n dt = 0.001; % True path time step\n t = 0:dt:T;\n X = zeros([2,length(t)]); % A vector to contain the true path values\n X(:,1) = X0; % Initial condition\n\n %Generate Poisson samples as 2 independent compound Poisson processes\n CP = [0,genMarkedPointProc(lambda,dt,0+dt,T,0)];\n\n %Simulate 2 independent Wiener Processes\n W = [[0;0],sqrt(dt).*randn([2,length(t)-1])];\n W = cumsum(W,2);\n\n %Compute Merton Process Values using Exact Solution from [1]\n for i = 2:length(X)\n X(:,i) = X0.*exp((mue-0.5*sig.^2)*t(i)+sig.*W(:,i)+psi*CP(i));\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%% Approximations %%%%%%%%%%%%%%%%%%%%%\n\n %Define Approximation Parameters\n dtapprox = 0.5; % Approximation time step.\n tapprox = 0:dtapprox:T;\n numruns = 50; % Number of times to perform the random simulation steps.\n \n XEuler = zeros([2,length(tapprox)]);\n XEuler(:,1) = X0;\n XTaylor = zeros([2,length(tapprox)]);\n XTaylor(:,1) = X0;\n XDerFree = zeros([2,length(tapprox)]);\n XDerFree(:,1) = X0;\n \n for i = 2:length(tapprox)\n [deltaP,Wj] = getDrivers(W,CP,dtapprox,dt,i);\n \n %Get Euler Approximation\n for run = 1:numruns\n XEuler(:,i) = XEuler(:,i) + strongStochTaylorStepJump(...\n XEuler(:,i-1),a,B,@(x,k,idx)c(x),lambda,dtapprox,1,[],[],deltaP,Wj);\n end\n XEuler(:,i) = XEuler(:,i)/numruns;\n \n %Get Taylor Approximation\n for run = 1:numruns\n XTaylor(:,i) = XTaylor(:,i) + strongStochTaylorStepJump(...\n XTaylor(:,i-1),a,B,c,lambda,dtapprox,3,pBpy,pcpy,deltaP,Wj,tapprox(i));\n end\n XTaylor(:,i) = XTaylor(:,i)/numruns;\n \n %Get Derivative Free Taylor Approximation\n for run = 1:numruns\n XDerFree(:,i) = XDerFree(:,i) + strongRungeKStepJump(...\n XDerFree(:,i-1),a,B,c,lambda,dtapprox,3,deltaP,Wj,tapprox(i));\n end\n XDerFree(:,i) = XDerFree(:,i)/numruns;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%%% Plotting %%%%%%%%%%%%%%%%%%%%%%%%\n\n %Plot the Paths\n figure('Position',[10 10 900 600])\n plot3(t,X(1,:),X(2,:)); label11='Exact';\n hold on\n plot3(tapprox,XEuler(1,:),XEuler(2,:)); label12='Euler';\n plot3(tapprox,XTaylor(1,:),XTaylor(2,:)); label13='Taylor';\n plot3(tapprox,XDerFree(1,:),XDerFree(2,:)); label14='DF';\n legend(label11,label12,label13,label14)\n xlabel('Time (t)','FontSize',16)\n ylabel('Position ($X_t^{(1)}$ or $\\tilde{X}_t^{(1)})$','Interpreter','latex','FontSize',16)\n zlabel('Position ($X_t^{(2)}$ or $\\tilde{X}_t^{(2)})$','Interpreter','latex','FontSize',16)\n title('A Simulated Merton Model','FontSize',16)\n hold off\n\n %Plot the Errors\n figure('Position',[10 10 900 600])\n errorEuler = sum((X(:,1:floor(dtapprox/dt):end)-XEuler).^2)/2;\n errorTaylor = sum((X(:,1:floor(dtapprox/dt):end)-XTaylor).^2)/2;\n errorDerFree = sum((X(:,1:floor(dtapprox/dt):end)-XDerFree).^2)/2;\n plot(tapprox,errorEuler); label21='Euler';\n hold on\n plot(tapprox,errorTaylor); label22='Taylor';\n plot(tapprox,errorDerFree); label23='DF';\n legend(label21,label22,label23)\n xlabel('Time (t)','FontSize',16)\n ylabel('$\\frac{1}{2}\\left[(X_t^{(1)}-\\tilde{X}_t^{(1)})^2+(X_t^{(2)}-\\tilde{X}_t^{(2)})^2\\right]$','Interpreter','latex','FontSize',16)\n title('Mean Squared Error for Each Time Step','FontSize',16)\n hold off\nend\n\nfunction [deltaP,Wj]=getDrivers(W,CP,dtapprox,dt,iter)\n%%GETDRIVERS A helper function to automate retrieval of the correct\n% interval of values from the driving processes used for the\n% generation of the true path.\n%\n%INPUTS: W An mXlength(t) vector containing realized Wiener processes in\n% each row.\n% CP A 1Xlength(t) row vector containing a realized Poisson process.\n% dtapprox The coarse approximation time step (assumed to be constant).\n% dt The fine true path time step (assumed to be constant).\n% iter The current iteration index (assumed indices are positive and\n% begin at 1).\n%\n%OUTPUTS: deltaP The number of jumps which occurred in CP during the time\n% interval.\n% Wj An mXdeltaP+2 vector which contains the values from W\n% which most closely occured at the same time as each jump\n% counted in deltaP. This assumes the distribution of jumps\n% over the time interval are uniformly random.\n%\n%July 2019 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n\n if(iter>1)\n currentIdx=floor(dtapprox/dt)*(iter-1)+1;\n prevIdx=floor(dtapprox/dt)*(iter-2)+1;\n deltaP=CP((iter-1)*floor(dtapprox/dt)+1)-CP((iter-2)*floor(dtapprox/dt)+1);\n if(deltaP~=0)\n jumpIdx=floor((prevIdx+rand([deltaP,1])*dtapprox/dt));\n Wj=W(:,[prevIdx;jumpIdx;currentIdx]);\n else\n Wj=W(:,[prevIdx;currentIdx]);\n end\n else\n error('Iter must be >1.')\n end\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Sample_Code/demoMertonModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7780679738782639}} {"text": "function [Rchordal, tchordal] = chordal_initialization(measurements)\n% function [Rchordal, tchordal] = chordal_initialization(measurements)\n%\n% This helper function accepts a MATLAB struct containing the raw \n% measurements specifying a special Euclidean synchronization problem, and \n% returns the corresponding chordal initialization for this problem.\n%\n% INPUT: A MATLAB struct 'measurements' containing the following fields\n% (see eq. (11) in the long-form version of the paper for details):\n% edges: An (mx2)-dimension encoding the edges in the measurement network;\n% edges(k, :) = [i,j] means that the kth measurement is of the\n% relative transform from pose i to pose j. NB: This indexing scheme \n% requires that the states x_i are numbered sequentially as \n% x_1, ... x_n.\n% R: An m-dimensional cell array whose kth element is the rotational part\n% of the kth measurement\n% t: An m-dimensional cell array whose kth element is the translational\n% part of the kth measurement\n% kappa: An m-dimensional cell array whose kth element gives the precision\n% of the rotational part of the kth measurement. \n% tau: An m-dimensional cell array whose kth element gives the precision\n% of the translational part of the kth measurement.\n\n% OUTPUT: \n% -Rchordal: A d x dn block matrix Rchordal containing the estimating\n% orientations.\n% -tchordal [optional]: A d x n block matrix containing the estimated\n% positions.\n\n% Copyright (C) 2016 by David M. Rosen\n\nd = length(measurements.t{1});\nn = max(max(measurements.edges));\nm = size(measurements.edges, 1);\n\nif nargout > 1\n [B3, B2, B1] = construct_B_matrices(measurements);\nelse\n B3 = construct_B_matrices(measurements);\nend\n\n\n% First, estimate the rotations using *only* the rotational observations\nId = eye(d);\nId_vec = Id(:);\n\n% Compute the constant vector cR induced by fixing the first orientation\n% estimate to be the identity Id.\ncR = B3(:, 1:d^2) * Id_vec;\n\n% Compute an estimate of the remaining rotations by solving the resulting\n% least squares problem *without* enforcing the constraint the the\n% estimates lie in SO(d)\nr2vec = - B3(:, d^2 + 1 : end) \\ cR;\nrvec = vertcat(Id_vec, r2vec);\nR_LS = reshape(rvec, d, d*n);\n\n% Now reproject these estimates onto SO(d)\nRchordal = zeros(d, d*n);\nfor i = 1:n\n Rchordal(:, d*(i-1) + 1 : d*i) = project_to_SOd(R_LS(:, d*(i-1) + 1 : d*i));\nend\n\nif nargout > 1\n \n % Solve for the translations in terms of the rotations\n \n % Constant vector induced by fixing R\n cT = B2 * Rchordal(:);\n \n % Solve for t_2, ... t_n assuming that t_1 = 0.\n \n t2 = - B1(:, d + 1 : end) \\ cT;\n tvec = vertcat(zeros(d, 1), t2);\n tchordal = reshape(tvec, d, n);\nend\n\nend\n\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/lib/chordal_initialization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7780679732820105}} {"text": "function type = r82poly2_type ( a, b, c, d, e, f )\n\n%*****************************************************************************80\n%\n%% R82POLY2_TYPE analyzes a second order polynomial in two variables.\n%\n% Discussion:\n%\n% The polynomial has the form\n%\n% A x^2 + B y^2 + C xy + Dx + Ey + F = 0\n%\n% The possible types of the solution set are:\n%\n% 1: a hyperbola;\n% 9x^2 - 4y^2 -36x - 24y - 36 = 0\n% 2: a parabola;\n% 4x^2 + 1y^2 - 4xy + 3x - 4y + 1 = 0;\n% 3: an ellipse;\n% 9x^2 + 16y^2 +36x - 32y - 92 = 0;\n% 4: an imaginary ellipse (no real solutions);\n% x^2 + y^2 - 6x - 10y + 115 = 0;\n% 5: a pair of intersecting lines;\n% xy + 3x - y - 3 = 0\n% 6: one point;\n% x^2 + 2y^2 - 2x + 16y + 33 = 0;\n% 7: a pair of distinct parallel lines;\n% y^2 - 6y + 8 = 0\n% 8: a pair of imaginary parallel lines (no real solutions);\n% y^2 - 6y + 10 = 0\n% 9: a pair of coincident lines.\n% y^2 - 2y + 1 = 0\n% 10: a single line;\n% 2x - y + 1 = 0;\n% 11; all space;\n% 0 = 0;\n% 12; no solutions;\n% 1 = 0;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% CRC Press, 30th Edition, 1996, pages 282-284.\n%\n% Parameters:\n%\n% Input, real A, B, C, D, E, F, the coefficients.\n%\n% Output, integer TYPE, indicates the type of the solution set.\n%\n\n%\n% Handle the degenerate case.\n%\n if ( a == 0.0 && b == 0.0 && c == 0.0 )\n if ( d == 0.0 && e == 0.0 )\n if ( f == 0.0 )\n type = 11;\n else\n type = 12;\n end\n else\n type = 10;\n end\n return\n end\n\n delta = 8.0 * a * b * f ...\n + 2.0 * c * e * d ...\n - 2.0 * a * e * e ...\n - 2.0 * b * d * d ...\n - 2.0 * f * c * c;\n\n j = 4.0 * a * b - c * c;\n\n if ( delta ~= 0.0 )\n if ( j < 0.0 )\n type = 1;\n elseif ( j == 0.0 )\n type = 2;\n elseif ( 0.0 < j )\n if ( r8_sign ( delta ) ~= r8_sign ( a + b ) )\n type = 3;\n elseif ( r8_sign ( delta ) == r8_sign ( a + b ) )\n type = 4;\n end\n end\n elseif ( delta == 0.0 )\n if ( j < 0.0 )\n type = 5;\n elseif ( 0.0 < j )\n type = 6;\n elseif ( j == 0.0 )\n\n k = 4.0 * ( a + b ) * f - d * d - e * e;\n\n if ( k < 0.0 )\n type = 7;\n elseif ( 0.0 < k )\n type = 8;\n elseif ( k == 0.0 )\n type = 9;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r82poly2_type.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.778010936407014}} {"text": "clear all; close all; clc\n\nmtime=21\nL=40; n=512; x2=linspace(-L/2,L/2,n+1); x=x2(1:n); % spatial discretization\nk=(2*pi/L)*[0:n/2-1 -n/2:-1].'; % wavenumbers for FFT\nt=linspace(0,2*pi,mtime); % time domain collection points\n\nq=2*ones(mtime,1);\nfor j=2:2:mtime\n q(j)=4;\nend\nq(1)=1; q(mtime)=1;\n\n\n\nN=2;\nu=N*sech(x);\nut=fft(u);\n[t,utsol]=ode45('ch_pod_sol_rhs',t,ut,[],k);\nfor j=1:length(t)\n usol(j,:)=ifft(utsol(j,:));\nend\n\n\nfigure(1)\nsubplot(2,2,2)\nwaterfall(x,t,abs(usol)), shading interp, colormap([0 0 0])\n%hold on\n%pcolor(x,t,abs(usol2)), shading interp, %colormap(gray)\nview(20,25)\nset(gca,'Xlim',[-20 20],'Ylim',[0 2*pi],'Zlim',[0 4],'Xtick',[-20 -10 0 10 20],'Ytick',[0 3 6],'Ztick',[0 2 4], ...\n 'Fontsize',[15]);\nsubplot(2,2,4)\nwaterfall(fftshift(k),t,abs(fftshift(utsol))), shading interp, colormap([0 0 0])\nview(20,25)\nset(gca,'Xlim',[-40 40],'Ylim',[0 2*pi],'Zlim',[0 80],'Xtick',[-40 -20 0 20 40],'Ytick',[0 3 6],'Ztick',[0 40 80], ...\n 'Fontsize',[15]);\n\nX=usol.';\nfor j=1:mtime\n X2(:,j)=X(:,j)*q(j);\nend\n \n[U,S,V]=svd(X);\n[U2,S2,V2]=svd(X2);\n\n%%\n\nfigure(2)\nsubplot(3,2,1)\nsemilogy(100*diag(S)/sum(diag(S)),'ko','Linewidth',[2]), grid on, hold on\nsemilogy(100*S(1,1)/sum(diag(S)),'bo','Linewidth',[2]), \nsemilogy(2,100*S(2,2)/sum(diag(S)),'go','Linewidth',[2]), \nsemilogy(3,100*S(3,3)/sum(diag(S)),'ro','Linewidth',[2]), \n\nset(gca,'Xlim',[0 21],'Xtick',[1 6 11 16 21],'Ylim',[10^(-8) 10^3],'Ytick',[10^(-6) 10^(-3) 10^0 10^3],'Fontsize',[15])\nxlabel('')\n\nsubplot(3,2,2)\nsemilogy(100*diag(S2)/sum(diag(S2)),'ko','Linewidth',[2]), grid on, hold on\nsemilogy(100*S2(1,1)/sum(diag(S2)),'bo','Linewidth',[2]), \nsemilogy(2,100*S2(2,2)/sum(diag(S2)),'go','Linewidth',[2]), \nsemilogy(3,100*S2(3,3)/sum(diag(S2)),'ro','Linewidth',[2]), \n\nset(gca,'Xlim',[0 21],'Xtick',[1 6 11 16 21],'Ylim',[10^(-8) 10^3],'Ytick',[10^(-6) 10^(-3) 10^0 10^3],'Fontsize',[15])\nxlabel('')\n\nsubplot(3,1,2)\nsn=[-1 -1 1 -1 -1];\nfor j=1:5\n nrm=1;\n Up(:,j)=real(U(:,j))*sn(j)/nrm;\nend\nplot(x,real(Up(:,2)),'g','Linewidth',[2]), hold on\nplot(x,real(Up(:,3)),'r','Linewidth',[2])\nplot(x,real(Up(:,1)),'b','Linewidth',[2])\nset(gca,'Xlim',[-10 10],'Xtick',[-10 -5 0 5 10],'Ylim',[-0.3 0.3],'Ytick',[-0.3 0 0.3],'Fontsize',[15])\nsubplot(3,1,3)\nsn=[-1 -1 1 -1 -1];\nfor j=1:5\n nrm=sqrt(trapz(x,U2(:,j).^2));\n nrm=1;\n Up2(:,j)=real(U2(:,j))*sn(j)/nrm;\nend\nplot(x,real(Up2(:,3)),'r','Linewidth',[2]), hold on\nplot(x,real(Up2(:,2)),'g','Linewidth',[2])\nplot(x,real(Up2(:,1)),'b','Linewidth',[2])\nset(gca,'Xlim',[-10 10],'Xtick',[-10 -5 0 5 10],'Ylim',[-0.3 0.3],'Ytick',[-0.3 0 0.3],'Fontsize',[15])\nlegend('mode 3','mode 2','mode 1')\n\nfigure(3)\nplot(100*diag(S)/sum(diag(S)),'ro','Linewidth',[2])\nhold on\nplot(100*diag(S2)/sum(diag(S2)),'ko','Linewidth',[2])\n\nfigure(4)\nsig1=100*diag(S)/sum(diag(S));\nsig2=100*diag(S2)/sum(diag(S2));\ndiff=abs(sig1-sig2);\nbar(diff)\n\n%% low-rank reconstructions\n\nX1=U(:,1:3)*S(1:3,1:3)*(V(:,1:3).');\nX22=U2(:,1:3)*S2(1:3,1:3)*(V2(:,1:3).');\n\nfor j=1:mtime\n X222(:,j)=X22(:,j)/q(j);\nend\n\n\nfigure(6)\nsubplot(2,2,1)\nwaterfall(x,t,abs(X1).'), shading interp, colormap([0 0 0])\nsubplot(2,2,2)\nwaterfall(x,t,abs(X222).'), shading interp, colormap([0 0 0])\nE1=norm(X1-X);\nE2=norm(X222-X);\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/CH12/old_extra/ch_pod_quad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.77800532318143}} {"text": "function y = vector_norm(x,dim)\n%VECTOR_NORM norm for the rows/columns of a matrix\n%\n% Usage: y = vector_norm(x,dim)\n%\n% Input parameters:\n% x - matrix [n x m]\n% dim - dimension along the norm should be calculated\n%\n% Output parameter:\n% y - norm of the vectors [1 x m] or [n x 1]\n%\n% VECTOR_NORM(x,dim) calculates the p-norm (with p=2) for the vectors\n% given within the matrix along the dimension dim.\n%\n% See also: norm, vector_product\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% NOTE: this is disabled due to performance issues in HRTF extrapolation, where\n% this function is called multiple times.\n%nargmin = 2;\n%nargmax = 2;\n%narginchk(nargmin,nargmax)\n%isargmatrix(x)\n%isargpositivescalar(dim)\n\n\n%% ===== Computation =====================================================\ny = sum(abs(x).^2,dim).^(1/2);\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/vector_norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.7779690306934214}} {"text": "function x = f1_abscissas_ab ( a, b, n )\n\n%*****************************************************************************80\n%\n%% F1_ABSCISSAS_AB computes Fejer type 1 abscissas for the interval [A,B].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Walter Gautschi,\n% Numerical Quadrature in the Presence of a Singularity,\n% SIAM Journal on Numerical Analysis,\n% Volume 4, Number 3, 1967, pages 357-362.\n%\n% Joerg Waldvogel,\n% Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules,\n% BIT Numerical Mathematics,\n% Volume 43, Number 1, 2003, pages 1-18.\n%\n% Parameters:\n%\n% Input, real A, B, the endpoints of the interval.\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real X(N), the abscissas.\n%\n if ( n == 1 )\n x(1) = 0.5 * ( b + a );\n return\n end\n\n for i = 1 : n\n theta(i) = ( 2 * n - 2 * i + 1 ) * pi ...\n / ( 2 * n );\n end\n\n x(1:n) = 0.5 * ( ( b + a ) + ( b - a ) * cos ( theta(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/interp/f1_abscissas_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8723473879530492, "lm_q1q2_score": 0.777969026001889}} {"text": "function ex4bvp\n%EX4BVP Example 4 of the BVP tutorial.\n% This is a nerve impulse model considered in Example 7.1 of\n% R. Seydel, From Equilibrium to Chaos, Elsevier, 1988. The\n% differential equations\n%\n% y1' = 3*(y1 + y2 - 1/3*y1^3 + lambda)\n% y2' = -(y1 - 0.7 + 0.8*y2)/3\n%\n% are to be solved subject to periodic boundary conditions\n%\n% y1(0) = y1(T)\n% y2(0) = y2(T)\n%\n% This is an example of non-separated boundary conditions, meaning\n% that some conditions involve values of the solution at both ends\n% of the interval. Periodic boundary conditions are a common source\n% of such problems. BVP4C is unusual in that it accepts problems\n% with non-separated boundary conditions.\n%\n% The parameter lambda has the value -1.3 in the text cited. The\n% period T is unknown, which is to say that the length of the \n% interval is not known. Such problems require some preparation. \n% By scaling the independent variable to tau = t/T the problem is \n% posed on the fixed interval [0,1]. When this is done, T becomes \n% an unknown parameter, but BVP4C provides for unknown parameters.\n\n% Copyright 1999, The MathWorks, Inc.\n\n% Periodic functions evaluated in EX4INIT are used as a guess for the\n% solution on a crude mesh of 5 equally spaced points. A guess of 2*pi \n% is provided for the unknown parameter T.\nsolinit = bvpinit(linspace(0,1,5),@ex4init,2*pi);\n\noptions = bvpset('stats','on');\n\nsol = bvp4c(@ex4ode,@ex4bc,solinit,options);\nT = sol.parameters;\n\n% The independent variable needs to be rescaled to its original value\n% before plotting the solution. The initial guess is also plotted.\nclf reset\nplot(T*sol.x,sol.y(1,:),T*solinit.x,solinit.y(1,:),'o')\nlegend('solution found','initial guess');\naxis([0 T -2.2 2]);\ntitle('Nerve impulse model');\nylabel('solution y_1(t)');\nxlabel(['Periodic solution with period ',num2str(sol.parameters,4)]);\nshg\n\n% --------------------------------------------------------------------------\n\nfunction v = ex4init(x)\n%EX4INIT Guess function for Example 4 of the BVP tutorial.\n% V = EX4INIT(X) returns a column vector V that is a guess for y(x).\nv = [ sin(2*pi*x) \n cos(2*pi*x)];\n\n% --------------------------------------------------------------------------\n\nfunction dydt = ex4ode(t,y,T);\n%EX4ODE ODE funcion for Example 4 of the BVP tutorial.\ndydt = [ 3*T*(y(1) + y(2) - 1/3*(y(1)^3) - 1.3);\n (-1/3)*T*(y(1) - 0.7 + 0.8*y(2)) ];\n\n% --------------------------------------------------------------------------\n\nfunction res = ex4bc(ya,yb,T)\n%EX4BC Boundary conditions for Example 4 of the BVP tutorial.\nres = [ya(1) - yb(1)\n ya(2) - yb(2)\n T*(-1/3)*(ya(1) - 0.7 + 0.8*ya(2)) - 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/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples/ex4bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8723473713594991, "lm_q1q2_score": 0.7779690237455363}} {"text": "function FPDF = GaussPDF\n% Return function handles to routines to calculate the area, mean, and\n% second moment of a unit-variance, zero-mean, Gaussian probability\n% density function.\n% b\n% Farea(a,b) = Int p(x) dx\n% a\n% b\n% Fmean(a,b) = Int x p(x) dx\n% a\n% b\n% Fvar(a,b) = Int x^2 p(x) dx\n% a\n% where p(x) = 1/sqrt(2 pi) e^(-x^2/2)\n\nFPDF = {@Garea, @Gmean, @Gvar};\n\n% ----- ------\nfunction v = Garea (a, b)\n\n% Evaluate the function so as to avoid taking differences\n% between nearly equal quantities (e.g. when a<0 and b<0)\nif (b >= 0)\n if (a >= 0)\n v = F0(b) - F0(a); % Both a and b positive\n else\n v = (F0(b) + 0.5) + (F0(-a) + 0.5); % a negative, b positive\n end\nelse\n if (a < 0)\n v = F0(-a) - F0(-b); % Both a and b negative\n else\n v = (-0.5 - F0(a)) + (-0.5 - F0(-b)); % a positive, b negative\n end\nend\n\nreturn\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F0(b) - F0(a)\n%\n% F0(x) = c Int e^(-x^2/2) dx [c = 1/sqrt(2 pi)]\n% = -Q(x)\n% = -1/2 erfc(x/sqrt(2))\n\nfunction v = F0(x)\n\nv = -0.5*erfc(x/sqrt(2));\n\nreturn\n\n\n% ----- ------\nfunction v = Gmean (a, b)\n\n% Since the integrand x*p(x) is odd, Gmean(A,B)=Gmean(abs(A),abs(B))\nv = F1(abs(b)) - F1(abs(a));\n\nreturn\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F1(b) - F1(a)\n%\n% F1(x) = c Int x e^(-x^2/2) du,\n%\n% A change of variables v=x^2/2, dv=x dx, gives\n%\n% F1(x) = c Int e^(-v) dv\n% = -c e^(-v)\n% = -c e^(-x^2/2)\n\nfunction v = F1 (x)\n\nv = -exp(-0.5*x^2)/sqrt(2*pi);\n\nreturn\n\n% ----- ------\nfunction v = Gvar (a, b)\n\n% Evaluate the function so as to avoid taking differences\n% between nearly equal quantities (e.g. when a<0 and b<0)\nif (b >= 0)\n if (a >= 0)\n v = F2(b) - F2(a); % Both a and b positive\n else\n v = (F2(b) + 0.5) + (F2(-a) + 0.5); % a negative, b positive\n end\nelse\n if (a < 0)\n v = F2(-a) - F2(-b); % Both a and b negative\n else\n v = (-0.5 - F2(a)) + (-0.5 - F2(-b)); % a positive, b negative\n end\nend\n\nreturn\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F2(b) - F2(a)\n%\n% F2(x) = c Int x^2 e^(-x^2/2) dx\n%\n% Using integration by parts, identify\n% f(x) = x, f'(x) = 1,\n% g'(u) = x e^(-x2/2), g(x) = -e^(-x^2/2)\n%\n% Int f(x) g'(x) dx = f(x) g(x) - Int f'(x) g(x) dx\n%\n% Then\n% F2(x) = -c x e^(-x^2/2) + c Int e^(-x^2/2) dx\n% = -c x e^(-x^2/2) - Q(x)\n\nfunction v = F2 (x)\n\n% The function evaluation fails for x = Inf because the term x e^(-x^2/2)\n% in the expression returns NaN. For non-infinite x, the expression\n% evaluates to 0 for large x.\nxmax = 40;\nif (x > xmax)\n v = 0;\nelse\n v = -x*exp(-0.5*x^2)/sqrt(2*pi) - 0.5*erfc(x/sqrt(2));\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/private/GaussPDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7779662930156026}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n%problem 1\n\n%x(t) =t*exp(-t), 0 1)\n warning('The specified AR model is unstable.')\n end\n \n % Discard the first ndisc time steps; if ndisc is not given as input\n % argument, use default\n if (nargin < 5) \n ndisc = 10^3; \n end\n \n % Compute Cholesky factor of covariance matrix C\n [R, err]= chol(C); % R is upper triangular\n if err ~= 0\n error('Covariance matrix not positive definite.')\n end\n \n % Get ndisc+n independent Gaussian pseudo-random vectors with \n % covariance matrix C=R'*R\n randvec = randn([ndisc+n,m])*R;\n\n % Add intercept vector to random vectors\n randvec = randvec + ones(ndisc+n,1)*w;\n \n % Get transpose of system matrix A (use transpose in simulation because \n % we want to obtain the states as row vectors)\n AT = A';\n\n % Take the p initial values of the simulation to equal the process mean, \n % which is calculated from the parameters A and w\n if any(w)\n % Process has nonzero mean mval = inv(B)*w' where \n % B = eye(m) - A1 -... - Ap; \n % Assemble B\n B \t = eye(m);\n for j=1:p\n B = B - A(:, (j-1)*m+1:j*m);\n end\n % Get mean value of process\n mval = w / B';\n\n % The optimal forecast of the next state given the p previous\n % states is stored in the vector x. The vector x is initialized\n % with the process mean.\n x = ones(p,1)*mval;\n else\n % Process has zero mean\n x = zeros(p,m); \n end\n \n % Initialize state vectors\n u = [x; zeros(ndisc+n,m)];\n \n % Simulate n+ndisc observations. In order to be able to make use of\n % Matlab's vectorization capabilities, the cases p=1 and p>1 must be\n % treated separately.\n if p==1\n for k=2:ndisc+n+1; \n x(1,:) = u(k-1,:)*AT;\n u(k,:) = x + randvec(k-1,:);\n end\n else\n for k=p+1:ndisc+n+p; \n for j=1:p;\n\tx(j,:) = u(k-j,:)*AT((j-1)*m+1:j*m,:);\n end\n u(k,:) = sum(x)+randvec(k-p,:);\n end\n end\n \n % return only the last n simulated state vectors\n v = u(ndisc+p+1:ndisc+n+p,:); \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/174-arfit/arsim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7779662785709801}} {"text": "function qwgw_test01 ( )\n\n%*****************************************************************************80\n%\n%% TEST01 tests QWGW for the Chebyshev Type 1 weight.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n\n%\n% Set the quadrature interval and number of points.\n%\n a = -1.0;\n b = +1.0;\n n = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01:\\n' );\n fprintf ( 1, ' Compute points and weights for Gauss quadrature\\n' );\n fprintf ( 1, ' with the Chebyshev Type 1 weight w(x) = 1/sqrt(1-x^2).\\n' );\n fprintf ( 1, ' Order N = %d\\n', n );\n fprintf ( 1, ' Interval = [%g,%g]\\n', a, b );\n%\n% Set the recursion coefficients.\n%\n aj = zeros ( n, 1 );\n bj = zeros ( n, 1 );\n\n aj(1:n) = 0.0;\n\n bj(1) = 1.0 / 2.0;\n for j = 2 : n - 1\n bj(j) = 1.0 / 4.0;\n end\n bj(n) = 0.0;\n\n bj(1:n) = sqrt ( bj(1:n) );\n\n mu0 = pi;\n%\n% Compute the points and weights.\n%\n [ x, w ] = sgqf ( n, aj, bj, mu0 );\n\n r8vec_print ( n, x, ' Abscissas:' );\n r8vec_print ( n, w, ' Weights:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_golub_welsch/qwgw_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.777964649866414}} {"text": "function value = r4_acos ( x )\n\n%*****************************************************************************80\n%\n%% R4_ACOS evaluates the arc-cosine of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the arc-cosine of X.\n%\n value = 0.5 * pi - r4_asin ( x );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_acos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7779646370562412}} {"text": "function a = complex_i ( )\n\n%*****************************************************************************80\n%\n%% COMPLEX_I returns the COMPLEX_I matrix.\n%\n% Formula:\n%\n% 0 1\n% -1 0\n%\n% Properties:\n%\n% A is integral: int ( A ) = A.\n%\n% A is anti-involutional: A * A = - I\n%\n% A * A * A * A = I\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real A(2,2), the matrix.\n%\n a(1,1) = 0.0;\n a(1,2) = 1.0;\n a(2,1) = -1.0;\n a(2,2) = 0.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/complex_i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7779414609620262}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% \n% \n% problem 1- Unilateral Laplace Transform computation \n\nsyms s t\nf=-1.25+3.5*t*exp(-2*t) +1.25*exp(-2*t);\n\nF=laplace(f,s);\nsimplify (F);\npretty(ans) \n\n%verification\nf=ilaplace(F,t);\nsimplify(f);\npretty(ans)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/9/c99a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7778508408844214}} {"text": "% \n% Computing the numerical rank of a updated matrix.\n%\n% \n% [r,Basis,C] = NumericalRankUpdate(A,pth,vec,C,RC)\n%\n% \n% 1. A -- the target matrix;\n% 2. pth -- the index of row/column to be inserted;\n% 3. vec -- the row/column vector to be inserted;\n% 4. C -- cell array contains information required by updating/downdating;\n% 5. RC -- Set to 'row', then the pth row will be inserted.\n% Set to 'column', then the pth column will be inserted.\n%\n% \n% 1. r -- the numerical rank of the updated matrix;\n% 2. Basis --\n% For high rank cases...\n% a matrix whose columns form an orthonormal basis of\n% the numerical kernel;\n%\n% For low rank cases...\n% a matrix whose columns form an orthonormal basis of\n% the numerical range;\n%\n% 3. C -- Matlab cell array\n%\n% For high rank cases...\n% C{1,1} = rank : the numerical rank of the updated matrix;\n% C{2,1} = Basis : matrix whose columns form an orthonormal kernel basis;\n% C{3,1} = Q : the Q in the QR decomposition of the kernel stacked matrix;\n% C{4,1} = R : the R in the QR decomposition of the kernel stacked matrix;\n% C{5,1} = tau : scaling factor in the kernel stacked matrix;\n% C{6,1} = tol : the rank decision threshold;\n%\n% For low rank cases...\n% C{1,1} = rank : the numerical rank of the updated matrix;\n% C{2,1} = U : the U in the USV+E decomposition of the updated matrix;\n% C{3,1} = V : the V in the USV+E decomposition of the updated matrix;\n% C{4,1} = S : the S in the USV+E decomposition of the updated matrix;\n% C{5,1} = tol : the rank decision threshold;\n%\n% \n% [1] T.Y. Li and Z. Zeng, \"A Rank-Revealing Method with Updating, Downdating\n% and Applications\", SIAM J. Matrix Anal. and Appl., 26 (2005), pp. 918--946.\n%\n% [2] T.L. Lee, T.Y. Li and Z. Zeng, \"A Rank-Revealing Method with Updating, \n% Downdating and Applications, Part II\", SIAM J. Matrix Anal. and Appl. (2009).\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/NumericalRankUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7778487104245745}} {"text": "function ilt = euler_inversion_sym(f_s, t, M, P)\n\n% ilt = euler_inversion_sym(f_s, t, [M], [P])\n%\n% Returns an approximation to the inverse Laplace transform of function\n% handle f_s evaluated at each value in t (1xn) using the Euler method as\n% summarized in the source below. This is a symbolic implementation capable\n% of much greater accuracy than euler_inversion. For this reason, it takes\n% an additional argument, P, the number of significant digits required by\n% the calculation. In general, P should be about 0.6*M.\n%\n% f_s: Handle to function of s\n% t: Times at which to evaluate the inverse Laplace transformation of f_s\n% M: Optional number of terms to sum for each t (64 is a good guess);\n% highly oscillatory functions require higher M, but this can grow\n% unstable; see example_inversions.m for an example of stability [64]\n% P: Optional precision of calculation in significant digits [default 32]\n% \n% Requires the Symbolic Toolbox(TM).\n%\n% Abate, Joseph, and Ward Whitt. \"A Unified Framework for Numerically \n% Inverting Laplace Transforms.\" INFORMS Journal of Computing, vol. 18.4 \n% (2006): 408-421. Print.\n% \n% The paper is also online: http://www.columbia.edu/~ww2040/allpapers.html.\n% \n% Tucker McClure\n% Copyright 2012, The MathWorks, Inc.\n\n % Make sure t is n-by-1.\n if size(t, 1) == 1\n t = t';\n elseif size(t, 2) > 1\n error('Input times, t, must be a vector.');\n end\n\n % Set M to 64 if user didn't specify an M.\n if nargin < 3, M = 32; end\n \n % Set P to the greater of the default from digits() or 0.6M.\n if nargin < 4, P = max(floor(0.6*M), digits()); end\n \n % Vectorized Talbot's algorithm\n \n % Binominal function\n bnml = @(n, z) factorial(n)/(factorial(z)*factorial(n-z));\n \n xi = sym([0.5, ones(1, M), zeros(1, M-1), 2^-sym(M)]);\n for k = 1:M-1\n xi(2*M-k + 1) = xi(2*M-k + 2) + 2^-sym(M) * bnml(sym(M), sym(k));\n end\n k = sym(0:2*M); % Iteration index\n beta = vpa(sym(M)*log(sym(10))/3 + 1i*pi*k, P);\n eta = vpa((1-mod(k, 2)*2) .* xi, P);\n \n % Make a mesh so we can do this entire calculation across all k for all\n % given times without a single loop (it's faster this way).\n [beta_mesh, t_mesh] = meshgrid(beta, sym(t));\n eta_mesh = meshgrid(eta, t);\n \n % Finally, calculate the inverse Laplace transform for each given time.\n f_s_evals = arrayfun(f_s, beta_mesh./t_mesh, 'UniformOutput', false);\n f_s_evals = vpa(reshape([f_s_evals{:}], size(beta_mesh)), P);\n ilt = vpa(10^(sym(M)/3)./sym(t).*sum(eta_mesh.*real(f_s_evals), 2), 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/39035-numerical-inverse-laplace-transform/euler_inversion_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7778430857540735}} {"text": "function [ n_data, n, m, x, fx ] = legendre_associated_normalized_values ...\n ( n_data )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_ASSOCIATED_NORMALIZED_VALUES: normalized associated Legendre.\n%\n% Discussion:\n%\n% The function considered is the associated Legendre polynomial P^M_N(X).\n%\n% In Mathematica, the function can be evaluated by:\n%\n% LegendreP [ n, m, x ]\n%\n% The function is normalized by dividing by\n%\n% sqrt ( 4 * pi * ( n + m )! / ( 2 * n + 1 ) / ( n - m )! )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964,\n% ISBN: 0-486-61272-4,\n% LC: QA47.A34.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Cambridge University Press, 1999,\n% ISBN: 0-521-64314-7,\n% LC: QA76.95.W65.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0\n% before the first call. On each call, the routine increments N_DATA by 1,\n% and returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, integer M, real X,\n% the arguments of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 21;\n\n fx_vec = [ ...\n 0.2820947917738781, ...\n 0.2443012559514600, ...\n -0.2992067103010745, ...\n -0.07884789131313000, ...\n -0.3345232717786446, ...\n 0.2897056515173922, ...\n -0.3265292910163510, ...\n -0.06997056236064664, ...\n 0.3832445536624809, ...\n -0.2709948227475519, ...\n -0.2446290772414100, ...\n 0.2560660384200185, ...\n 0.1881693403754876, ...\n -0.4064922341213279, ...\n 0.2489246395003027, ...\n 0.08405804426339821, ...\n 0.3293793022891428, ...\n -0.1588847984307093, ...\n -0.2808712959945307, ...\n 0.4127948151484925, ...\n -0.2260970318780046 ]';\n m_vec = [ ...\n 0, 0, 1, 0, ...\n 1, 2, 0, 1, ...\n 2, 3, 0, 1, ...\n 2, 3, 4, 0, ...\n 1, 2, 3, 4, ...\n 5 ]';\n n_vec = [ ...\n 0, 1, 1, 2, ...\n 2, 2, 3, 3, ...\n 3, 3, 4, 4, ...\n 4, 4, 4, 5, ...\n 5, 5, 5, 5, ...\n 5 ]';\n x_vec = [ ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50, ...\n 0.50 ]';\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 m = 0;\n x = 0.0;\n fx = 0.0;\n else\n n = n_vec(n_data);\n m = m_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/spherical_harmonic/legendre_associated_normalized_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.777843080157802}} {"text": "function variance = weibull_variance ( a, b, c )\n\n%*****************************************************************************80\n%\n%% WEIBULL_VARIANCE returns the variance of the Weibull PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, the parameters of the PDF.\n% 0.0 < B,\n% 0.0 < C.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n g1 = gamma ( ( c + 2.0 ) / c );\n g2 = gamma ( ( c + 1.0 ) / c );\n\n variance = b * b * ( g1 - g2 * g2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/weibull_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7778430783956318}} {"text": "%% Example \n%\n% Copyright: \n% 2018 - Simo Särkkä and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%% Leapfrog / Verlet integration\n\ndts = logspace(-2,0,10);\nerr = nan(10,numel(dts));\n\nfor j=1:numel(dts)\n fprintf('Running step %d/%d\\n',j,numel(dts));\n\n% Leapfrog / Verlet integration\n\n % Lock seed\n if exist('rng') % Octave doesn't have rng\n rng(j,'twister')\n else\n randn('state',j);\n end\n\n % Parameters\n n = 25000;\n g = 1; % g>0\n eta = 1;\n q = 1;\n x0 = 1;\n v0 = 0;\n\n % Time discretization\n dt = dts(j); %0.1;\n t = 0:dt:10;\n \n % Specify the model\n f = @(x) -g*x;\n s = @(x) 1;\n \n % Allocate space and set initial conditions\n x = zeros(n,numel(t)); x(:,1) = x0;\n v = zeros(n,numel(t)); v(:,1) = v0;\n \n % For each trajectory\n for i=1:n\n\n % Simulate one trajectory from the leapfrog method\n z = leapfrog(f,s,eta,t,[x0; v0],q);\n \n x(i,:) = z(1,:);\n v(i,:) = z(2,:);\n \n end\n \n figure(1); clf\n subplot(211)\n plot(t,x(1:5,:), ...\n t,mean(x), ...\n t,mean(x)+1.96*std(x),'--', ...\n t,mean(x)-1.96*std(x),'--')\n xlabel('Time, t'), ylabel('Position, x(t)') \n subplot(212)\n plot(t,v(1:5,:), ...\n t,mean(v), ...\n t,mean(v)+1.96*std(v),'--', ...\n t,mean(v)-1.96*std(v),'--')\n xlabel('Time, t'), ylabel('Velocity, v(t)') \n \n \n% Euler-Maruyama\n\n % Same random seed\n % Lock seed\n if exist('rng') % Octave doesn't have rng\n rng(j,'twister')\n else\n randn('state',j);\n end\n\n % Specify the model\n f = @(x,t) [0 1; -g -eta]*x;\n L = @(x,t) [0; 1];\n \n % Allocate space and set initial conditions\n x_em = zeros(n,numel(t)); x_em(:,1) = x0;\n v_em = zeros(n,numel(t)); v_em(:,1) = v0;\n \n % For each trajectory\n for i=1:n\n\n % Simulate one trajectory from the leapfrog method\n z = eulermaruyama(f,L,t,[x0; v0],q);\n \n x_em(i,:) = z(1,:);\n v_em(i,:) = z(2,:);\n \n end\n \n figure(1); clf\n subplot(211)\n plot(t,x_em(1:5,:), ...\n t,mean(x_em), ...\n t,mean(x_em)+1.96*std(x_em),'--', ...\n t,mean(x_em)-1.96*std(x_em),'--')\n xlabel('Time, t'), ylabel('Position, x(t)')\n subplot(212)\n plot(t,v(1:5,:), ...\n t,mean(v_em), ...\n t,mean(v_em)+1.96*std(v_em),'--', ...\n t,mean(v_em)-1.96*std(v_em),'--')\n xlabel('Time, t'), ylabel('Velocity, v(t)')\n \n \n% Closed-form solution\n\n % This is a LTI SDE of the form\n F = [0 1; -g -eta];\n L = [0; 1];\n Qc = q;\n\n % Discretize\n [A,Q] = lti_disc(F,L,Qc,dt);\n \n % Evaluate\n M = zeros(2,numel(t)); M(:,1) = [x0; v0];\n P = zeros(2,2,numel(t));\n \n % Loop through\n for k=1:numel(t)-1\n M(:,k+1) = A*M(:,k);\n P(:,:,k+1) = A*P(:,:,k)*A'+Q;\n end\n \n figure(2); clf\n subplot(211)\n plot(t,M(1,:), ...\n t,M(1,:)'+1.96*sqrt(squeeze(P(1,1,:))),'--', ...\n t,M(1,:)'-1.96*sqrt(squeeze(P(1,1,:))),'--')\n subplot(212)\n plot(t,M(2,:), ...\n t,M(2,:)'+1.96*sqrt(squeeze(P(2,2,:))),'--', ...\n t,M(2,:)'-1.96*sqrt(squeeze(P(2,2,:))),'--')\n\n \n% Calculate errors\n \n err(1,j) = P(1,1,end)-std(x(:,end))^2;\n err(2,j) = P(2,2,end)-std(v(:,end))^2;\n \n err(3,j) = P(1,1,end)-std(x_em(:,end))^2;\n err(4,j) = P(2,2,end)-std(v_em(:,end))^2;\n\n err(5,j) = M(1,end)-mean(x(:,end));\n err(6,j) = M(2,end)-mean(v(:,end));\n \n err(7,j) = M(1,end)-mean(x_em(:,end));\n err(8,j) = M(2,end)-mean(v_em(:,end));\n \n err(9,j) = mean(abs(squeeze(P(1,1,:))'-std(x).^2));\n err(10,j) = mean(abs(squeeze(P(1,1,:))'-std(x_em).^2));\n \n \nend\n\n\n%% Compose results\n\n figure(1); clf\n loglog(dts,abs(err(9,:)),'-k', ...\n dts,abs(err(10,:)),'--k')\n xlabel('Time step length, $\\Delta t$')\n ylabel('Mean absolute error in $\\sigma_x^2$')\n legend('Leapfrog Verlet', 'Euler--Maruyama')\n %ylim([0.4 10])\n xlim([min(dts) max(dts)])\n set(gca,'XTick',[0.01 0.1 1],'XTickLabel',[0.01 0.1 1])\n set(gca,'YTick',[1e-3 1e-2 1e-1 1e0 1e1], ...\n 'YTickLabel',{'','$10^{-2}$','$10^{-1}$','$10^{0}$','$10^1$'})\n", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch08_ex21_leapfrog_verlet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7778430739420058}} {"text": "function Ft = CIELabFunction(t, inverse)\n%\n% Ft = CIELabFunction(t, inverse)\n%\n%\n% Input:\n% -t: image\n% -inverse: takes as values 0 or 1. If it is set to 1 the\n% transformation from XYZ to CIE Lab is applied, otherwise\n% the transformation from CIE Lab to XYZ\n%\n% Output:\n% -Ft: application of CIE Lab f or f^{-1} (if inverse = 1) to X\n%\n% Copyright (C) 2013 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\nif(inverse == 0) %forward function\n Ft = zeros(size(t));\n \n c1 = (6 / 29)^3;\n c2 = ((29 / 6)^2)/3;\n c3 = 4 / 29;\n \n Ft(t > c1) = t(t > c1).^(1 / 3);\n Ft(t <= c1) = t(t <= c1) * c2 + c3;\nend\n\nif(inverse == 1) %inverse function\n Ft = zeros(size(t));\n\n c1 = 6 / 29;\n c2 = ((6 / 29)^2) * 3;\n c3 = 4 / 29;\n \n Ft(t > c1) = t(t > c1).^3;\n Ft(t <= c1) = (t(t <= c1) - c3) * c2; \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/CIELabFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475715065792, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7777541540125861}} {"text": "function angle = lines_exp_angle_3d ( p1, p2, q1, q2 )\n\n%*****************************************************************************80\n%\n%% LINES_EXP_ANGLE_3D finds the angle between two explicit lines in 3D.\n%\n% Discussion:\n%\n% The explicit form of a line in 3D is:\n%\n% ( P1, P2 ) = ( (X1,Y1,Z1), (X2,Y2,Z3) ).\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,1), P2(3,1), two points on the first line.\n%\n% Input, real Q1(3,1), Q2(3,1), two points on the second line.\n%\n% Output, real ANGLE, the angle in radians between the two\n% lines. The angle is computed using the ACOS function, and so lies between\n% 0 and PI. But if one of the lines is degenerate, the angle is\n% returned as -1.0.\n%\n dim_num = 3;\n\n pnorm = sqrt ( sum ( ( p2(1:dim_num,1) - p1(1:dim_num,1) ).^2 ) );\n\n if ( pnorm == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINES_EXP_ANGLE_3D - Fatal error!\\n' );\n fprintf ( 1, ' The line (P1,P2) is degenerate!\\n' );\n angle = -1.0;\n return\n end\n\n qnorm = sqrt ( sum ( ( q2(1:dim_num,1) - q1(1:dim_num,1) ).^2 ) );\n\n if ( qnorm == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINES_EXP_ANGLE_3D - Fatal error!\\n' );\n fprintf ( 1, ' The line (Q1,Q2) is degenerate!\\n' );\n angle = -1.0;\n return\n end\n\n pdotq = ( p2(1:dim_num,1) - p1(1:dim_num,1) )' ...\n * ( q2(1:dim_num,1) - q1(1:dim_num,1) );\n\n ctheta = pdotq / ( pnorm * qnorm );\n\n angle = r8_acos ( ctheta );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/lines_exp_angle_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7777127302540366}} {"text": "function taun = tau ( n, taun )\n\n%*****************************************************************************80\n%\n%% TAU returns the value of TAU(N), the number of distinct divisors of N.\n%\n% Discussion:\n%\n% TAU(N) is the number of divisors of N, including 1 and N.\n%\n% First values:\n%\n% N TAU(N)\n%\n% 1 1\n% 2 2\n% 3 2\n% 4 3\n% 5 2\n% 6 4\n% 7 2\n% 8 4\n% 9 3\n% 10 4\n% 11 2\n% 12 6\n% 13 2\n% 14 4\n% 15 4\n% 16 5\n% 17 2\n% 18 6\n% 19 2\n% 20 6\n%\n% Formula:\n%\n% If the prime factorization of N is\n%\n% N = P1^E1 * P2^E2 * ... * PM^EM,\n%\n% then\n%\n% TAU(N) = ( E1 + 1 ) * ( E2 + 1 ) * ... * ( EM + 1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the value to be analyzed. N must be 1 or\n% greater.\n%\n% Output, integer TAUN, the value of TAU(N). But if N is 0 or\n% less, TAUN is returned as 0, a nonsense value. If there is\n% not enough room for factoring, TAUN is returned as -1.\n%\n if ( n <= 0 )\n taun = 0;\n return\n end\n\n if ( n == 1 )\n taun = 1;\n return\n end\n%\n% Factor N.\n%\n [ nfactor, factor, power, nleft ] = i4_factor ( n );\n\n if ( nleft ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TAU - Fatal error!\\n' );\n fprintf ( 1, ' Not enough factorization space.\\n' );\n taun = -1;\n error ( 'TAU - Fatal error!' );\n end\n\n taun = 1;\n for i = 1 : nfactor\n taun = taun * ( power(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/tau.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7777127178102363}} {"text": "function value = fall ( x, n )\n\n%*****************************************************************************80\n%\n%% FALL computes the falling factorial function [X]_N.\n%\n% Discussion:\n%\n% The number of \"injections\" or 1-to-1 mappings from\n% a set of N elements to a set of M elements is [M]_N.\n%\n% The number of permutations of N objects out of M is [M}_N.\n%\n% The Stirling numbers of the first kind can be used\n% to convert a falling factorial into a polynomial, as follows:\n%\n% [X]_N = S^0_N + S^1_N * X + S^2_N * X^2 + ... + S^N_N X^N.\n%\n% Formula:\n%\n% [X]_N = X * ( X - 1 ) * ( X - 2 ) * ... * ( X - N + 1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X, the argument of the falling factorial\n% function.\n%\n% Input, integer N, the order of the falling factorial function.\n% If N = 0, FALL = 1, if N = 1, FALL = X. Note that if N is\n% negative, a \"rising\" factorial will be computed.\n%\n% Output, integer VALUE, the falling factorial function.\n%\n value = 1;\n\n arg = x;\n\n if ( 0 < n )\n\n for i = 1 : n\n value = value * arg;\n arg = arg - 1;\n end\n\n elseif ( n < 0 )\n\n for i = -1 : - 1 : - n\n value = value * arg;\n arg = arg + 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/fall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7776952791190447}} {"text": "function [bp,wf]=grule(n)\n%\n% [bp,wf]=grule(n)\n% This function computes Gauss base points and weight factors\n% using the algorithm given by Davis and Rabinowitz in 'Methods\n% of Numerical Integration', page 365, Academic Press, 1975.\n%\nbp=zeros(n,1); wf=bp; iter=2; m=fix((n+1)/2); e1=n*(n+1);\nmm=4*m-1; t=(pi/(4*n+2))*(3:4:mm); nn=(1-(1-1/n)/(8*n*n));\nxo=nn*cos(t);\nfor j=1:iter\n pkm1=1; pk=xo;\n for k=2:n\n t1=xo.*pk; pkp1=t1-pkm1-(t1-pkm1)/k+t1;\n pkm1=pk; pk=pkp1;\n end\n den=1.-xo.*xo; d1=n*(pkm1-xo.*pk); dpn=d1./den;\n d2pn=(2.*xo.*dpn-e1.*pk)./den;\n d3pn=(4*xo.*d2pn+(2-e1).*dpn)./den;\n d4pn=(6*xo.*d3pn+(6-e1).*d2pn)./den;\n u=pk./dpn; v=d2pn./dpn;\n h=-u.*(1+(.5*u).*(v+u.*(v.*v-u.*d3pn./(3*dpn))));\n p=pk+h.*(dpn+(.5*h).*(d2pn+(h/3).*(d3pn+.25*h.*d4pn)));\n dp=dpn+h.*(d2pn+(.5*h).*(d3pn+h.*d4pn/3));\n h=h-p./dp; xo=xo+h;\nend\nbp=-xo-h;\nfx=d1-h.*e1.*(pk+(h/2).*(dpn+(h/3).*(d2pn+(h/4).*(d3pn+(.2*h).*d4pn))));\nwf=2*(1-bp.^2)./(fx.*fx);\nif ( (m+m) > n )\n\tbp(m)=0; \nend\nif ( ~ ((m+m) == n) )\n\tm=m-1;\nend\njj=1:m; n1j=(n+1-jj); bp(n1j)=-bp(jj); wf(n1j)=wf(jj);\nbp = reshape(bp,length(bp),1);\nwf = reshape(wf,length(wf),1);\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/utils/grule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7776952752828229}} {"text": "function [EC,ec,degij] = edge_nei_overlap_bu(CIJ)\n%EDGE_NEI_OVERLAP_BU overlap amongst neighbors of two adjacent nodes\n%\n% [EC,ec,degij] = edge_nei_bu(CIJ);\n%\n% This function determines the neighbors of two nodes that are linked by \n% an edge, and then computes their overlap. Connection matrix must be\n% binary and directed. Entries of 'EC' that are 'inf' indicate that no\n% edge is present. Entries of 'EC' that are 0 denote \"local bridges\", i.e.\n% edges that link completely non-overlapping neighborhoods. Low values\n% of EC indicate edges that are \"weak ties\".\n%\n% If CIJ is weighted, the weights are ignored.\n%\n% Inputs: CIJ, undirected (binary/weighted) connection matrix\n% \n% Outputs: EC, edge neighborhood overlap matrix\n% ec, edge neighborhood overlap per edge, in vector format\n% degij, degrees of node pairs connected by each edge\n%\n% Reference: Easley and Kleinberg (2010) Networks, Crowds, and Markets. \n% Cambridge University Press, Chapter 3.\n%\n% Olaf Sporns, Indiana University, 2012\n\n[ik,jk,ck] = find(CIJ);\nlel = length(ck);\nN = size(CIJ,1);\n\n[deg] = degrees_und(CIJ);\n\nec = zeros(1,lel);\ndegij = zeros(2,lel);\nfor e=1:lel\n neiik = setdiff(union(find(CIJ(ik(e),:)),find(CIJ(:,ik(e))')),[ik(e) jk(e)]);\n neijk = setdiff(union(find(CIJ(jk(e),:)),find(CIJ(:,jk(e))')),[ik(e) jk(e)]);\n ec(e) = length(intersect(neiik,neijk))/length(union(neiik,neijk));\n degij(:,e) = [deg(ik(e)) deg(jk(e))];\nend;\n\nff = find(CIJ);\nEC = 1./zeros(N);\nEC(ff) = ec; %#ok\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/edge_nei_overlap_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7776952679448144}} {"text": "function count = subset_sum_count ( w, t, r )\n\n%*****************************************************************************80\n%\n%% SUBSET_SUM_COUNT counts the solutions to the subset sum problem in a given range.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer W(N), a set of weights. The length of this\n% array must be no more than 31.\n%\n% Input, integer T, the target value.\n%\n% Input, integer R(2), the lower and upper limits to be searched.\n% If this argument is omitted, the entire range, [0, 2^N-1 ] will\n% be searched.\n%\n% Output, integer COUNT, the number of solutions found in this range.\n%\n c = [];\n index = [];\n%\n% Using a single integer to track the subsets only works if the number\n% of objects is small enough. MATLAB can pack no more than 31 bits of\n% information into a nonnegative integer.\n%\n if ( nargin < 1 )\n w = input ( 1, ' Enter the vector of weights [ w(1), w(2), ..., w(n)]: ' );\n end\n\n n = length ( w );\n\n if ( 31 < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SUBSET_SUM_FIND - Fatal error!\\n' );\n fprintf ( 1, ' This function is restricted to N <= 31.\\n' );\n error ( 'SUBSET_SUM_FIND - Fatal error!' );\n end\n\n if ( nargin < 2 )\n t = input ( ' Enter the target value T: ' );\n end\n%\n% Make sure the range is reasonable.\n%\n if ( nargin < 3 )\n r(1) = 0;\n r(2) = 2^n - 1;\n else\n r(1) = max ( r(1), 0 );\n r(2) = min ( r(2), 2^n - 1 );\n end\n\n fprintf ( 1, '\\n' )\n fprintf ( 1, ' Searching indices %d through %d\\n', r(1), r(2) );\n%\n% Run through the range.\n%\n count = 0;\n\n for index = r(1) : r(2)\n%\n% Convert INDEX into vector of indices in W.\n%\n c = find ( bitget ( index, 1:n ) );\n%\n% If the sum of those weights matches the target, increment the count.\n%\n if ( sum ( w(c) ) == t )\n count = count + 1;\n end\n\n end\n\n index = [];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/subset_sum/subset_sum_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7776952679448144}} {"text": "function h = hypot3(dx, dy, dz)\n%HYPOT3 Diagonal length of a cuboidal 3D box \n%\n% h = hypot3(a, b, c)\n% computes the quantity sqrt(a^2 + b^2 + c^2), by avoiding roundoff\n% errors.\n%\n% Example\n% % Compute diagonal of unit cube\n% hypot3(1, 1, 1)\n% ans =\n% 1.7321\n%\n% % Compute more complicated diagonal\n% hypot3(3, 4, 5)\n% ans = \n% 7.0711\n% \n% See also\n% hypot, vectorNorm3d\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-04-29, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\nh = hypot(hypot(dx, dy), dz);\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/hypot3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7776537480285907}} {"text": "function M = cross2Matrix(x)\n% CROSS2MATRIX Antisymmetric matrix corresponding to a 3-vector\n%\n% Computes the antisymmetric matrix M corresponding to a 3-vector x such\n% that M*y = cross(x,y) for all 3-vectors y.\n%\n% Input: \n% - x(3,1) : vector\n%\n% Output: \n% - M(3,3) : antisymmetric matrix\n%\n\nM = [0, -x(3), x(2); ...\n x(3), 0, -x(1); ...\n -x(2), x(1), 0 ];\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/triangulation/cross2Matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.77764739595704}} {"text": "function [R] = quat2mat(q)\n % QUAT2MAT convert quaternions to 3d rotation matrices\n %\n % [R] = quat2mat(q)\n %\n % Input:\n % q is an m by 4 list of normalized quaternions, [1 i j k]\n % Output:\n % R is a 3 by 3 by m list of rotation matrices\n %\n % See:\n % http://en.wikipedia.org/wiki/\n % Conversion_between_quaternions_and_Euler_angles#Rotation_matrices\n %\n % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)\n %\n\n assert(size(q,2) == 4);\n\n R = zeros(3,3,size(q,1));\n R(1,1,:) = q(:,1).^2 + q(:,2).^2 - q(:,3).^2 - q(:,4).^2;\n R(1,2,:) = 2*(q(:,2).*q(:,3) - q(:,1).*q(:,4));\n R(1,3,:) = 2*(q(:,1).*q(:,3) + q(:,2).*q(:,4));\n R(2,1,:) = 2*(q(:,2).*q(:,3) + q(:,1).*q(:,4));\n R(2,2,:) = q(:,1).^2 - q(:,2).^2 + q(:,3).^2 - q(:,4).^2;\n R(2,3,:) = 2*(q(:,3).*q(:,4) - q(:,1).*q(:,2));\n R(3,1,:) = 2*(q(:,2).*q(:,4) - q(:,1).*q(:,3));\n R(3,2,:) = 2*(q(:,1).*q(:,2) + q(:,3).*q(:,4));\n R(3,3,:) = q(:,1).^2 - q(:,2).^2 - q(:,3).^2 + q(:,4).^2;\n\n %yy2 = 2.0 .* q(:,2) .* q(:,2);\n %xy2 = 2.0 .* q(:,1) .* q(:,2);\n %xz2 = 2.0 .* q(:,1) .* q(:,3);\n %yz2 = 2.0 .* q(:,2) .* q(:,3);\n %zz2 = 2.0 .* q(:,3) .* q(:,3);\n %wz2 = 2.0 .* q(:,4) .* q(:,3);\n %wy2 = 2.0 .* q(:,4) .* q(:,2);\n %wx2 = 2.0 .* q(:,4) .* q(:,1);\n %xx2 = 2.0 .* q(:,1) .* q(:,1);\n %R(1,1,:) = - yy2 - zz2 + 1;\n %R(1,2,:) = xy2 + wz2;\n %R(1,3,:) = xz2 - wy2;\n %R(2,1,:) = xy2 - wz2;\n %R(2,2,:) = - xx2 - zz2 + 1;\n %R(2,3,:) = yz2 + wx2;\n %R(2,1,:) = xz2 + wy2;\n %R(2,2,:) = yz2 - wx2;\n %R(2,3,:) = - xx2 - yy2 + 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/quat2mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7776473907691753}} {"text": "function prob_test0253 ( )\n\n%*****************************************************************************80\n%\n%% TEST0253 tests BUFFON_PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0253\\n' );\n fprintf ( 1, ' BUFFON_PDF evaluates the Buffon PDF,\\n' );\n fprintf ( 1, ' the probability that, on a grid of cells of width A,\\n' );\n fprintf ( 1, ' a needle of length L, dropped at random,\\n' );\n fprintf ( 1, ' will cross at least one grid line.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A L PDF\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 5\n a = i;\n\n for k = 0 : 5\n l = k * a / 5.0;\n pdf = buffon_pdf ( a, l );\n fprintf ( 1, ' %8.4f %8.4f %14f\\n', a, l, pdf );\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/prob/prob_test0253.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7776394309320048}} {"text": "function epsil = precise_rand(n, delta, logm, shutup)\n% This function computes (almost) precise random coding bound for BSC. The only imprecision is due to \n% union bound.\n% epsil <= sum_k \\delta^k (1-delta)^(n-k) P[one of M-1 other codewords is inside sphere <= k]\n\nKs = 0:n;\nbino_coeffs = (gammaln(n+1) - gammaln(Ks+1) - gammaln(n-Ks+1))/log(2);\nterms_spheres = bino_coeffs + logm - n;\n[tmp log_spheres] = sumlog2(terms_spheres);\n\n% cut off stupid >1 values (this what gallager rho-trick is supposed to do also)\nlog_spheres = min(log_spheres, 0);\n\nterms = bino_coeffs + log2(delta)*Ks + log2(1-delta)*(n-Ks) + log_spheres;\n\nepsil = 2^sumlog2(terms);\n\nif(nargin < 4) || (isempty(shutup))\n\tdisp(sprintf('-- precise_rand(n = %d, delta = %g, logm = %.1f): epsil = %.3g', n, delta, logm, epsil));\nend\n", "meta": {"author": "yp-mit", "repo": "spectre", "sha": "57af76799e4eb43aa707cc13c4c5220d281e0b78", "save_path": "github-repos/MATLAB/yp-mit-spectre", "path": "github-repos/MATLAB/yp-mit-spectre/spectre-57af76799e4eb43aa707cc13c4c5220d281e0b78/bsc/precise_rand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7776166784738592}} {"text": "%% BIHARMONICMIXEDFEM solves the biharmonic equation\n%\n% laplace^2 u = f; [0,1]^2\n% u = g_D; \n% Dn u = g_N. \n%\n% by writing in a mixed form\n% \n% w = Lap u\n% Lap w = f\n%\n% The boundary condition u = g_D is imposed into the space (Dirichlet) and\n% the boundary condition Dn u = g_N is imposed as a Newmann boundary\n% condition. \n%\n% The rate of convergence for u is optimal but for w is sub-optimal. For\n% linear element, optimal order for w is also observed.\n%\n% Created by Jie Zhou. Clean up by Long Chen. Further clean up on\n% biharmonic functions are needed and multigrid solvers should be included.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all\nclear variables;\n\n%% Parameters\nmaxIt = 4; \nN = zeros(maxIt,1); \nh = zeros(maxIt,1);\nerruL2 = zeros(maxIt,1); \nerruH1 = zeros(maxIt,1);\nerrwL2 = zeros(maxIt,1); \nerrwH1 = zeros(maxIt,1);\n\n%% Generate an initial mesh\n[node,elem] = squaremesh([0 1 0 1], 0.25);\nbdFlag = setboundary(node,elem,'Dirichlet'); % Dirichlet boundary condition\n\nfor k = 1:1\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\nend\n\n%% Set up PDE data\npde = biharmonicdata;\n\n%% Finite Element Method \nfor k = 1:maxIt\n % refine mesh\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag); \n [w,u] = biharmonicP1(node,elem,bdFlag,pde);\n% [w,u] = biharmonicP2(node,elem,bdFlag,pde);\n% [w,u] = biharmonicP3(node,elem,bdFlag,pde);\n N(k) = size(w,1)+size(u,1);\n h(k) = 1./(sqrt(size(node,1))-1);\n erruL2(k) = getL2error(node,elem,pde.exactu,u);\n erruH1(k) = getH1error(node,elem,pde.Du,u);\n errwL2(k) = getL2error(node,elem,pde.exactw,w);\n errwH1(k) = getH1error(node,elem,pde.Dw,w);\nend\n \n%% Plot convergence rates and display error table\nfigure;\nsubplot(1,2,1);\nshowrateh2(h,erruH1,1,'-*','|| Du - Du_h||',...\n h,erruL2,1,'k-+','|| u - u_h||');\nsubplot(1,2,2)\nshowrateh2(h,errwH1,1,'c-*','|| Dw - Dw_h||',...\n h,errwL2,1,'m-+','|| w - w_h||'); \n\nfprintf('\\n');\ndisp('Table: Error')\ncolname = {'#Dof','h','||u-u_h||','||Du-Du_h||','||Dw-Dw_h||','||w - w_h||'};\ndisptable(colname,N,[],h,'%0.3e',erruL2,'%0.5e',erruH1,'%0.5e',errwH1,'%0.5e',errwL2,'%0.5e');\n\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/biharmonic/biharmonicMixedFEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7775098752495776}} {"text": "function lebesgue_test07 ( )\n\n%*****************************************************************************80\n%\n%% LEBESGUE_TEST07 looks at Equidistant3 points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEBESGUE_TEST07:\\n' );\n fprintf ( 1, ' Analyze Equidistant3 points.\\n' );\n\n n_max = 11;\n l = zeros ( n_max, 1 );\n xfun = linspace ( -1.0, +1.0, 501 );\n xfun = xfun';\n\n for n = 1 : n_max\n x = equidistant3 ( n );\n l(n) = lebesgue_constant ( n, x, xfun );\n end\n\n r8vec_print ( n_max, l, ' Equidistant3 Lebesgue constants for N = 1 to 11:' )\n%\n% Examine one case more closely.\n%\n n = 11;\n x = equidistant3 ( n );\n r8vec_print ( n, x, ' Equidistant3 points for N = 11' );\n\n label = 'Equidistant3 points for N = 11';\n filename = 'equidistant3.png';\n lebesgue_plot ( n, x, xfun, label, filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot file saved as \"%s\"\\n', filename );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/lebesgue/lebesgue_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.7774170521052163}} {"text": "function c = correlation_damped_cosine ( n, rho, rho0 )\n\n%*****************************************************************************80\n%\n%% CORRELATION_DAMPED_COSINE evaluates the damped cosine correlation function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 March 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, integer N, the number of arguments.\n%\n% Input, real RHO(N,1), the arguments.\n%\n% Input, real RHO0, the correlation length.\n%\n% Output, real C(N,1), the correlations.\n%\n rho = rho ( : );\n\n rhohat = abs ( rho ) / rho0;\n\n c = exp ( - rhohat ) .* cos ( rhohat );\n\n return\nend\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/correlation/correlation_damped_cosine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.868826769445233, "lm_q1q2_score": 0.7774170484803123}} {"text": "[dummy,T] = lu(rand(5));\nb = rand(5,1);\n%fprintf('The columns should be equal:\\n');\nr = [solve_triu(T,b) T\\b];\nassert(all(abs(r(:,1) - r(:,2)) < 1e-10))\nr = [solve_tril(T',b) T'\\b];\nassert(all(abs(r(:,1) - r(:,2)) < 1e-10))\nfprintf('Verified that solve_triu and solve_tril results match backslash.\\n');\n\nd = 100;\nniter = (20000/d)^2;\nA = rand(d);\n[dummy,T] = lu(A);\nb = rand(d,1);\ntic; for i = 1:niter T\\b; end; t1=toc/niter;\ntic; for i = 1:niter solve_triu(T,b); end; t2=toc/niter;\nfprintf('backslash: \\t%g\\nsolve_triu: \\t%g (%g times faster)\\n',t1,t2,t1/t2);\n% backslash is detecting triangularity as a preprocessing step, which doubles\n% the time.\n%fprintf('by flops, should be %g times faster\\n',...\n% flops_solve(T,b)/flops_solve_tri(T,b));\n\nniter = ceil(niter/d);\ntic; for i = 1:niter inv(T); end; t1=toc/niter;\n%I = eye(size(T));\n%tic; for i = 1:niter solve_triu(T,I); end; t2=toc;\ntic; for i = 1:niter inv_triu(T); end; t2=toc/niter;\nfprintf('inv: \\t%g\\ninv_triu: \\t%g (%g times faster)\\n',t1,t2,t1/t2);\nfprintf('by flops, should be %g times faster\\n',...\n flops_inv(rows(T))/flops_solve_tri(T,eye(size(T))));\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/lightspeed/tests/test_solve_tri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.77740675094941}} {"text": "J = 5; % J: number of stages\n\n% get filters\n[Faf, Fsf] = FSfarras;\n[af, sf] = dualfilt1;\n\nx = zeros(1,256); % zero signal\n\n% Compute dual-tree complex DWT of zero signal\nw = dualtree(x, J, Faf, af); \n% Set a single (real) coefficient to 1\nw{5}{1}(4) = 1;\n% Compute the inverse transform \ny1 = idualtree(w, J, Fsf, sf);\n\n% Compute dual-tree complex DWT of zero signal\nw = dualtree(x, J, Faf, af); \n% Set a single (imaginary) coefficient to 1\nw{5}{2}(4) = 1;\n% Compute the inverse transform \ny2 = idualtree(w, J, Fsf, sf);\n\n% Display real and imaginary parts and magnitude\nn = [1:256]/256;\nplot(n,y1,n,y2,n,sqrt(y1.^2+y2.^2))\ntitle('COMPLEX 1D WAVELET') \nxlabel('t');\nylabel('\\psi(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/DTCWT/dualtree_eg1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7773855821089036}} {"text": "function z = piecewise_eval(x,breakpoints,funs)\n% PIECEWISE_EVAL: evaluates a piecewise function of x\n% usage: y = PIECEWISE_EVAL(x,breakpoints,funs)\n%\n% arguments (input)\n% x - vector or array of points to evaluate though the function\n% \n% breakpoints - list of n breakpoints, -inf and +inf are implicitly\n% the first and last breakpoints. A function with only two\n% pieces has only one explicit breakpoint. In the event that\n% you want to define a function with breakpoints [a,b,c],\n% and only two functions, but you do not care what happens\n% for x < a or x > b, then you should specify only the\n% breakpoint b. Alternatively, one could specify all 3\n% breaks, and force the function to return NaN above and\n% below those limits.\n%\n% x(i) will be identified as falling in interval (j) if\n% break(j) <= x(i) < break(j+1)\n% \n% funs - cell array containing n+1 functions as scalar constants,\n% strings, anonymous functions, inline functions, or any\n% simple matlab function name.\n%\n% Note: use .*, ./, .^ where appropriate in the function\n%\n% These functions need not be differentiable or even\n% continuous across the breaks.\n%\n% arguments (output)\n% z - evaluated function, result is same shape as x\n%\n% Example usage:\n% For x < -5, y = 2\n% For -5 <= x < 0, y = sin(x)\n% For 0 <= x < 2, y = x.^2\n% For 2 <= x < 3, y = 6\n% For 3 <= x, y = inf\n%\n% y = piecewise_eval(-10:10,[-5 0 2 3],{2,'sin(x)','x.^2',6,inf})\n\nn=length(breakpoints);\n% there must be n+1 funs for n breaks\nif length(funs)~=(n+1)\n error 'funs and breakpoints are incompatible in size'\nend\n\nif any(diff(breakpoints)<=0)\n error 'Breakpoints must be both distinct and increasing'\nend\n\n% ensure the functions are feval-able\nfor i=1:(n+1)\n if ischar(funs{i})\n % A string. Make it a function\n f=inline(funs{i});\n funs{i} = f;\n elseif isa(funs{i},'function_handle') || isa(funs{i},'inline')\n % a function handle or an inline. do nothing.\n elseif isnumeric(funs{i}) | isnan(funs{i}) | isinf(funs{i})\n % A scalar value was supplied, may be NaN or inf.\n % Make it a function.\n funs{i}=@(x) funs{i};\n else\n % It must be something that feval can handle\n % directly, so leave funs{i} alone.\n end\nend\n\n% initialize as nans\nz=nan(size(x));\n\n% below the first break\nk=(x=breakpoints(end));\nz(k)=feval(funs{end},x(k));\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/9394-piecewise-functions/piecewise_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7772002823836442}} {"text": "function x = spgridm(levelseq)\n% SPGRIDM Compute grid points, maximum-norm-based grid\n% X = SPGRIDM(LEVELSEQ,D) Computes the sparse grid points for\n% the given sequence of index LEVELSEQ and problem dimension D. \n% The coordinate value of dimension i is stored in column i of\n% the matrix X. One row of matrix X represents one grid point.\n% (Internal function)\n\n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.2\n% Date : January 24, 2006\n\t\n% Change log:\n% V1.0 : Sep 24, 2003\n% V1.1 : April 21, 2004\n% Altered function header to enable dimension-adaptive\n% grids. Simplified code.\n% V1.2 : January 24, 2006\n% Changed data types to operate on uint arrays\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\n% Get the number of levels\nnlevels = uint32(size(levelseq,1));\n\n% Get the dimension\nd = uint16(size(levelseq,2));\n\nnpoints = zeros(nlevels,1,'uint32');\n\n% Initialize sp with the total number of grid points of the\n% level.\n% Compute number of points\ntotalpoints = uint32(0);\nfor k = 1:nlevels;\n\tntemp = uint32(1);\n\tfor l = 1:d\n\t\tlev = levelseq(k,l);\n\t\tif lev == 0\n\t\t\tntemp = ntemp * 3;\n\t\telse\n\t\t\tntemp = ntemp * 2^uint32(lev);\n\t\tend\n\tend\n\tnpoints(k) = ntemp;\n\ttotalpoints = totalpoints + ntemp;\nend\n\t\n% index contains the index of the resulting array containing all\n% subdomains of the level.\nindex = uint32(1);\n\t\nx = zeros(totalpoints,d);\n\t\nfor kl = 1:nlevels\n\tlevel = double(levelseq(kl,:));\n\tfor i = 1:d\n\t\t% compute the points, scaled to [0,1]\n\t\tif level(i) == 0\n\t\t\tc = [0; 0.5; 1];\n\t\telse\n\t\t\tc = (((1:2:(2^level(i).*2))).*2^(-1-level(i)))';\n\t\tend\n\n\t\t% Compute the number of grid points per dimension, store it\n\t\t% in repvec. The funny (level == 0) statement makes sure that\n\t\t% each level 0 dimension is counted as three.\n\t\trepvec = [2.^level+(level == 0).*2]';\n\t\tnpoints = prod(repvec);\n\t\trepvec(i) = 1;\n\t\tc = repmat(shiftdim(c, 1-double(i)), repvec);\n\t\tx(index:index+npoints-1,i) = c(:);\n\tend\n\tindex = index + npoints;\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spinterp/private/spgridm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7771291762554524}} {"text": "function [val,retData]=unbiasedMomentCumulant(x,r,isMoment,algorithm,retData)\n%%UNBIASEDMOMENTCUMULANT Given a set of samples of a scalar distribution,\n% return an unbiased estimate of the rth order central moment (h\n% statistic), which is E{(x-mu)^r}, where E is the expected value\n% operation, when given only samples of x and not knowing the\n% mean mu. Alternatively, one could compute an unbiased estimate\n% of the rth order cumulant (k statistic). Note that for r=0, if\n% a moment is desired, then the mean is returned, rather than\n% returning 0. If r is a vector, one can estimate generalized h\n% statistics, which are an estimate of\n% E{(x-mu)^r(1)}*E{(x-mu)^r(2)}*...*E{(x-mu)^r(v)} However,\n% algorithm 2 is used for generalized h statistics and its\n% complexity increases rapidly with the number of samples.\n%\n%INPUTS: x A 1XN or NX1 array of scalar samples of the distribution.\n% r The scalar order of the cumulant or of the central moment.\n% Alternatively, if this is a vector, then one will get a\n% generalized h statistic, and in that instance, algorithm 2 is\n% required.\n% isMoment A parameter selecting whether a moment or a cumulant is desired.\n% The default if omitted or an empty matrix is passed is true,\n% indicating that a central moment is desired.\n% algorithm An optional parameter selecting which algorithm to use.\n% possible values are:\n% 0 Use an explicit solution with precomputed coefficients. These\n% are only available for scalar r=1,...,5. The explicit\n% solutions use the parameters in Table I of [1]. This is the\n% default if r<=5 is scalar.\n% 1 Use Dwyer's method in [1] to determine the coefficients of the\n% expression of the moment in terms of the sample power sums\n% sum(x^k) for k=1 to r.\n% 2 Use the symmetric function based algorithm of [2]. This\n% algorithm can only estimate central moments, not cumulants. \n% The complexity of this algorithm increases rapidly with N.\n% This can be used with a vector r and is thus the default when\n% r is a vector.\n% retData If algorithm=1 is used, then the retData value is returned. If\n% one calls this function passing back retData and keeps all other\n% inputs the same except replacing x with a different set of\n% samples, then the function will execute faster. One should not\n% pass back retData if any inputs other than x have changed.\n%\n%OUTPUTS: val The scalar value of the moment.\n% retData If algorithm=1, then this is a structure that can be passed\n% back so that if the function is called a second time with the same\n% inputs, changing only x to different samples, then the algorithm will\n% be faster.\n%\n%When mu is not available and must be found from the samples, as is the\n%case here, then the average mean((x-mean(x)).^p) to approximate\n%E{(x-mu)^p} is a biased estimator. Hence, h statistics are more\n%complicated.\n%\n%EXAMPLE 1:\n%Here, we estimate the sixth central moment of the scalar Laplace\n%distribution from 1000 samples. Since the distribution is symmetric and\n%unbounded, we can assume that if the estimator is unbiased, the averaging\n%a large number of these estimates will approach the true moment value.\n%That is done here and compared to the true moment value. One can also see\n%how retData is used to speed up the algorithm.\n% n=1000;\n% lambda=0.1;\n% mu=2;\n% Gamma=1;\n% momentNum=6;\n% numRuns=1e4;\n% \n% hAvg=0;\n% retData=[];\n% for curRun=1:numRuns\n% x=LaplaceD.rand(n,lambda,mu,Gamma);\n% [val,retData]=unbiasedMomentCumulant(x,momentNum,true,[],retData);\n% hAvg=hAvg+val;\n% end\n% avgMomentEst=hAvg/numRuns\n% muList=zeros(momentNum,1);\n% for k=1:momentNum\n% muList(k)=LaplaceD.momentGenFun(lambda,mu,Gamma,k);\n% end\n% centralMoment=raw2CentralMoments(muList);\n% trueMoment=centralMoment(end)\n%One should see that the average moment and the true moment should agree to\n%a few decimal places.\n%\n%EXAMPLE 2:\n%Now, we estimate the product of the second central moment and the fourth\n%central moment. This necessitates the use of algorith 2, which can be\n%rather slow. This example will typically take a few seconds to run.\n% rng(0);%To make the results reproducible\n% n=10;\n% lambda=0.25;\n% mu=2;\n% Gamma=1;\n% p=[2,4];\n% numRuns=1000;\n% \n% hAvg=0;\n% for curRun=1:numRuns\n% x=LaplaceD.rand(n,lambda,mu,Gamma);\n% hAvg=hAvg+unbiasedMomentCumulant(x,p);\n% end\n% avgMomentEst=hAvg/numRuns\n% muList=zeros(max(p),1);\n% for k=1:max(p)\n% muList(k)=LaplaceD.momentGenFun(lambda,mu,Gamma,k);\n% end\n% centralMoment=raw2CentralMoments(muList);\n% trueMoment=prod(centralMoment(p))\n%The average moment estimate will be about 0.0998 and the true moment will\n%be about 0.0938.\n%\n%REFERENCES:\n%[1] P. S. Dwyer, \"Moments of any rational integral isobaric sample moment\n% function,\" The Annals of Mathematical Statistics, vol. 8, no. 1, pp.\n% 21-65, Mar. 1937.\n%[2] D. S. Tracy and B. C. Gupta, \"Generalized h-statistics and other\n% symmetric functions,\" The Annals of Statistics, vol. 2, no. 4, pp. \n% 837-844, 1974.\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<3||isempty(isMoment))\n isMoment=true;\nend\n\nif(nargin<4||isempty(algorithm))\n if(isscalar(r))\n if(r<=5)\n algorithm=0;%Use the explicit solution.\n else\n algorithm=1;%Use the power sum solution of Dwyer.\n end\n else\n algorithm=2;\n \n if(isMoment==false)\n error('Vector values of r are not allowed for algorithm~=2.')\n end\n end\nend\n\nif(nargin<5)\n retData=[];\nend\n\nif(isMoment)%h-statistics\n switch(algorithm)\n case 0\n val=hStatExplicit(x,r);\n retData=[];\n case 1\n [val,retData]=momCumDwyer(x,r,false,retData);\n case 2\n val=genHStat(x,r);\n \n retData=[];\n otherwise\n error('Unknown Algorithm specified.')\n end\nelse%k-statistics\n switch(algorithm)\n case 0\n val=kStatExplicit(x,r);\n retData=[];\n case 1\n [val,retData]=momCumDwyer(x,r,true,retData);\n otherwise\n error('Unknown Algorithm specified.')\n end\nend\nend\n\nfunction [momentVal,retData]=momCumDwyer(x,r1,isCumulant,retData)\n%%MOMCUMDWYER Compute unbiased central moments (h statistics) or cumulants\n% (k statistics) using Dwyer's algorithm, described in [1]. The\n% definition of the symmetric powers in the algorithm can be\n% bettwer understood when considering [2].\n%\n%The algorithm uses a weird definition of a product, which involves\n%appending the indices of various \"b\" variables on each other. Thus, an\n%initial phase of the algorithm involves just determinign the indices of\n%the necessary coefficients. Sections 17 and 18 of [1] give the b variables\n%for k statistics and h statistics. Section 16 discusses how to turn the b\n%variables into a variables. The expression for turning the a variables\n%into moments, F_r, is in Section 1.\n%\n%REFERENCES:\n%[1] P. S. Dwyer, \"Moments of any rational integral isobaric sample moment\n% function,\" The Annals of Mathematical Statistics, vol. 8, no. 1, pp.\n% 21-65, Mar. 1937.\n%[2] P. S. Dwyer, \"Combined expansions of products of symmetric power sums\n% and of sums of symmetric power products with application to sampling,\"\n% The Annals of Mathematical Statistics, vol. 9, no. 1, pp. 1-47, Mar.\n% 1938.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nn=length(x);\n\nnumParts=numberOfPartitions(r1,true);\n\nif(nargin<4||isempty(retData))\n %If we have to compute the coefficients.\n %AParts holds the indices of the b that go into the sum to form the a as\n %well as their coefficients.\n aParts=cell(r1,2);\n for r=1:r1\n %Allocate space for the indices of the b values needed and their\n %coefficients.\n bIdx=cell(numParts(r+1),1);\n bCoeff=zeros(numParts(r+1),1);\n [thePartition,theData]=getNextPartition(r);\n curB=1;\n while(~isempty(thePartition))\n s=theData.d;\n p=theData.r(1:s);\n piVals=theData.m(1:s);\n rho=sum(piVals);\n\n [p,idx]=sort(p,'descend');\n piVals=piVals(idx);\n\n bCoeff(curB)=partComboNum(r,p,piVals)*(-1)^(rho-1)*factorial(rho-1);\n idx=zeros(rho,1);\n startIdx=1;\n for k=1:s\n numRep=piVals(k);\n sel=startIdx:(startIdx+numRep-1);\n idx(sel)=p(k);\n startIdx=startIdx+numRep;\n end\n bIdx{curB}=idx;\n\n [thePartition,theData]=getNextPartition(r,theData);\n curB=curB+1;\n end\n aParts{r,1}=bIdx;\n aParts{r,2}=bCoeff;\n end\n\n %Now, determine the b indices needed to construct the sum in terms of the\n %as. (The Fr equation).\n aPartNeeded=cell(r1,3);\n %This stores the a indices, the coefficient of the a term and the powers of\n %the P sums for each a term.\n [thePartition,theData]=getNextPartition(r1);\n curA=1;\n while(~isempty(thePartition))\n s=theData.d;\n p=theData.r(1:s);\n piVals=theData.m(1:s);\n rho=sum(piVals);\n\n [p,idx]=sort(p,'descend');\n piVals=piVals(idx);\n coeffVal=partComboNum(r1,p,piVals);\n\n idx=zeros(rho,1);\n startIdx=1;\n for k=1:s\n numRep=piVals(k);\n sel=startIdx:(startIdx+numRep-1);\n idx(sel)=p(k);\n startIdx=startIdx+numRep;\n end\n\n aPartNeeded{curA,1}=idx;\n aPartNeeded{curA,2}=coeffVal;\n aPartNeeded{curA,3}=piVals(:);\n aPartNeeded{curA,4}=p(:);\n\n [thePartition,theData]=getNextPartition(r1,theData);\n curA=curA+1;\n end\n\n %To build each of the required \"a\" terms with the parts needed from the\n %single index a terms.\n numCoeffs=curA-1;\n %Allocate space for the a coefficients. These must be built from the suffix\n %multiplication rule of Section 16.\n aCoeffs=zeros(numCoeffs,1);\n for curPart=1:numCoeffs\n idx=aPartNeeded{curPart,1};\n r=length(idx);\n\n bIdxList=aParts{idx(1),1};\n bCoeffList=aParts{idx(1),2};\n for k=2:r\n bIdxCur=aParts{idx(k),1};\n bCoeffCur=aParts{idx(k),2};\n numB=length(bIdxList);\n numCur=length(bIdxCur);\n\n bIdxListNew=cell(numB*numCur,1);\n bCoeffListNew=zeros(numB*numCur,1);\n newCur=1;\n for i1=1:numB\n for i2=1:numCur\n bIdxListNew{newCur}=[bIdxList{i1};bIdxCur{i2}];\n bCoeffListNew(newCur)=bCoeffList(i1)*bCoeffCur(i2);\n\n newCur=newCur+1;\n end\n end\n bIdxList=bIdxListNew;\n bCoeffList=bCoeffListNew;\n end\n\n %We now have the b indices and coefficients to construct the a\n %coefficients once we compute the b values.\n numB=length(bIdxList);\n aSum=0;\n for curB=1:numB\n bIdx=bIdxList{curB};\n bCoeff=bCoeffList(curB);\n\n numBIdx=length(bIdx);\n s=numBIdx;\n\n bIdx=sort(bIdx,'descend');\n p=zeros(s,1);\n piVals=zeros(s,1);\n\n p(1)=bIdx(1);\n numUnique=1;\n piVals(1)=1;\n for curIdx=2:numBIdx\n if(bIdx(curIdx)==bIdx(curIdx-1))\n s=s-1;\n piVals(numUnique)=piVals(numUnique)+1;\n else\n numUnique=numUnique+1;\n p(numUnique)=bIdx(curIdx);\n piVals(numUnique)=1;\n end\n end\n %Note that s==numUnique.\n piVals=piVals(1:s);\n p=p(1:s);\n rho=sum(piVals);\n\n if(isCumulant)%For Fisher k statistics\n b=(-1)^(rho-1)*factorial(rho-1)/fallingFactorial(n,rho);\n else%For h statistics\n if(s==1&&piVals(1)==1&&p(1)==r1)\n AVal=1;\n elseif(p(1)>1&&piVals(1)==1&&s==2&&p(2)==1)\n AVal=(-1)^piVals(2);\n elseif(p(1)==1&&s==1&&piVals(1)==r1)\n AVal=(-1)^(r1-1)*(r1-1);\n else\n AVal=0;\n end\n b=AVal/fallingFactorial(n,rho);\n end\n\n aSum=aSum+bCoeff*b;\n end\n\n aCoeffs(curPart)=aSum;\n end\n\n retData.aPartNeeded=aPartNeeded;\n retData.aCoeffs=aCoeffs;\nelse\n aPartNeeded=retData.aPartNeeded;\n aCoeffs=retData.aCoeffs;\n numCoeffs=length(aCoeffs);\nend\n\n%We have all of the coefficients. To get this moment with a generic length\n%n set of data, we just need the power sums up to degree r.\nP=zeros(r1,1);\nfor k=1:r1\n P(k)=sum(x.^k);\nend\n\nmomentVal=0;\nfor curA=1:numCoeffs\n aCur=aCoeffs(curA);\n coeff=aPartNeeded{curA,2};\n piVals=aPartNeeded{curA,3};\n idx=aPartNeeded{curA,4};\n\n momentVal=momentVal+coeff*aCur*prod(P(idx).^piVals);\nend\n\nend\n\nfunction val=partComboNum(r,p,piVals)\n%%PARTCOMBONUM The expression for this multinomial value is given on page\n% 23 of [1].\n%\n%REFERENCES:\n%[1] P. S. Dwyer, \"Moments of any rational integral isobaric sample moment\n% function,\" The Annals of Mathematical Statistics, vol. 8, no. 1, pp.\n% 21-65, Mar. 1937.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n %For large r, use this form to help reduce overflow.\n val=exp(gammaln(r+1)-sum(piVals.*gammaln(p+1))-sum(gammaln(piVals+1)));\nend\n\nfunction val=hStatExplicit(x,r)\n%%HSTATEXPLICIT This implements the explicit h statistics of orders 1 to 5\n% that are given in the table I of [1] using the formula for\n% Fr given in Section 1 of [1]. h statistics are unbiased\n% estimates of the moment about the mean.\n%\n%INPUTS: x A 1XN or NX1 array of scalar samples of the distribution.\n% r The order of the moment. 1<=r<=5.\n%\n%OUTPUT: val The rth order h statistic. This is a scalar value.\n%\n%REFERENCES:\n%[1] P. S. Dwyer, \"Moments of any rational integral isobaric sample moment\n% function,\" The Annals of Mathematical Statistics, vol. 8, no. 1, pp.\n% 21-65, Mar. 1937.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nn=length(x);\nswitch(r)\n case 1\n a1=1/n;\n \n P1=sum(x);\n val=a1*P1;\n case 2\n a2=1/(n-1);\n a11=-1/(n*(n-1));\n \n P1=sum(x);\n P2=sum(x.^2);\n \n val=a2*P2+a11*P1^2;\n case 3\n a3=n/((n-1)*(n-2));\n a21=-1/((n-1)*(n-2));\n c21=3;\n a111=2/(n*(n-1)*(n-2));\n \n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n \n val=a3*P3+c21*a21*P1*P2+a111*P1^3;\n case 4\n n13=(n-1)*(n-2)*(n-3);\n n4=n*n13;\n \n a4=(n^2-2*n+3)/n13;\n a31=-(n^2-2*n+3)/n4;\n c31=4;\n a22=-(2*n-3)/n4;\n c22=3;\n a211=1/n13;\n c211=6;\n a1111=-3/n4;\n \n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n P4=sum(x.^4);\n \n val=a4*P4+c31*a31*P3*P1+c22*a22*P2^2+c211*a211*P2*P1^2+a1111*P1^4;\n case 5\n n14=(n-1)*(n-2)*(n-3)*(n-4);\n n5=n*n14;\n \n a5=n*(n^2-5*n+10)/n14;\n a41=-(n^2-5*n+10)/n14;\n c41=5;\n a32=-(n-2)/n14;\n c32=10;\n a311=(n^2-4*n+8)/n5;\n c311=10;\n a221=(2*n-4)/n5;\n c221=15;\n a2111=-1/n14;\n c2111=10;\n a11111=4/n5;\n \n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n P4=sum(x.^4);\n P5=sum(x.^5);\n val=P5*a5+c41*a41*P4*P1+c32*a32*P3*P2+c311*a311*P3*P1^2+c221*a221*P2^2*P1+c2111*a2111*P2*P1^3+a11111*P1^5; \n otherwise\n error('The explicit solutions are only available up to order 5.');\nend\nend\n\nfunction val=kStatExplicit(x,r)\n%%KSTATEXPLICIT This implements the explicit Fisher k statistics of orders\n% 1 to 5 that are given in the table I of [1] using the\n% formula for Fr given in Section 1 of [1]. h statistics are\n% unbiased estimates of the cumulants of the distribution. Up\n% to order 3, they are the same as the h statistics.\n%\n%INPUTS: x A 1XN or NX1 array of scalar samples of the distribution.\n% r The order of the moment. 1<=r<=5.\n%\n%OUTPUT: val The rth order h statistic. This is a scalar value.\n%\n%REFERENCES:\n%[1] P. S. Dwyer, \"Moments of any rational integral isobaric sample moment\n% function,\" The Annals of Mathematical Statistics, vol. 8, no. 1, pp.\n% 21-65, Mar. 1937.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nn=length(x);\nswitch(r)\n case 1\n a1=1/n;\n \n P1=sum(x);\n val=a1*P1;\n case 2\n a2=1/(n-1);\n a11=-1/(n*(n-1));\n \n P1=sum(x);\n P2=sum(x.^2);\n \n val=a2*P2+a11*P1^2;\n case 3\n a3=n/((n-1)*(n-2));\n a21=-1/((n-1)*(n-2));\n c21=3;\n a111=2/(n*(n-1)*(n-2));\n \n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n \n val=a3*P3+c21*a21*P1*P2+a111*P1^3;\n case 4\n n22=(n-2)*(n-3);\n n13=(n-1)*n22;\n n4=n*n13;\n \n a4=n*(n+1)/n13;\n a31=-(n+1)/n13;\n c31=4;\n a22=-1/n22;\n c22=3;\n a211=2/n13;\n c211=6;\n a1111=-6/n4;\n \n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n P4=sum(x.^4);\n \n val=a4*P4+c31*a31*P3*P1+c22*a22*P2^2+c211*a211*P2*P1^2+a1111*P1^4;\n case 5\n n14=(n-1)*(n-2)*(n-3)*(n-4);\n n5=n*n14;\n \n a5=n^2*(n+5)/n14;\n a41=-n*(n+5)/n14;\n c41=5;\n a32=-n*(n-1)/n14;\n c32=10;\n a311=2*(n+2)/n14;\n c311=10;\n a221=2*(n-1)/n14;\n c221=15;\n a2111=-6/n14;\n c2111=10;\n a11111=24/n5;\n\n P1=sum(x);\n P2=sum(x.^2);\n P3=sum(x.^3);\n P4=sum(x.^4);\n P5=sum(x.^5);\n val=P5*a5+c41*a41*P4*P1+c32*a32*P3*P2+c311*a311*P3*P1^2+c221*a221*P2^2*P1+c2111*a2111*P2*P1^3+a11111*P1^5; \n otherwise\n error('The explicit solutions are only available up to order 5.');\nend\nend\n\nfunction h=genHStat(x,p)\n%%GENHSTAT Given a set of scalar samples, obtain an unbiased estimate of\n% the pth central sample moment. That is, estimate E{(x-mu)^p},\n% where E is the expected value operation and mu is the mean of\n% the distribution. Alternatively, p can be a length-v vector, and\n% an unbiased estimate of\n% E{(x-mu)^p(1)}*E{(x-mu)^p(2)}*...*E{(x-mu)^p(v)} is obtained.\n% When mu is not available and must be found from the samples, as\n% is the case here, then the average mean((x-mean(x)).^p) is a\n% biased estimator. Additionally multiplying unbiased estimators\n% can lead to a biased estimator. The unbiased estimator for this\n% type of problem when p is a scalar is called an h-statistic and\n% when p is a vector is a generalized statistic.\n%\n%INPUTS: x An nX1 or 1Xn vector of real samples. Note that this function\n% can be slow for values of p>4 when a large number of samples is\n% used. \n% p The integer moment desired. p>=1. p can be a vector of all\n% unique elements if the product of central moments should be\n% estimated.\n%\n%OUTPUTS: h The unbiased estimate of the pth central moment given the\n% samples.\n%\n%The estimator of [1], which is an h-statistic, is rather complicated. An\n%explicit expression for h-statistics in terms of symmetric means is given\n%in [2], and an expression for generalized h statististics in terms of\n%symmetric means is also provided. These are how this function is\n%implemented. Equation 2.2 is used when p is a scalar (a central moment)\n%and Equation 3.3 is used when p is a vector (a product of central\n%moments). Note that the evaluation of symmetric means involves the\n%evaluation of matrix permanents and thus the complexity scales\n%exponentialy with the number of samples in x. Only small numbers of\n%samples can be used, because the computational complexity increases too\n%rapidly.\n%\n%REFERENCES:\n%[1] P. R. Halmos, \"The theory of unbiased estimation,\" The Annals of\n% Mathematical Statistics, vol. 17, no. 1, pp. 34-43, Mar. 1946.\n%[2] D. S. Tracy and B. C. Gupta, \"Generalized h-statistics and other\n% symmetric functions,\" The Annals of Statistics, vol. 2, no. 4, pp. \n% 837-844, 1974.\n%\n%September 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=length(x);\n\nif(any(p>=n))\n error('p must be >=n for an unbiased estimator to exist.')\nend\n\nif(isscalar(p))\n if(p==1)%Return the mean instead of 0.\n h=mean(x);\n return\n end\n \n h=0;\n for r=0:p\n h=h+(-1)^r*binomial(p,r)*symmetricMean(x,[p-r,ones(1,r)]);\n end\nelse\n v=length(p);\n \n p=p(:)';\n h=0;\n \n r=zeros(1,v);\n while(~isempty(r))\n sumR=sum(r);\n \n prodVal=1;\n for k=1:v\n prodVal=prodVal*binomial(p(k),r(k)); \n end\n\n %We want p-r without the zero elements.\n pV=p-r;\n pV(pV==0)=[];\n\n h=h+(-1)^sumR*prodVal*symmetricMean(x,[pV,ones(1,sumR)]);\n\n r=getNextTuple(r,p);\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/unbiasedMomentCumulant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7770499015286111}} {"text": "function [nfft,tableout]=floor23(n)\n%FLOOR23 Previous number with only 2,3 factors\n% Usage: nceil=floor23(n);\n%\n% `floor23(n)` returns the first number less than or equal to *n*,\n% which can be written as a product of powers of *2* and *3*.\n%\n% The algorithm will look up the best size in a table, which is computed\n% the first time the function is run. If the input size is larger than the\n% largest value in the table, the input size will be reduced by factors of\n% *2*, until it is in range.\n%\n% `[nceil,table]=floor23(n)` additionally returns the table used for lookup.\n%\n% Examples:\n% ---------\n%\n% Return the first number smaller or equal to *26* that can be written\n% solely as products of powers of *2* and *3*:::\n% \n% floor23(26)\n%\n% This plot shows the behaviour of |floor23| and |ceil23| for numbers\n% up to 100:::\n%\n% x=1:100;\n% plot(x,floor23(x),x,ceil23(x));\n% legend('floor23','ceil23','Location','Northwest');\n%\n% See also: ceil23, floor235, nextfastfft\n \n% AUTHOR: Peter L. Søndergaard\n \n \npersistent table;\n \nmaxval=2^20;\n\nif isempty(table)\n % Compute the table for the first time, it is empty.\n l2=log(2);\n l3=log(3);\n l5=log(5);\n lmaxval=log(maxval);\n table=zeros(143,1);\n ii=1;\n prod2=1;\n for i2=0:floor(lmaxval/l2)\n prod3=prod2;\n for i3=0:floor((lmaxval-i2*l2)/l3) \n table(ii)=prod3; \n prod3=prod3*3;\n ii=ii+1;\n end;\n prod2=prod2*2; \n end;\n table=sort(table);\nend;\n\n% Copy input to output. This allows us to efficiently work in-place.\nnfft=n;\n\n% Handle input of any shape by Fortran indexing.\nfor ii=1:numel(n)\n n2reduce=0;\n \n if n(ii)>maxval\n % Reduce by factors of 2 to get below maxval\n n2reduce=ceil(log2(nfft(ii)/maxval));\n nfft(ii)=nfft(ii)/2^n2reduce;\n end;\n \n % Use a simple bisection method to find the answer in the table.\n from=1;\n to=numel(table);\n while from<=to\n mid = round((from + to)/2); \n diff = table(mid)-nfft(ii);\n if diff<0\n from=mid+1;\n else\n to=mid-1; \n end\n end\n if nfft(ii)~=table(from)\n nfft(ii)=table(from-1);\n end;\n \n % Add back the missing factors of 2 (if any)\n nfft(ii)=nfft(ii)*2^n2reduce;\n \nend;\n\ntableout=table;\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/floor23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7770391402040805}} {"text": "function pn = line_par_point_near_2d ( f, g, x0, y0, p )\n\n%*****************************************************************************80\n%\n%% LINE_PAR_POINT_NEAR_2D: nearest point on parametric line to given point, 2D.\n%\n% Discussion:\n%\n% The parametric form of a line in 2D is:\n%\n% X = X0 + F * T\n% Y = Y0 + G * T\n%\n% We may normalize by choosing F*F + G*G = 1, and F nonnegative.\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% Reference:\n%\n% Adrian Bowyer, John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983,\n% ISBN: 0408012420.\n%\n% Parameters:\n%\n% Input, real F, G, X0, Y0, the parametric line parameters.\n%\n% Input, real P(2,1), the point whose distance from the line is\n% to be measured.\n%\n% Output, real PN(2,1), the point on the parametric line which\n% is nearest to P.\n%\n t = ( f * ( p(1) - x0 ) + g * ( p(2) - y0 ) ) / ( f * f + g * g );\n\n pn(1,1) = x0 + t * f;\n pn(2,1) = y0 + t * g;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/line_par_point_near_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381604, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7770380399987932}} {"text": "function h=window(N,type, varargin)\n\n% window\n%\n% h=window(N,type, varargin)\n% \n% Generate window of length N (in samples)\n% \n% \n% Possible types are :\n% 'Hamming', 'Hanning', 'Nuttall', 'Papoulis', 'Harris',\n% 'Rect', 'Triang', 'Bartlett', 'BartHann', 'Blackman'\n% 'Gauss', 'Parzen', 'Kaiser', 'Dolph', 'Hanna'.\n% 'Nutbess', 'spline'\n% \n% For the gaussian window, an optionnal parameter K\n% sets the value at both extremities. The default value is 0.005\n% \n% For the Kaiser-Bessel window, an optionnal parameter\n% sets the scale. The default value is 3*pi.\n% \n% For the Spline windows, h=window(N,'spline',nfreq,p)\n% yields a spline weighting function of order p and frequency\n% bandwidth proportional to nfreq.\n% \n% Example : w=window(256,'Gauss',0.005); \n\n\nif nargin < 1\n\thelp(mfilename); \n\treturn\nend\n\nif N<=0\n\terror('N should be strictly positive.');\nend\n\nif nargin < 2\n\ttype= 'Hamming';\nend\n\ntype=upper(type);\n\nswitch(type)\n\tcase {'RECTANG','RECT'}\n\t \th=ones(N,1);\n\tcase 'HAMMING'\n\t\th=0.54 - 0.46*cos(2.0*pi*(1:N)'/(N+1));\n\tcase {'HANNING', 'HANN'}\n\t\th=0.50 - 0.50*cos(2.0*pi*(1:N)'/(N+1));\n\tcase 'KAISER'\n\t\tif (nargin==3), beta=varargin{1}; else beta=3.0*pi; end;\n\t\tind=(-(N-1)/2:(N-1)/2)' *2/N; beta=3.0*pi;\n\t\th=bessel(0,j*beta*sqrt(1.0-ind.^2))/real(bessel(0,j*beta));\n\tcase 'NUTTALL',\n\t\tind=(-(N-1)/2:(N-1)/2)' *2.0*pi/N;\n\t\th=+0.3635819 ...\n\t\t+0.4891775*cos( ind) ...\n\t\t+0.1363995*cos(2.0*ind) ...\n\t\t+0.0106411*cos(3.0*ind) ;\n\tcase 'BLACKMAN'\n\t\tind=(-(N-1)/2:(N-1)/2)' *2.0*pi/N;\n\t\th= +0.42 + 0.50*cos(ind) + 0.08*cos(2.0*ind) ;\n\tcase 'HARRIS'\n\t\tind=(1:N)' *2.0*pi/(N+1);\n\t\th=+0.35875 ...\n\t\t-0.48829 *cos( ind) ...\n\t\t+0.14128 *cos(2.0*ind) ...\n\t\t-0.01168 *cos(3.0*ind);\n\tcase {'BARTLETT','TRIANG'}\n\t\th=2.0*min((1:N),(N:-1:1))'/(N+1);\n\tcase 'BARTHANN'\n\t\th= 0.38 * (1.0-cos(2.0*pi*(1:N)/(N+1))') ...\n\t\t+ 0.48 * min((1:N),(N:-1:1))'/(N+1);\n\tcase 'PAPOULIS'\n\t\tind=(1:N)'*pi/(N+1); h=sin(ind);\n\tcase 'GAUSS'\n\t\tif (nargin==3), K=varargin{1}; else K=0.005; end;\n\t\th= exp(log(K) * linspace(-1,1,N)'.^2 );\n\tcase 'PARZEN'\n\t\tind=abs(-(N-1)/2:(N-1)/2)'*2/N; temp=2*(1.0-ind).^3;\n\t\th= min(temp-(1-2.0*ind).^3,temp);\n\tcase 'HANNA'\n\t\tif (nargin==3), L=varargin{1}; else L=1; end;\n\t\tind=(0:N-1)';h=sin((2*ind+1)*pi/(2*N)).^(2*L);\n\tcase {'DOLPH','DOLF'}\n\t\tif (rem(N,2)==0), oddN=1; N=2*N+1; end;\n\t\tif (nargin==3), A=10^(param/20); else A=1.0e-3; end;\n\t\tK=N-1; Z0=cosh(acosh(1.0/A)/K); x0=acos(1/Z0)/pi; x=(0:K)/N; \n\t\tindices1=find((x1-x0));\n\t\tindices2=find((x>=x0)&(x<=1-x0));\n\t\th(indices1)= cosh(K*acosh(Z0*cos(pi*x(indices1))));\n\t\th(indices2)= cos(K*acos(Z0*cos(pi*x(indices2))));\n\t\th=fftshift(real(ifft(A*real(h))));h=h'/h(K/2+1);\n \t\tif oddN, h=h(2:2:K); end;\n\tcase 'NUTBESS',\n\t\tif (nargin==3), beta=varargin{1}; nu=0.5; \n\t\telseif (nargin==4), beta=varargin{1}; nu=varargin{2};\n\t\telse beta=3*pi; nu=0.5;\n\t\tend;\n\t\tind=(-(N-1)/2:(N-1)/2)' *2/N; \n\t\th=sqrt(1-ind.^2).^nu .* ...\n\t\treal(bessel(nu,j*beta*sqrt(1.0-ind.^2)))/real(bessel(nu,j*beta));\n\tcase 'SPLINE'\n\t\tif (nargin < 3),\n\t\t\terror('Three or four parameters required for spline windows');\n\t\telseif (nargin==3)\n\t\t\tnfreq=param; p=pi*N*nfreq/10.0;\n\t\t\telse nfreq=varargin{1}; p=varargin{2};\n\t\tend\n\t\tind=(-(N-1)/2:(N-1)/2)'; \n\t\th=sinc((0.5*nfreq/p)*ind) .^ p;\n\totherwise\n\t\terror('unknown window type');\nend\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/utils/window.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7770380311369166}} {"text": "function [alpha, beta, stability] = evaluateAlphaBetaParam(process, noisy, dt)\n% evaluateAlphaBetaParam - evaluates alpha and beta parameters for alpha-beta filter\n% With this parameters, alpha-beta filter becomes a steady-state Kalman filter\n%\n% Syntax: [xkp,vkp] = alphaBetaFilter(xm, dt, xk, vk, alpha, beta)\n% [alpha, beta, stability] = evaluateAlphaBetaParam(process, noisy, dt)\n% [alpha,beta,stability] = evalABGParam([alpha,beta])\n%\n% Inputs:\n% process - real system state\n% noisy - measured system state\n%\n% Outputs:\n% alpha - alpha parameter\n% beta - beta parameter\n%\n% Other m-files required: none\n% Subfunctions: none\n% MAT-files required: none\n%\n% See also: alphaBetaFilter;\n\n% Author: Marco Borges, Ph.D. Student, Computer/Biomedical Engineer\n% UFMG, PPGEE, Neurodinamica Lab, Brazil\n% email address: marcoafborges@gmail.com\n% Website: http://www.cpdee.ufmg.br/\n% June 2013; Version: v2; Last revision: 2013-09-18\n% Changelog:\n% v2 - add Stability test\n%\n%------------------------------- BEGIN CODE -------------------------------\n\nif nargin == 3\n varProcess = var(process);\n varNoise = var(noisy);\n l = varProcess * dt / varNoise; % lambda\n r = (4+l-sqrt(8*l+l^2))/4;\n alpha = 1 - r^2;\n beta = 2*(2-alpha)-4*sqrt(1-alpha);\nelseif nargin == 1 && length(process) == 2\n alpha = process(1);\n beta = process(2);\nelse\n error('evaluateAlphaBetaParam : Incorrect Parameters!');\nend\n\nif ( alpha > 0 && alpha < 2 && beta > 0 && beta < (4-2*alpha) )\n stability = 'Stable';\nelse\n stability = 'Unstable';\nend\n\nend\n%-------------------------------- END CODE --------------------------------", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42409-evaluatealphabetaparam/evaluateAlphaBetaParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7770317634081667}} {"text": "function val=logOnePlusXMinusX(x)\n%%LOGONEPLUSXMINUSX Evaluate log(1+x)-x reducing the loss of precision that\n% occurs for values of x that are very close to 0 for real\n% values of x.\n%\n%INPUTS: x A matrix of real values>=-1.\n%\n%OUTPUTS: val The values log(1+x)-x.\n%\n%The function first computes z=log(1+x) using log1p(x) to reduce finite\n%precision errors. This value is put into the expSlope2 function, which\n%computes 2*(exp(x)-1-x)/x^2 without a low loss of finite precision.\n%Multiplying the result by (-1/2)*z^2, one gets the expression log(1+x)-x.\n%This approach ovoids a direct subtraction of x, which is where the finite\n%precision problems occur.\n%\n%EXAMPLE:\n%Here, we show the improvement that this algorithm offers to a direct\n%evaluation.\n% x=1e-150;\n% valAccurate=logOnePlusXMinusX(x)\n% valInaccurate=log1p(x)-x\n%One will see that valAccurate is about -5e-301, whereas valInaccurate is\n%just zero. The value -5e-301 can be verified using greatly extended\n%precision arithmetic.\n%\n%October 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(any(x(:)<-1)||~isreal(x))\n error('This function only supports real values of x >=-1.');\n end\n \n val=zeros(size(x));\n \n selNeg=x<-0.99;\n xNeg=x(selNeg);\n xPos=x(~selNeg);\n if(~isempty(xNeg))\n valNeg=log1p(x)-x;\n else\n valNeg=[]; \n end\n \n if(~isempty(xPos))\n z=log1p(x);\n e2Val=expSlope2(z);\n valPos=-(1/2)*e2Val.*z.^2;\n else\n valPos=[];\n end\n \n val(selNeg)=valNeg;\n val(~selNeg)=valPos;\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/logOnePlusXMinusX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7770022435459111}} {"text": "function pts = rotate(pts, phi, theta, psi)\n% ROTATE - Apply rotation to a vector of points \n\n% Define rotation matrix (right handed)\nR_roll = [...\n 1, 0, 0;...\n 0, cos(phi), sin(phi);...\n 0, -sin(phi), cos(phi)];\nR_pitch = [...\n cos(theta), 0, -sin(theta);...\n 0, 1, 0;...\n sin(theta), 0, cos(theta)];\nR_yaw = [...\n cos(psi), sin(psi), 0;...\n -sin(psi), cos(psi), 0;...\n 0, 0, 1];\nR = R_roll * R_pitch * R_yaw; % inertial to body\nR = R'; % body to inertial\n\n% Rotate vertices\npts = R*pts;\n\nend\n\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/math_tools/rotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7769839396174286}} {"text": "function value = gamma_inc ( p, x )\n\n%*****************************************************************************80\n%\n%% GAMMA_INC computes the incomplete Gamma function.\n%\n% Discussion:\n%\n% GAMMA_INC(P,X) = Integral ( 0 <= T <= X ) T**(P-1) EXP(-T) DT / GAMMA(P).\n%\n% GAMMA_INC(P, 0) = 0,\n% GAMMA_INC(P,Infinity) = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 September 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% B L Shea,\n% Chi-squared and Incomplete Gamma Integral,\n% Algorithm AS239,\n% Applied Statistics,\n% Volume 37, Number 3, 1988, pages 466-473.\n%\n% Parameters:\n%\n% Input, real P, the exponent parameter.\n% 0.0 < P.\n%\n% Input, real X, the integral limit parameter.\n% If X is less than or equal to 0, GAMMA_INC is returned as 0.\n%\n% Output, real VALUE, the value of the function.\n%\n exp_arg_min = -88.0;\n overflow = 1.0E+37;\n plimit = 1000.0;\n tol = 1.0E-07;\n xbig = 1.0E+08;\n\n value = 0.0;\n\n if ( p <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAMMA_INC - Fatal error!\\n' );\n fprintf ( 1, ' Parameter P <= 0.\\n' );\n error ( 'GAMMA_INC - Fatal error!' );\n end\n\n if ( x <= 0.0 )\n value = 0.0;\n return\n end\n%\n% Use a normal approximation if PLIMIT < P.\n%\n if ( plimit < p )\n pn1 = 3.0 * sqrt ( p ) * ( ( x / p )^( 1.0 / 3.0 ) + 1.0 / ( 9.0 * p ) - 1.0 );\n cdf = normal_01_cdf ( pn1 );\n value = cdf;\n return\n end\n%\n% Is X extremely large compared to P?\n%\n if ( xbig < x )\n value = 1.0;\n return\n end\n%\n% Use Pearson's series expansion.\n% (P is not large enough to force overflow in the log of Gamma.\n%\n if ( x <= 1.0 | x < p )\n\n arg = p * log ( x ) - x - gammaln ( p + 1.0 );\n c = 1.0;\n value = 1.0;\n a = p;\n\n while ( 1 )\n\n a = a + 1.0;\n c = c * x / a;\n value = value + c;\n\n if ( c <= tol )\n break\n end\n\n end\n\n arg = arg + log ( value );\n\n if ( exp_arg_min <= arg )\n value = exp ( arg );\n else\n value = 0.0;\n end\n\n else\n%\n% Use a continued fraction expansion.\n%\n arg = p * log ( x ) - x - gammaln ( p );\n a = 1.0 - p;\n b = a + x + 1.0;\n c = 0.0;\n pn1 = 1.0;\n pn2 = x;\n pn3 = x + 1.0;\n pn4 = x * b;\n value = pn3 / pn4;\n\n while ( 1 )\n\n a = a + 1.0;\n b = b + 2.0;\n c = c + 1.0;\n pn5 = b * pn3 - a * c * pn1;\n pn6 = b * pn4 - a * c * pn2;\n\n if ( 0.0 < abs ( pn6 ) )\n\n rn = pn5 / pn6;\n\n if ( abs ( value - rn ) <= min ( tol, tol * rn ) )\n\n arg = arg + log ( value );\n\n if ( exp_arg_min <= arg )\n value = 1.0 - exp ( arg );\n else\n value = 1.0;\n end\n\n return\n\n end\n\n value = rn;\n\n end\n\n pn1 = pn3;\n pn2 = pn4;\n pn3 = pn5;\n pn4 = pn6;\n%\n% Rescale terms in continued fraction if terms are large.\n%\n if ( overflow <= abs ( pn5 ) )\n pn1 = pn1 / overflow;\n pn2 = pn2 / overflow;\n pn3 = pn3 / overflow;\n pn4 = pn4 / overflow;\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/prob/gamma_inc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7769814105874874}} {"text": "function [V, Q, policy] = mdp_bellman_operator_with_Q(P, PR, discount, Vprev)\n\n\n% mdp_bellman_operator Applies the Bellman operator on the value function Vprev\n% Returns a new value function and a Vprev-improving policy\n% Arguments ---------------------------------------------------------------\n% Let S = number of states, A = number of actions\n% P(SxSxA) = transition matrix\n% P could be an array with 3 dimensions or \n% a cell array (1xA), each cell containing a matrix (SxS) possibly sparse\n% PR(SxA) = reward matrix\n% PR could be an array with 2 dimensions or \n% a sparse matrix\n% discount = discount rate, in ]0, 1]\n% Vprev(S) = value function\n% Evaluation --------------------------------------------------------------\n% V(S) = new value function\n% policy(S) = Vprev-improving policy\n\n% MDPtoolbox: Markov Decision Processes Toolbox\n% Copyright (C) 2009 INRA\n% Redistribution and use in source and binary forms, with or without modification, \n% are permitted provided that the following conditions are met:\n% * Redistributions of source code must retain the above copyright notice, \n% this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright notice, \n% this list of conditions and the following disclaimer in the documentation \n% and/or other materials provided with the distribution.\n% * Neither the name of the nor the names of its contributors \n% may be used to endorse or promote products derived from this software \n% without specific prior written permission.\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \n% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n% IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \n% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n% OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n% OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nif iscell(P); S = size(P{1},1); else S = size(P,1); end;\nif discount <= 0 || discount > 1\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1]')\n disp('--------------------------------------------------------')\nelseif size(Vprev,1) ~= S\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Vprev must have the same dimension as P')\n disp('--------------------------------------------------------')\nelse\n \n if iscell(P)\n A = length(P);\n for a=1:A \n Q(:,a) = PR(:,a) + discount*P{a}*Vprev;\n end\n else\n A = size(PR,2);\n for a=1:A\n Q(:,a) = PR(:,a) + discount*P(:,:,a)*Vprev;\n end\n end\n [V, policy] = max(Q,[],2);\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/MDPtoolbox/mdp_bellman_operator_with_Q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7769812057025115}} {"text": "\n% ----------------------------------------------------------------- %\n% Matlab Programs included the Appendix B in the book: %\n% Xin-She Yang, Engineering Optimization: An Introduction %\n% with Metaheuristic Applications %\n% Published by John Wiley & Sons, USA, July 2010 %\n% ISBN: 978-0-470-58246-6, Hardcover, 347 pages %\n% ----------------------------------------------------------------- %\n% Citation detail: %\n% X.-S. Yang, Engineering Optimization: An Introduction with %\n% Metaheuristic Application, Wiley, USA, (2010). %\n% % \n% http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470582464.html % \n% http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582464.html %\n% ----------------------------------------------------------------- %\n% ===== ftp:// ===== ftp:// ===== ftp:// ======================= %\n% Matlab files ftp site at Wiley %\n% ftp://ftp.wiley.com/public/sci_tech_med/engineering_optimization %\n% ---------------------------------------------------------------- %\n\n% Simulated Annealing (by X-S Yang, Cambridge University) %\n% Usage: B2_sa %\n% For the constrained optimization, please see the file: sa_mincon.m %\n% ------------------------------------------------------------------ %\n\ndisp('Simulating ... it will take a minute or so!');\n% Rosenbrock's function with f*=0 at (1,1)\nfstr='(1-x)^2+100*(y-x^2)^2';\n% Convert into an inline function\nf=vectorize(inline(fstr));\n% Show the topography of the objective function\nrange=[-2 2 -2 2];\nxgrid=range(1):0.1:range(2); ygrid=range(3):0.1:range(4);\n[x,y]=meshgrid(xgrid,ygrid);\nsurfc(x,y,f(x,y));\n% Initializing parameters and settings\nT_init = 1.0; % Initial temperature\nT_min = 1e-10; % Finial stopping temperature\nF_min = -1e+100; % Min value of the function\nmax_rej=5000; % Maximum number of rejections\nmax_run=500; % Maximum number of runs\nmax_accept = 250; % Maximum number of accept\nk = 1; % Boltzmann constant\nalpha=0.95; % Cooling factor\nEnorm=1e-8; % Energy norm (eg, Enorm=1e-8)\nguess=[2 2]; % Initial guess\n% Initializing the counters i,j etc\ni= 0; j = 0; accept = 0; totaleval = 0;\n% Initializing various values\nT = T_init;\nE_init = f(guess(1),guess(2));\nE_old = E_init; E_new=E_old;\nbest=guess; % initially guessed values\n% Starting the simulated annealling\nwhile ((T > T_min) & (j <= max_rej) & E_new>F_min)\n i = i+1;\n % Check if max numbers of run/accept are met\n if (i >= max_run) | (accept >= max_accept)\n % Cooling according to a cooling schedule\n T = alpha*T;\n totaleval = totaleval + i;\n % reset the counters\n i = 1; accept = 1;\n end\n % Function evaluations at new locations\n ns=guess+rand(1,2)*randn;\n E_new = f(ns(1),ns(2));\n % Decide to accept the new solution\n DeltaE=E_new-E_old;\n % Accept if improved\n if (-DeltaE > Enorm)\n best = ns; E_old = E_new;\n accept=accept+1; j = 0;\n end\n % Accept with a small probability if not improved\n if (DeltaE<=Enorm & exp(-DeltaE/(k*T))>rand );\n best = ns; E_old = E_new;\n accept=accept+1;\n else\n j=j+1;\n end\n % Update the estimated optimal solution\n f_opt=E_old;\nend\n% Display the final results\ndisp(strcat('Obj function :',fstr));\ndisp(strcat('Evaluations :', num2str(totaleval)));\ndisp(strcat('Best solution:', num2str(best)));\ndisp(strcat('Best objective:', num2str(f_opt)));\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/29682-engineering-optimization-an-introduction-with-metaheuristic-applications/B2_sa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7769811989369645}} {"text": "function p = predict(Theta1, Theta2, X)\n%PREDICT Predict the label of an input given a trained neural network\n% p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the\n% trained weights of a neural network (Theta1, Theta2)\n\n% Useful values\nm = size(X, 1);\nnum_labels = size(Theta2, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned neural network. You should set p to a \n% vector containing labels between 1 to num_labels.\n%\n% Hint: The max function might come in useful. In particular, the max\n% function can also return the index of the max element, for more\n% information see 'help max'. If your examples are in rows, then, you\n% can use max(A, [], 2) to obtain the max for each row.\n%\n\nZ = zeros(size(X, 1), 1);\n\nX = [ones(m, 1) X];\n\nA2 = sigmoid(X * Theta1');\n\nA2 = [ones(m, 1), A2];\n\nA3 = sigmoid(A2 * Theta2');\n\n[Z, p] = max(A3, [], 2);\n\n% =========================================================================\n\n\nend", "meta": {"author": "UtkarshPathrabe", "repo": "Machine-Learning-Stanford-University-Coursera", "sha": "0e5855855b5ddd475775b75bad69b47c2ebe84ef", "save_path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera", "path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera/Machine-Learning-Stanford-University-Coursera-0e5855855b5ddd475775b75bad69b47c2ebe84ef/Programming Exercises/machine-learning-ex3/ex3/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7769811889008604}} {"text": "function [c ceq gradc gradceq] = hs71C(x)\n\nc = -(prod(x)-25);\nceq = sum(x.^2)-40;\n\nif(nargout > 2)\n gradc = -(prod(x)./x')';\n gradceq = 2*x;\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/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/hs71C.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7769470138491404}} {"text": "function line_num = sphere_llt_grid_line_num ( lat_num, long_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLT_GRID_LINE_NUM counts lines for an LLT grid.\n%\n% Discussion:\n%\n% An LLT grid is a grid of triangles bounded by latitude and longitude \n% lines over the surface of a sphere in 3D.\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% 29 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LAT_NUM, LONG_NUM, the number of latitude 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 + long_num * lat_num ...\n + long_num * ( lat_num - 1 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_llt_grid/sphere_llt_grid_line_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.7768438150474956}} {"text": "function points = intersectLineCircle(line, circle)\n%INTERSECTLINECIRCLE Intersection point(s) of a line and a circle.\n%\n% INTERS = intersectLineCircle(LINE, CIRCLE);\n% Returns a 2-by-2-by-N array, containing on each row the coordinates of\n% an intersection point for each line-circle pair, i.e. INTERS(:,:,k)\n% contains the intersections between LINE(k,:) and CIRCLE(k,:).\n%\n% If a line-circle pair does not intersect, the corresponding results are\n% set to NaN. \n%\n% Example\n% % base point\n% center = [10 0];\n% % create vertical line\n% l1 = [center 0 1];\n% % circle\n% c1 = [center 5];\n% pts = intersectLineCircle(l1, c1)\n% pts =\n% 10 -5\n% 10 5\n% % draw the result\n% figure; clf; hold on;\n% axis([0 20 -10 10]);\n% drawLine(l1);\n% drawCircle(c1);\n% drawPoint(pts, 'rx');\n% axis equal;\n%\n% See also \n% lines2d, circles2d, intersectLines, intersectCircles\n%\n% References\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/sphereline/\n% http://mathworld.wolfram.com/Circle-LineIntersection.html\n%\n\n% ------\n% Authors: David Legland, JuanPi Carbajal\n% E-mail: david.legland@inrae.fr, ajuanpi+dev@gmail.com\n% Created: 2011-01-14, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n \t\t \n% check size of inputs\nnLines = size(line, 1);\nnCircles = size(circle, 1);\nif nLines ~= nCircles\n error ('matGeom:geom3d:invalidArguments', ...\n 'Requires same number of lines and circles');\nend\n \t\t \n% center parameters\ncenter = circle(:, 1:2);\nradius = circle(:, 3);\n\n% line parameters\ndp = line(:, 1:2) - center;\nvl = line(:, 3:4);\n\n% coefficients of second order equation\na = sum(line(:, 3:4).^2, 2);\nb = 2 * sum(dp .* vl, 2);\nc = sum(dp.^2, 2) - radius.^2;\n\n% discriminant\ndelta = b .^ 2 - 4 * a .* c;\n\npoints = nan(2, 2, nCircles);\n\nvalid = delta >= 0;\n\nif any(valid)\n % compute roots (as a N-by-N-by-2 array)\n u = bsxfun(@plus, -b(valid), bsxfun(@times, [-1 1], sqrt(delta(valid))));\n u = bsxfun(@rdivide, u, a(valid)) / 2;\n\n if sum(valid) == 1\n points = [...\n line(1:2) + u(:,1) .* line(3:4); ...\n line(1:2) + u(:,2) .* line(3:4)];\n else\n tmp = [...\n line(valid, 1:2) + u(:,1) .* line(valid, 3:4) ...\n line(valid, 1:2) + u(:,2) .* line(valid, 3:4)].';\n\t points(:, :, valid) = permute(reshape(tmp, [2, 2, nCircles]), [2 1 3]);\n end\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/intersectLineCircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7768314263876656}} {"text": "\nfunction [y,r,vr]=ssa(x1,L)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ----------------------------------------------------------------- \n% Author: Francisco Javier Alonso Sanchez e-mail:fjas@unex.es\n% Departament of Electronics and Electromecanical Engineering\n% Industrial Engineering School\n% University of Extremadura\n% Badajoz\n% Spain\n% -----------------------------------------------------------------\n%\n% SSA generates a trayectory matrix X from the original series x1\n% by sliding a window of length L. The trayectory matrix is aproximated \n% using Singular Value Decomposition. The last step reconstructs\n% the series from the aproximated trayectory matrix. The SSA applications\n% include smoothing, filtering, and trend extraction.\n% The algorithm used is described in detail in: Golyandina, N., Nekrutkin, \n% V., Zhigljavsky, A., 2001. Analisys of Time Series Structure - SSA and \n% Related Techniques. Chapman & Hall/CR.\n\n% x1 Original time series (column vector form)\n% L Window length\n% y Reconstructed time series\n% r Residual time series r=x1-y\n% vr Relative value of the norm of the approximated trajectory matrix with respect\n%\t to the original trajectory matrix\n\n% The program output is the Singular Spectrum of x1 (must be a column vector),\n% using a window length L. You must choose the components be used to reconstruct \n%the series in the form [i1,i2:ik,...,iL], based on the Singular Spectrum appearance.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n% Step1 : Build trayectory matrix\n\n N=length(x1); \n if L>N/2;L=N-L;end\n\tK=N-L+1; \n X=zeros(L,K); \n\tfor i=1:K\n\t X(1:L,i)=x1(i:L+i-1); \n\tend\n \n% Step 2: SVD\n\n S=X*X'; \n\t[U,autoval]=eig(S);\n\t[d,i]=sort(-diag(autoval)); \n d=-d;\n U=U(:,i);sev=sum(d); \n\tplot((d./sev)*100),hold on,plot((d./sev)*100,'rx');\n\ttitle('Singular Spectrum');xlabel('Eigenvalue Number');ylabel('Eigenvalue (% Norm of trajectory matrix retained)')\n V=(X')*U; \n rc=U*V';\n\n% Step 3: Grouping\n\n I=input('Choose the agrupation of components to reconstruct the series in the form I=[i1,i2:ik,...,iL] ')\n Vt=V';\n rca=U(:,I)*Vt(I,:);\n\n% Step 4: Reconstruction\n\n y=zeros(N,1); \n Lp=min(L,K);\n Kp=max(L,K);\n\n for k=0:Lp-2\n for m=1:k+1;\n y(k+1)=y(k+1)+(1/(k+1))*rca(m,k-m+2);\n end\n end\n\n for k=Lp-1:Kp-1\n for m=1:Lp;\n y(k+1)=y(k+1)+(1/(Lp))*rca(m,k-m+2);\n end\n end\n\n for k=Kp:N\n for m=k-Kp+2:N-Kp+1;\n y(k+1)=y(k+1)+(1/(N-k))*rca(m,k-m+2);\n end\n end\n\n figure;subplot(2,1,1);hold on;xlabel('Data poit');ylabel('Original and reconstructed series')\n plot(x1);grid on;plot(y,'r')\n\n r=x1-y;\n subplot(2,1,2);plot(r,'g');xlabel('Data poit');ylabel('Residual series');grid on\n vr=(sum(d(I))/sev)*100;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8115-singular-spectrum-analysis-smoother/ssa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7768314061175055}} {"text": "function [sigma_points, w_m, w_c] = compute_sigma_points(mu, sigma, lambda, alpha, beta)\n% This function samples 2n+1 sigma points from the distribution given by mu and sigma\n% according to the unscented transform, where n is the dimensionality of mu.\n% Each column of sigma_points should represent one sigma point\n% i.e. sigma_points has a dimensionality of nx2n+1.\n% The corresponding weights w_m and w_c of the points are computed using lambda, alpha, and beta:\n% w_m = [w_m_0, ..., w_m_2n], w_c = [w_c_0, ..., w_c_2n] (i.e. each of size 1x2n+1)\n% They are later used to recover the mean and covariance respectively.\n\nn = length(mu);\nsigma_points = zeros(n,2*n+1);\nw_m = zeros(1,2*n+1);\nw_c = zeros(1,2*n+1);\n\n% TODO: compute all sigma points\nsigma_points(:,1) = mu;\naddTerm = sqrtm((n+lambda)*sigma);\nfor i=1:n\n sigma_points(:,i+1) = mu + addTerm(:,i);\nendfor\nfor i=n+1:2*n\n sigma_points(:,i+1) = mu - addTerm(:,i-n);\nendfor\n\n% TODO compute weight vectors w_m and w_c\nw_m(1,1) = lambda/(n+lambda);\nw_c(1,1) = w_m(1) + (1 - alpha*alpha + beta);\nw_m(1,2:end) = 1/(2*(n+lambda));\nw_c(1,2:end) = 1/(2*(n+lambda));\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/2_Unscented_Transform/octave/compute_sigma_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7767514075875686}} {"text": "%%% Projection onto Feasible motion space\n\n% Course: Robotic Manipulation and Mobility\n% Advisor: Dr. V. Krovi\n% \n% Homework Number: MIDTERM\n% \n% Names: Sourish Chakravarty \n% \tHrishi Lalit Shah\n\n\nfunction [dX]= ROBO_midterm_f1(t,X)\n\nglobal l1 lc1 m1 j1 tau1 l2 lc2 m2 j2 tau2 g\n\nth1=X(1);\nx2= X(2);\ny2= X(3);\nth2=X(4);\nth1d= X(5);\nth2d= X(6);\n%%%%%%%%%%%%%%%%%%%%%%% CREATING IMPORTANT MATRICES IN THE GOVERNING EQUATION\ns1=sin(th1);\ns2=sin(th2);\nc1=cos(th1);\nc2=cos(th2);\n\n%%%% Element - 1\nM1= [j1+m1*(lc1^2)];\nE1= [1,-1];\nG1= [m1*lc1*c1*g];\n% B11 = [-l1*s1, l1*c1];\n% B12 = [-m1*lc1*c1];\n\n%%%% Element - 2\nM2= [m2, 0, 0;\n 0, m2, 0;\n 0, 0, j2];\nE2= [ 0; 0; 1];\nG2= [0; m2*g; 0];\n% B21= [-1, 0;\n% 0, -1;\n% -lc2*s2, lc2*c2];\n% B22= [0, -m2, 0]'; \n\n%%%% Constraints\nC= [x2-l1*c1-lc2*c2;\n y2-l1*s1-lc2*s2];\nA= [l1*s1, 1, 0, lc2*s2;\n -l1*c1, 0, 1, -lc2*c2];% Jacobian of constraint matrix\nS = [1, 0;\n -l1*s1, -lc2*s2;\n l1*c1, lc2*c2;\n 0, 1]; % Null space of A or Feasible Motion \nSd = [0, 0;\n -l1*c1*th1d, -lc2*c2*th2d;\n -l1*s1*th1d, -lc2*s2*th2d;\n 0, 0]; % Derivative of S matrix \n\n%%%%%%%%%%%%%%%%%%%%%%% PROJECTION ONTO FEASIBLE MOTION SPACE\nM=[M1, zeros(1,3);\n zeros(3,1), M2];\nE=[E1;\n zeros(3,1),E2];\nG= [G1;G2];\nT =[tau1; tau2];\nV=zeros(4,1);\n\nt1= inv(S'*M*S);\nt2= S'*(M*Sd*[th1d,th2d]'+V+G-E*T);\n\ndX(1:4,1)=S*[th1d,th2d]';\ndX(5:6,1)= -t1*t2;\n% Cerr1=([Cerr1;abs(C')]);\n% Tstore1=[Tstore1,t];\nreturn", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24246-dynamic-control-of-two-link-manipulator-with-redundant-coordinates/2 Link Dynamic Control/Code/ROBO_f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7766160502433669}} {"text": "function [ rexp, sexp ] = poly_q9 ( )\n\n%*****************************************************************************80\n%\n%% POLY_Q9 returns the monomials associated with a 9 node quadrilateral.\n%\n% Reference Element Q9:\n%\n% |\n% 1 4--7--3\n% | | |\n% | | |\n% S 8 9 6\n% | | |\n% | | |\n% 0 1--5--2\n% |\n% +--0--R--1-->\n%\n% Formula:\n%\n% Given coefficients A(I), the polynomial interpolant at (R,S) is\n%\n% P(R,S) = sum ( 1 <= I <= N ) A(I) * R**REXP(I) * S**SEXP(I)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, integer REXP(9), SEXP(9), the powers of R and S associated\n% with each monomial.\n%\n rexp(1:9) = [ 0, 0, 1, 0, 1, 2, 1, 2, 2 ];\n sexp(1:9) = [ 0, 1, 0, 2, 1, 0, 2, 1, 2 ];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/poly_q9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7766160422155874}} {"text": "function varargout = rosenbruck(X)\n% Extended Rosenbruck's Banana-function, for N-dimensional input\n%\n% ROSENBRUCK([x1, x2, .., xn]) returns the value of the Rosenbruck\n% function at the specified points. All [xi] may be vectors. The search \n% domain is\n%\n% -100 < x_i < 100\n%\n% The global minimum is \n%\n% f(x1, x2, ..., xn) = f(1, 1, ..., 1) = 0\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 28/Feb/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = inf; % # dims\n varargout{2} = -100; % LB\n varargout{3} = +100; % UB\n varargout{4} = 1; % solution\n varargout{5} = 0; % function value at solution\n \n % otherwise, output function value\n else\n \n % keep all values within the domain\n X(X < -100) = inf; X(X > 100) = inf;\n \n % split input vector X into X1, X2\n % NOTE: proper orientation can not be determined automatically\n % the sum is taken by default over the rows:\n X1 = X(1:2:end-1, :); X2 = X(2:2:end, :);\n \n % output rowsum\n varargout{1} = sum( 100*(X2 - X1.^2).^2 + (1 - X1).^2, 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/23147-many-testfunctions-for-global-optimizers/single-objective/rosenbruck.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7766160409085703}} {"text": "% Separating ellipsoids in 2D\n% Joelle Skaf - 11/06/05\n% (a figure is generated)\n%\n% Finds a separating hyperplane between 2 ellipsoids {x| ||Ax+b||^2<=1} and\n% {y | ||Cy + d||^2 <=1} by solving the following problem and using its\n% dual variables:\n% minimize ||w||\n% s.t. ||Ax + b||^2 <= 1 : lambda\n% ||Cy + d||^2 <= 1 : mu\n% x - y == w : z\n% the vector z will define a separating hyperplane because z'*(x-y)>0\n\n% input data\nn = 2;\nA = eye(n);\nb = zeros(n,1);\nC = [2 1; -.5 1];\nd = [-3; -3];\n\n% solving for the minimum distance between the 2 ellipsoids and finding\n% the dual variables\ncvx_begin\n variables x(n) y(n) w(n)\n dual variables lam muu z\n minimize ( norm(w,2) )\n subject to\n lam: square_pos( norm (A*x + b) ) <= 1;\n muu: square_pos( norm (C*y + d) ) <= 1;\n z: x - y == w;\ncvx_end\n\n\nt = (x + y)/2;\np=z;\np(1) = z(2); p(2) = -z(1);\nc = linspace(-2,2,100);\nq = repmat(t,1,length(c)) +p*c;\n\n% figure\nnopts = 1000;\nangles = linspace(0,2*pi,nopts);\n[u,v] = meshgrid([-2:0.01:4]);\nz1 = (A(1,1)*u + A(1,2)*v + b(1)).^2 + (A(2,1)*u + A(2,2)*v + b(2)).^2;\nz2 = (C(1,1)*u + C(1,2)*v + d(1)).^2 + (C(2,1)*u + C(2,2)*v + d(2)).^2;\ncontour(u,v,z1,[1 1]);\nhold on;\ncontour(u,v,z2,[1 1]);\naxis square\nplot(x(1),x(2),'r+');\nplot(y(1),y(2),'b+');\nline([x(1) y(1)],[x(2) y(2)]);\nplot(q(1,:),q(2,:),'k');\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/Ch08_geometric_probs/separate_ell_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7766160378717273}} {"text": "function points = intersectLineCircle(line, circle)\n%INTERSECTLINECIRCLE Intersection point(s) of a line and a circle\n%\n% INTERS = intersectLineCircle(LINE, CIRCLE);\n% Returns a 2-by-2-by-N array, containing on each row the coordinates of\n% an intersection point for each line-circle pair, i.e. INTERS(:,:,k)\n% contains the intersections between LINE(k,:) and CIRCLE(k,:).\n%\n% If a line-circle pair does not intersect, the corresponding results are\n% set to NaN. \n%\n% Example\n% % base point\n% center = [10 0];\n% % create vertical line\n% l1 = [center 0 1];\n% % circle\n% c1 = [center 5];\n% pts = intersectLineCircle(l1, c1)\n% pts =\n% 10 -5\n% 10 5\n% % draw the result\n% figure; clf; hold on;\n% axis([0 20 -10 10]);\n% drawLine(l1);\n% drawCircle(c1);\n% drawPoint(pts, 'rx');\n% axis equal;\n%\n% See also\n% lines2d, circles2d, intersectLines, intersectCircles\n%\n% References\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/sphereline/\n% http://mathworld.wolfram.com/Circle-LineIntersection.html\n%\n\n% ------\n% Author: David Legland, david.legland@inra.fr\n% Author: JuanPi Carbajal \n% Created: 2011-01-14, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2011-06-06 fix bug in delta test\n% 2017-05-05 included some suggestions from code by JuanPi Carbajal \n% 2017-08-08 update doc\n \t\t \n% check size of inputs\nnLines = size(line, 1);\nnCircles = size(circle, 1);\nif nLines ~= nCircles\n error ('matGeom:geom3d:invalidArguments', ...\n 'Requires same number of lines and circles');\nend\n \t\t \n% center parameters\ncenter = circle(:, 1:2);\nradius = circle(:, 3);\n\n% line parameters\ndp = line(:, 1:2) - center;\nvl = line(:, 3:4);\n\n% coefficient of second order equation\na = sum(line(:, 3:4).^2, 2);\nb = 2*sum(dp .* vl, 2);\nc = sum(dp.^2, 2) - radius.^2;\n\n% discriminant\ndelta = b .^ 2 - 4 * a .* c;\n\npoints = nan(2, 2, nCircles);\n\nvalid = delta >= 0;\n\nif any(valid)\n % compute roots\n u = bsxfun(@plus, -b(valid), bsxfun(@times, [-1 1], sqrt(delta(valid))));\n u = bsxfun(@rdivide, u, a(valid)) / 2;\n\n if nCircles == 1\n points = [...\n line(1:2) + u(:,1) .* line(3:4); ...\n line(1:2) + u(:,2) .* line(3:4)];\n else\n tmp = [...\n line(valid, 1:2) + u(:,1) .* line(valid, 3:4) ...\n line(valid, 1:2) + u(:,2) .* line(valid, 3:4)].';\n\t points(:, :, valid) = permute(reshape(tmp, [2, 2, nCircles]), [2 1 3]);\n end\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/intersectLineCircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7765987219768299}} {"text": "function [ pr, pq ] = plane_normal_basis_3d ( pp, normal )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_BASIS_3D finds two perpendicular vectors in a plane in 3D.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% N is a normal vector to the plane.\n%\n% The two vectors to be computed, PQ and PR, can be regarded as\n% the basis of a Cartesian coordinate system for points in the plane.\n% Any point in the plane can be described in terms of the \"origin\"\n% point PP plus a weighted sum of the two vectors PQ and PR:\n%\n% P = PP + a * PQ + b * PR.\n%\n% The vectors PQ and PR have unit length, and are perpendicular to N\n% and to each other.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3,1), a point on the plane. (Actually,\n% we never need to know these values to do the calculation!)\n%\n% Input, real NORMAL(3,1), a normal vector N to the plane. The\n% vector must not have zero length, but it is not necessary for N\n% to have unit length.\n%\n% Output, real PQ(3,1), a vector of unit length,\n% perpendicular to the vector N and the vector PR.\n%\n% Output, real PR(3,1), a vector of unit length,\n% perpendicular to the vector N and the vector PQ.\n%\n dim_num = 3;\n%\n% Compute the length of NORMAL.\n%\n normal_norm = norm ( normal );\n\n if ( normal_norm == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_NORMAL_BASIS_3D - Fatal error!\\n' );\n fprintf ( 1, ' The normal vector is 0.\\n' );\n error ( 'PLANE_NORMAL_BASIS_3D - Fatal error!' );\n end\n%\n% Find a vector PQ that is normal to NORMAL and has unit length.\n%\n pq = r8vec_any_normal ( 3, normal );\n%\n% Now just take the cross product NORMAL x PQ to get the PR vector.\n%\n pr = r8vec_cross_product_3d ( normal, pq );\n\n pr_norm = norm ( pr );\n\n pr(1:dim_num,1) = pr(1:dim_num,1) / pr_norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_normal_basis_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7765987075640105}} {"text": "function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...\n num_features, lambda)\n%COFICOSTFUNC Collaborative filtering cost function\n% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...\n% num_features, lambda) returns the cost and gradient for the\n% collaborative filtering problem.\n%\n\n% Unfold the U and W matrices from params\nX = reshape(params(1:num_movies*num_features), num_movies, num_features);\nTheta = reshape(params(num_movies*num_features+1:end), ...\n num_users, num_features);\n\n\n% You need to return the following values correctly\nJ = 0;\nX_grad = zeros(size(X));\nTheta_grad = zeros(size(Theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost function and gradient for collaborative\n% filtering. Concretely, you should first implement the cost\n% function (without regularization) and make sure it is\n% matches our costs. After that, you should implement the\n% gradient and use the checkCostFunction routine to check\n% that the gradient is correct. Finally, you should implement\n% regularization.\n%\n% Notes: X - num_movies x num_features matrix of movie features\n% Theta - num_users x num_features matrix of user features\n% Y - num_movies x num_users matrix of user ratings of movies\n% R - num_movies x num_users matrix, where R(i, j) = 1 if the\n% i-th movie was rated by the j-th user\n%\n% You should set the following variables correctly:\n%\n% X_grad - num_movies x num_features matrix, containing the\n% partial derivatives w.r.t. to each element of X\n% Theta_grad - num_users x num_features matrix, containing the\n% partial derivatives w.r.t. to each element of Theta\n%\n\nJ = sum(((X * Theta' - Y) .^ 2)(R == 1)) / 2;\nJ = J + lambda / 2 * (sum(sum(Theta .^ 2)) + sum(sum(X .^ 2)));\n\nX_grad = ((X * Theta' - Y) .* R) * Theta;\nTheta_grad = ((X * Theta' - Y) .* R)' * X;\n\nX_grad = X_grad + (lambda * X);\nTheta_grad = Theta_grad + (lambda * Theta);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n% =============================================================\n\ngrad = [X_grad(:); Theta_grad(:)];\n\nend\n", "meta": {"author": "fewtime", "repo": "ML", "sha": "fd9679e9d6648d01e36047e97434f38c8d2d6168", "save_path": "github-repos/MATLAB/fewtime-ML", "path": "github-repos/MATLAB/fewtime-ML/ML-fd9679e9d6648d01e36047e97434f38c8d2d6168/coursera-machine-learning/machine-learning-ex8/ex8/cofiCostFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7765987030447087}} {"text": "% fit_circle.m\n\n%fit circle to set of positions\n\n% Eq1: (X-x0)^2 + (Y-y0)^2 = r0^2\n% Eq2: (-2*x0)*X + (-2*y0)*Y + (x0^2 + y0^2 - r0^2) = -(X^2 + Y^2)\n% Eq3: [X Y 1] * [-2*x0; -2*y0; x0^2+y0^2-r0^2] = -(X^2+Y^2)\n% Eq4: A*x = b\n\n% Copyright 2003-2010 The MathWorks, Inc.\n\n% substitute:\nA = [X(:) Y(:) ones(size(X(:)))];\nb = -(X(:).^2+Y(:).^2);\n\n% solve:\nx = A\\b;\n\n% back calculate parameters\nx0 = -x(1)/2;\ny0 = -x(2)/2;\nr0 = sqrt(x0^2 + y0^2 - x(3));\n\n%draw fitted circular arc through data points\n[x_lo,i1]=min(X); th1=atan2(Y(i1)-y0,X(i1)-x0);\n[x_hi,i2]=max(X); th2=atan2(Y(i2)-y0,X(i2)-x0);\nth=linspace(th1,th2,100);\n[xx,yy]=pol2cart(th,r0*ones(size(th)));\nfigure(myFig)\nline(xx+x0+x1,yy+y0+y1,'color','m')\nline([X(i1) x0 X(i2)]+x1,[Y(i1) y0 Y(i2)]+y1,'color','g')\naxis tight\ntitle(sprintf('Center = (%.1f,%.1f), Radius = %.1f pixels',x0,y0,r0))\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3700-gravity-measurement-case-study/Gravity Measurement/fit_circle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7765476943295981}} {"text": "function y = digamma(x)\n%DIGAMMA Digamma function.\n% DIGAMMA(X) returns digamma(x) = d log(gamma(x)) / dx\n% If X is a matrix, returns the digamma function evaluated at each element.\n\n% Reference:\n%\n% J Bernardo,\n% Psi ( Digamma ) Function,\n% Algorithm AS 103,\n% Applied Statistics,\n% Volume 25, Number 3, pages 315-317, 1976.\n%\n% From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f\n\nlarge = 9.5;\nd1 = -0.5772156649015328606065121; % digamma(1)\nd2 = pi^2/6;\nsmall = 1e-6;\ns3 = 1/12;\ns4 = 1/120;\ns5 = 1/252;\ns6 = 1/240;\ns7 = 1/132;\ns8 = 691/32760;\ns9 = 1/12;\ns10 = 3617/8160;\n\n% Initialize\ny = zeros(size(x));\n\n% illegal arguments\ni = find(x == -Inf | isnan(x));\nif ~isempty(i)\n x(i) = NaN;\n y(i) = NaN;\nend\n\n% Negative values\ni = find(x < 0);\nif ~isempty(i)\n % Use the reflection formula (Jeffrey 11.1.6):\n % digamma(-x) = digamma(x+1) + pi*cot(pi*x)\n y(i) = digamma(-x(i)+1) + pi*cot(-pi*x(i));\n % This is related to the identity\n % digamma(-x) = digamma(x+1) - digamma(z) + digamma(1-z)\n % where z is the fractional part of x\n % For example:\n % digamma(-3.1) = 1/3.1 + 1/2.1 + 1/1.1 + 1/0.1 + digamma(1-0.1)\n % = digamma(4.1) - digamma(0.1) + digamma(1-0.1)\n % Then we use\n % digamma(1-z) - digamma(z) = pi*cot(pi*z)\nend\n \ni = find(x == 0);\nif ~isempty(i)\n y(i) = -Inf;\nend\n\n% Use approximation if argument <= small.\ni = find(x > 0 & x <= small);\nif ~isempty(i)\n y(i) = y(i) + d1 - 1 ./ x(i) + d2*x(i);\nend\n\n% Reduce to digamma(X + N) where (X + N) >= large.\nwhile(1)\n i = find(x > small & x < large);\n if isempty(i)\n break\n end\n y(i) = y(i) - 1 ./ x(i);\n x(i) = x(i) + 1;\nend\n\n% Use de Moivre's expansion if argument >= large.\n% In maple: asympt(Psi(x), x);\ni = find(x >= large);\nif ~isempty(i)\n r = 1 ./ x(i);\n y(i) = y(i) + log(x(i)) - 0.5 * r;\n r = r .* r;\n y(i) = y(i) - r .* ( s3 - r .* ( s4 - r .* (s5 - r .* (s6 - r .* s7))));\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/digamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7765321569164925}} {"text": "function value = legendre_3d_monomial_integral ( a, b, p )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_3D_MONOMIAL_INTEGRAL the Legendre integral of a monomial.\n%\n% Discussion:\n%\n% The Legendre integral to be evaluated has the form\n%\n% I(f) = integral ( z1 <= z <= z2 )\n% integral ( y1 <= y <= y2 ) \n% integral ( x1 <= x <= x2 ) x^i y^j z^k dx dy dz\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(3), the lower limits of integration.\n%\n% Input, real B(3), the upper limits of integration.\n%\n% Input, integer P(3), the exponents of X and Y.\n%\n% Output, real VALUE, the value of the exact integral.\n%\n value = ( b(1) ^ ( p(1) + 1 ) - a(1) ^ ( p(1) + 1 ) ) / ( p(1) + 1 ) ...\n * ( b(2) ^ ( p(2) + 1 ) - a(2) ^ ( p(2) + 1 ) ) / ( p(2) + 1 ) ...\n * ( b(3) ^ ( p(3) + 1 ) - a(3) ^ ( p(3) + 1 ) ) / ( p(3) + 1 );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cube_exactness/legendre_3d_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7765321522969711}} {"text": "% Copyright (C) 2016, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction jacobian_symbolic_spherical_v\n% link lengths\nL3 = 0.38;\nL6 = 0.065;\n\nsyms q1 q2 q3\n% matrices DH\nA01 = dh_sym(q1, L3, 0, pi/2);\nA12 = dh_sym(q2, 0, 0, -pi/2);\nA23 = dh_sym(q3, L6, 0, 0);\n\nA02 = A01*A12;\nA03 = A01*A12*A23;\n\nz0 = [0 0 1]';\nz1 = A01(1:3,3);\nz2 = A02(1:3,3);\n\np03=A03(1:3,4);\np13=A03(1:3,4)-A01(1:3,4);\np23=A03(1:3,4)-A02(1:3,4);\n\nJv = [cross(z0, p03) cross(z1, p13) cross(z2, p23)];\n\nsingularities = det(Jv)\n\n\n\nfunction A = dh_sym(theta, d, a, alpha)\nsyms q1 q2 q3\n% avoid almost zero elements in cos(alpha) and sin(alpha)\nca = cos(alpha);\nsa = sin(alpha);\nif abs(ca) < 1e-6\n ca = 0;\nend\nif abs(sa) < 1e-6\n sa = 0;\nend\n\n\nA=[cos(theta) -ca*sin(theta) sa*sin(theta) a*cos(theta);\n sin(theta) ca*cos(theta) -sa*cos(theta) a*sin(theta);\n 0 sa ca d;\n 0 0 0 1];\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/book/jacobian_symbolic_spherical_v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7765321495725959}} {"text": "% PAD_SIZE Compute the optimal size for padding\n%\n% Usage\n% sz_padded = PAD_SIZE(sz, min_margin, max_ds)\n%\n% Input\n% sz (int): The size of the original signal.\n% min_margin (int): The minimum margin for padding.\n% max_ds (int): The maximum downsampling factor.\n%\n% Output\n% sz_padded (int): The minimum size of the padded signal.\n%\n% Description\n% Calculates the smallest multiple of 2^max_ds larger than sz by at least \n% 2*min_margin. This ensures that there is enough margin on both sides of\n% the signal to avoid border effects, assuming that min_margin is equal\n% to at least half of the size of the largest filter used, while ensuring\n% that downsampling by powers of 2 up to 2^max_ds are possible through\n% periodization of the Fourier transform.\n% sz_added is also enforced to be at least 1\n%\n% See Also\n% PAD_SIGNAL, UNPAD_SIGNAL\n\nfunction sz_padded = pad_size(sz, min_margin, max_ds)\n sz_padded = 2^max_ds * ceil( (sz + 2*min_margin)/2^max_ds );\n sz_padded = max(1, sz_padded);\nend", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/convolution/pad_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7765321452238096}} {"text": "function exactness_test09 ( )\n\n%*****************************************************************************80\n%\n%% EXACTNESS_TEST09 tests Gauss-Chebyshev2 rules for the Chebyshev2 integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXACTNESS_TEST09\\n' );\n fprintf ( 1, ' Test Gauss-Chebyshev2 rules for the Chebyshev2 integral.\\n' );\n fprintf ( 1, ' Density function rho(x) = sqrt(1-x^2).\\n' );\n fprintf ( 1, ' Region: -1 <= x <= +1.\\n' );\n fprintf ( 1, ' Exactness: 2*N-1.\\n' );\n\n for n = 1 : 5\n\n [ x, w ] = chebyshev2_set ( n );\n p_max = 2 * n;\n chebyshev2_exactness ( n, x, w, p_max );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/exactness/exactness_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7765292904205074}} {"text": "function [ x, w ] = hermite_ek_compute ( n )\n\n%*****************************************************************************80\n%\n%% HERMITE_EK_COMPUTE computes a Gauss-Hermite quadrature rule.\n%\n% Discussion:\n%\n% The code uses an algorithm by Elhay and Kautsky.\n%\n% The abscissas are the zeros of the N-th order Hermite polynomial.\n%\n% The integral:\n%\n% integral ( -oo < x < +oo ) exp ( - x * x ) * 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% 09 May 2012\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the number of abscissas.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = gamma ( 0.5 );\n%\n% Define the Jacobi matrix.\n%\n bj = zeros ( n, 1 );\n for i = 1 : n\n bj(i) = i / 2.0;\n end\n bj(1:n) = sqrt ( bj(1:n) );\n\n x = zeros ( n, 1 );\n\n w = zeros ( n, 1 );\n w(1) = sqrt ( zemu );\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\n%\n% If N is odd, force the center X to be 0.\n%\n if ( mod ( n, 2 ) == 1 )\n x((n+1)/2) = 0.0;\n end\n\n w(1:n) = w(1:n).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/hermite_ek_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7765292749730712}} {"text": "function [ pols, dersx, dersy ] = klegeypols3 ( x, y, n )\n\n%*****************************************************************************80\n%\n%% KLEGEYPOLS3 evaluate scaled Legendre polynomials and derivatives.\n%\n% Discussion:\n%\n% This routine evaluates a sequence of scaled Legendre polynomials\n% P_n(x/y) y^n, with the parameter y in [0,1], together with their\n% derivatives with respect to the parameters x and y.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 27 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Input, real Y, the parameter value.\n%\n% Input, integer N, the highest degree to be evaluated.\n%\n% Output, real POLS(N+1), the polynomial values.\n%\n% Output, real DERSX(N+1), the derivatives with respect to X.\n%\n% Output, real DERSY(N+1), the derivatives with respect to Y.\n%\n pkp1 = 1.0;\n pols(1) = pkp1;\n dkp1 = 0.0;\n dersx(1) = dkp1;\n ykp1 = 0.0;\n dersy(1) = ykp1;\n\n if ( n == 0 )\n return\n end\n\n pk = pkp1;\n pkp1 = x;\n pols(2) = pkp1;\n dk = dkp1;\n dkp1 = 1.0;\n dersx(2) = dkp1;\n yk = ykp1;\n ykp1 = 0.0;\n dersy(2) = ykp1;\n\n if ( n == 1 )\n return\n end\n\n for k = 1 : n - 1\n pkm1 = pk;\n pk = pkp1;\n dkm1 = dk;\n dk = dkp1;\n ykm1 = yk;\n yk = ykp1;\n pkp1 = ( ( 2.0 * k + 1.0 ) * x * pk - k * pkm1 * y * y ) / ( k + 1.0 );\n dkp1 = ( ( 2.0 * k + 1.0 ) * ( x * dk + pk ) ...\n - k * dkm1 * y * y ) / ( k + 1.0 );\n ykp1 = ( ( 2.0 * k + 1.0 ) * ( x * yk ) ...\n - k * ( pkm1 * 2.0 * y + ykm1 * y * y ) ) / ( k + 1.0 );\n pols(k+2) = pkp1;\n dersx(k+2) = dkp1;\n dersy(k+2) = ykp1;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_symq_rule/klegeypols3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.776524216270755}} {"text": "function exact = p42_exact ( )\n\n%*****************************************************************************80\n%\n%% P42_EXACT returns the exact integral for problem 42.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the value of the integral.\n%\n alpha = p42_param_get ( );\n\n exact = 2.0^( alpha - 2.0 ) * ( gamma ( alpha / 2.0 ) )^2 / gamma ( alpha );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p42_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7765242112668672}} {"text": "function [ yval, ypval, yppval ] = spline_cubic_val ( n, t, y, ypp, tval )\n\n%*****************************************************************************80\n%\n%% SPLINE_CUBIC_VAL evaluates a piecewise cubic spline at a point.\n%\n% Discussion:\n%\n% SPLINE_CUBIC_SET must have already been called to define the\n% values of YPP.\n%\n% For any point T in the interval T(IVAL), T(IVAL+1), the form of\n% the spline is\n%\n% SPL(T) = A\n% + B * ( T - T(IVAL) )\n% + C * ( T - T(IVAL) )**2\n% + D * ( T - T(IVAL) )**3\n%\n% Here:\n% A = Y(IVAL)\n% B = ( Y(IVAL+1) - Y(IVAL) ) / ( T(IVAL+1) - T(IVAL) )\n% - ( YPP(IVAL+1) + 2 * YPP(IVAL) ) * ( T(IVAL+1) - T(IVAL) ) / 6\n% C = YPP(IVAL) / 2\n% D = ( YPP(IVAL+1) - YPP(IVAL) ) / ( 6 * ( T(IVAL+1) - T(IVAL) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl de Boor,\n% A Practical Guide to Splines,\n% Springer Verlag, 1978.\n%\n% Parameters:\n%\n% Input, integer N, the number of data values.\n%\n% Input, real T(N), the knot values.\n%\n% Input, real Y(N), the data values at the knots.\n%\n% Input, real YPP(N), the second derivatives of the spline at the knots.\n%\n% Input, real TVAL, a point, typically between T(1) and T(N), at\n% which the spline is to be evalulated. If TVAL lies outside\n% this range, extrapolation is used.\n%\n% Output, real YVAL, YPVAL, YPPVAL, the value of the spline, and\n% its first two derivatives at TVAL.\n%\n\n%\n% Determine the interval [T(LEFT), T(RIGHT)] that contains TVAL.\n% Values below T(1) or above T(N) use extrapolation.\n%\n [ left, right ] = r8vec_bracket ( n, t, tval );\n%\n% Evaluate the polynomial.\n%\n dt = tval - t(left);\n h = t(right) - t(left);\n\n yval = y(left) ...\n + dt * ( ( y(right) - y(left) ) / h ...\n - ( ypp(right) / 6.0 + ypp(left) / 3.0 ) * h ...\n + dt * ( 0.5 * ypp(left) ...\n + dt * ( ( ypp(right) - ypp(left) ) / ( 6.0 * h ) ) ) );\n\n ypval = ( y(right) - y(left) ) / h ...\n - ( ypp(right) / 6.0 + ypp(left) / 3.0 ) * h ...\n + dt * ( ypp(left) ...\n + dt * ( 0.5 * ( ypp(right) - ypp(left) ) / h ) );\n\n yppval = ypp(left) + dt * ( ypp(right) - ypp(left) ) / h;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/spline_cubic_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.776524207930942}} {"text": "function [R_ned_2_frame, ned_x, ned_y, ned_z] = computeNedFrameInFrame(rVect)\n %Source: https://en.wikipedia.org/wiki/North_east_down\n \n rNorm = norm(rVect);\n lambda = AngleZero2Pi(atan2(rVect(2),rVect(1)));\n phi = pi/2 - acos(rVect(3)/rNorm);\n \n RFrame2Ned = [-sin(phi)*cos(lambda), -sin(lambda), -cos(phi)*cos(lambda);\n -sin(phi)*sin(lambda), cos(lambda), -cos(phi)*sin(lambda);\n cos(phi), 0, -sin(phi)]';\n \n R_ned_2_frame = RFrame2Ned';\n ned_x = R_ned_2_frame(:,1);\n ned_y = R_ned_2_frame(:,2);\n ned_z = R_ned_2_frame(:,3);\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/steering/computeNedFrameInFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7765135782425223}} {"text": "function [v,beta]=HouseholderVec(x,forceSign)\n%%HOUSEHOLDERVEC Given an mX1 column vector x, compute mX1 column\n% vector v and scalar beta such that P=eye(m,m)-beta*v*v' is\n% orthogonal and P*x=(+/-)norm(x)*e1 for real x, where e1 is a\n% vector with a 1 in the first entry and zeros elsewhere. If\n% forceSign is true, then it will be such that the + sign is\n% always chosen. For complex x,\n% P*x=(+/-)exp(1j*angle(x(1)))*norm(x)*e1, whereby the sign in\n% front can vary. The v vector is chosen such that v(1)=1. If a\n% scalar value is provided, then v=1, beta=0 are returned.\n%\n%INPUTS: x An mX1 vector, real or complex.\n% forceSign If true and x is real, then P*x always equals +norm(x)*e1.\n% Otherwise, it can be + or -. Often, assumptions on recovering\n% matrices from factored form implicitly assume that\n% forceSign=false. The default if omitted or an empty matrix is\n% passed is false.\n%\n%OUTPUTS: v An mX1 vector such that P=eye(m)-beta*v*v' is an orthogonal\n% matrix and P*x having the only nonzero element be the first\n% one. If a scalar input is given, then v=0 is returned.\n% beta The real scalar beta as mentioned with v. beta= 2/(v'*v). If a\n% scalar input is given, then beta=0 is returned.\n%\n%For real vectors x, the Householder vector algorithm of Section 5.1.1 of\n%[1] is used. For complex vectors, the Householder algorithm of Section\n%5.1.13 is used.\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(forceSign))\n forceSign=false;\nend\n\nm=length(x);\n\nif(isempty(x))\n v=[];\n beta=[];\n return;\nend\n\nif(m==1)\n v=1;\n beta=0;\n return;\nend\n\nif(isreal(x))%The real case from Chapter 5.1.3 in [1].\n sigma=x(2:m)'*x(2:m);\n v=[1;x(2:m)];\n if(sigma==0&&x(1)>=0)\n if(forceSign)\n beta=0;\n else\n beta=2;\n end\n\n return;\n elseif(sigma==0&&x(1)<0)\n beta=2;%Sign corrected from that in the book.\n return;\n else\n mu=sqrt(x(1).*x(1)+sigma);\n %The book has <=; we are using < as it does not change things and\n %for some data types, such as Intervals, it is easier to overload <\n %than <=.\n if(x(1)<0)\n v(1)=x(1)-mu;\n else\n v(1)=-sigma/(x(1)+mu);\n end\n beta=2*v(1).*v(1)./(sigma+v(1).*v(1));\n v=v./v(1);\n end\nelse%The complex case from Chapter 5.1.13\n angVal=x(1)/abs(x(1));\n %Deal with NaNs due to x(1)=0.\n if(~isfinite(angVal))\n angVal=1;\n end\n\n x2Norm=norm(x,2);\n \n v=zeros(m,1);\n \n v(2:end)=x(2:end);\n v1=x(1)+angVal*x2Norm;\n v2=x(1)-angVal*x2Norm;\n \n %Of v1 and v2, choose the one with the largest norm.\n if(abs(v1)>abs(v2))\n v(1)=v1;\n else\n v(1)=v2;\n end\n \n v=v/v(1);\n beta=2/(v'*v);\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/HouseholderVec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.776408256094197}} {"text": "function rotMat = axisAngle2RotMat(axis,angle)\n% Function to get the rotation matrix for a given axis and angle where x \n% is a column vector, such that:\n% xNew = rotMat*x \n% \n% Alternate use where x is a row vector: \n% xNew = x*rotMat'\n% \n% Parameters\n% ------------\n% axis : 1 x 3 float vector\n% Axis about which to rotate the point x\n% angle : float\n% Rotation angle (radian)\n%\n% Returns\n% ------------\n% rotMat : 3 x 3 float vector \n% Rotation matrix from the input axis and angle\n%\n\nrotMat = zeros(3);\nrotMat(1,1) = axis(1)*axis(1)*(1-cos(angle)) + cos(angle);\nrotMat(1,2) = axis(2)*axis(1)*(1-cos(angle)) - axis(3)*sin(angle);\nrotMat(1,3) = axis(3)*axis(1)*(1-cos(angle)) + axis(2)*sin(angle);\nrotMat(2,1) = axis(1)*axis(2)*(1-cos(angle)) + axis(3)*sin(angle);\nrotMat(2,2) = axis(2)*axis(2)*(1-cos(angle)) + cos(angle);\nrotMat(2,3) = axis(3)*axis(2)*(1-cos(angle)) - axis(1)*sin(angle);\nrotMat(3,1) = axis(1)*axis(3)*(1-cos(angle)) - axis(2)*sin(angle);\nrotMat(3,2) = axis(2)*axis(3)*(1-cos(angle)) + axis(1)*sin(angle);\nrotMat(3,3) = axis(3)*axis(3)*(1-cos(angle)) + cos(angle);\n\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/coordTransformation/axisAngle2RotMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176860436174, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.776291953997817}} {"text": "function [X, maxdot] = packing_on_the_sphere(d, n, epsilon, X0)\n% Return a set of points spread out on the sphere.\n%\n% function [X, maxdot] = packing_on_the_sphere(d, n, epsilon, X0)\n%\n% Using optimization on the oblique manifold, that is, the product of\n% spheres, this function returns a set of n points with unit norm in R^d in\n% the form of a matrix X of size nxd, such that the points are spread out\n% on the sphere. Ideally, we would minimize the maximum inner product\n% between any two points X(i, :) and X(j, :), i~=j, but that is a nonsmooth\n% cost function. Instead, we replace the max function by a classical\n% log-sum-exp approximation and (attempt to) solve:\n%\n% min_{X in OB(d, n)} log( .5*sum_{i~=j} exp( xi'*xj/epsilon ) ),\n%\n% with xi = X(:, i) and epsilon is some \"diffusion constant\". As epsilon\n% goes to zero, the cost function is a sharper approximation of the max\n% function (under some assumptions), but the cost function becomes stiffer\n% and hence harder to optimize.\n%\n% The second output, maxdot, is the maximum inner product between any two\n% points in the returned X. This number is the one we truly are trying to\n% minimize.\n%\n% Notice that this cost function is invariant under rotation of X:\n% f(X) = f(XQ) for all orthogonal Q in O(d).\n% This calls for optimization over the set of symmetric positive\n% semidefinite matrices of size n and rank d with unit diagonal, which can\n% be thought of as the quotient of the oblique manifold OB(d, n) by O(d):\n% See elliptopefactory.\n%\n% This is known as the Thomson or, more specifically, the Tammes problem:\n% http://en.wikipedia.org/wiki/Tammes_problem\n% An interesting page by Neil Sloane collecting best known packings is\n% available here http://neilsloane.com/packings/\n\n% This file is part of Manopt and is copyrighted. See the license file.\n%\n% Main author: Nicolas Boumal, July 2, 2013\n% Contributors:\n%\n% Change log:\n% Aug. 14, 2013 (NB) : Code now compatible to experiment with both the\n% obliquefactory and the elliptopefactory.\n%\n% Jan. 7, 2014 (NB) : Added reference to Neil Sloane's page and the\n% maxdot output.\n%\n% June 24, 2014 (NB) : Now shifting exponentials to alleviate numerical\n% trouble when epsilon is too small.\n% \n% Aug. 31, 2021 (XJ) : Added AD to compute the gradient\n\n if ~exist('d', 'var') || isempty(d)\n % Dimension of the embedding space: R^d\n d = 3;\n end\n if ~exist('n', 'var') || isempty(n)\n % Number n of points to place of the sphere in R^d.\n % For example, n=12 yields an icosahedron:\n % https://en.wikipedia.org/wiki/Icosahedron\n % Notice though that platonic solids are not always optimal.\n % Try for example n = 8: you don't get a cube.\n n = 24;\n end\n if ~exist('epsilon', 'var') || isempty(epsilon)\n % This value should be as close to 0 as affordable.\n % If it is too close to zero, optimization first becomes much\n % slower, than simply doesn't work anymore becomes of floating\n % point overflow errors (NaN's and Inf's start to appear).\n % If it is too large, then log-sum-exp is a poor approximation of\n % the max function, and the spread will be less uniform.\n % An okay value seems to be 0.01 or 0.001 for example. Note that a\n % better strategy than using a small epsilon straightaway is to\n % reduce epsilon bit by bit and to warm-start subsequent\n % optimization in that way. Trustregions will be more appropriate\n % for these fine tunings.\n epsilon = 0.0015;\n end\n \n % Pick your manifold (the elliptope factory quotients out the global\n % rotation invariance of the problem, which is more natural but\n % conceptually a bit more complicated --- for usage with the toolbox it\n % is the same though: just uncomment the appropriate line).\n manifold = obliquefactory(d, n, true);\n % manifold = elliptopefactory(n, d);\n \n % Generate a random initial guess if none was given.\n if ~exist('X0', 'var') || isempty(X0)\n X0 = manifold.rand();\n end\n\n % Define the cost function with caching system used: the store\n % structure we receive as input is tied to the input point X. Everytime\n % this cost function is called at this point X, we will receive the\n % same store structure back. We may modify the store structure inside\n % the function and return it: the changes will be remembered for next\n % time.\n function [f, store] = cost(X, store)\n if ~isfield(store, 'ready')\n XXt = X*X';\n % Shift the exponentials by the maximum value to reduce\n % numerical trouble due to possible overflows.\n s = max(max(triu(XXt, 1)));\n expXXt = exp((XXt-s)/epsilon);\n % Zero out the diagonal\n expXXt(1:(n+1):end) = 0;\n u = sum(sum(triu(expXXt, 1)));\n store.XXt = XXt;\n store.s = s;\n store.expXXt = expXXt;\n store.u = u;\n store.ready = true;\n end\n u = store.u;\n s = store.s;\n f = s + epsilon*log(u);\n end\n\n % Define the gradient of the cost. When the gradient is called at a\n % point X for which the cost was already called, the store structure we\n % receive remember everything that the cost function stored in it, so\n % we can reuse previously computed elements.\n function [g, store] = grad(X, store)\n if ~isfield(store, 'ready')\n [~, store] = cost(X, store);\n end\n % Compute the Euclidean gradient\n eg = store.expXXt*X / store.u;\n % Convert to the Riemannian gradient (by projection)\n g = manifold.egrad2rgrad(X, eg);\n end\n\n % Setup the problem structure with its manifold M and cost+grad\n % functions.\n problem.M = manifold;\n problem.cost = @cost;\n problem.grad = @grad;\n\n % An alternative way to compute the grad is to use automatic\n % differentiation provided in the deep learning toolbox (slower)\n % Notice that the function triu is not supported for AD so far.\n % Replace it with ctriu described in the file manoptADhelp.m\n % problem.cost = @cost_AD;\n % function f = cost_AD(X)\n % XXt = X*X';\n % s = max(max(ctriu(XXt, 1)));\n % expXXt = exp((XXt-s)/epsilon);\n % expXXt(1:(n+1):end) = 0;\n % u = sum(sum(ctriu(expXXt, 1)));\n % f = s + epsilon*log(u);\n % end\n % Call manoptAD to prepare AD for the problem structure\n % problem = manoptAD(problem,'egrad');\n \n % For debugging, it's always nice to check the gradient a few times.\n % checkgradient(problem);\n % pause;\n \n % Call a solver on our problem with a few options defined. We did not\n % specify the Hessian but it is still okay to call trustregion: Manopt\n % will approximate the Hessian with finite differences of the gradient.\n opts.tolgradnorm = 1e-8;\n opts.maxtime = 1200;\n opts.maxiter = 1e5;\n % X = trustregions(problem, X0, opts);\n X = conjugategradient(problem, X0, opts);\n \n % Evaluate the maximum inner product between any two points of X.\n XXt = X*X';\n dots = XXt(find(triu(ones(n), 1))); %#ok\n maxdot = max(dots);\n \n % Similarly, even though we did not specify the Hessian, we may still\n % estimate its spectrum at the solution. It should reflect the\n % invariance of the cost function under a global rotatioon of the\n % sphere, which is an invariance under the group O(d) of dimension\n % d(d-1)/2 : this translates into d(d-1)/2 zero eigenvalues in the\n % spectrum of the Hessian.\n % The approximate Hessian is not a linear operator, and is it a\n % fortiori not symmetric. The result of this computation is thus not\n % reliable. It does display the zero eigenvalues as expected though.\n if manifold.dim() < 300\n evs = real(hessianspectrum(problem, X));\n figure;\n stem(1:length(evs), sort(evs), '.');\n title(['Eigenvalues of the approximate Hessian of the cost ' ...\n 'function at the solution']);\n end\n \n \n % Show how the inner products X(:, i)'*X(:, j) are distributed.\n figure;\n histogram(real(acos(dots)), 20);\n title('Histogram of the geodesic distances');\n \n % This is the quantity we actually want to minimize.\n fprintf('Maximum inner product between two points: %g\\n', maxdot);\n \n \n % Give some visualization if the dimension allows\n if d == 2\n % For the circle, the optimal solution consists in spreading the\n % points with angles uniformly sampled in (0, 2pi). This\n % corresponds to the following value for the max inner product:\n fprintf('Optimal value for the max inner product: %g\\n', cos(2*pi/n));\n figure;\n t = linspace(-pi, pi, 201);\n plot(cos(t), sin(t), '-', 'LineWidth', 3, 'Color', [152,186,220]/255);\n daspect([1 1 1]);\n box off;\n axis off;\n hold on;\n plot(X(:, 1), X(:, 2), 'r.', 'MarkerSize', 25);\n hold off;\n end\n if d == 3\n figure;\n set(gcf, 'Color', 'w');\n % Plot the sphere\n [sphere_x, sphere_y, sphere_z] = sphere(50);\n handle = surf(sphere_x, sphere_y, sphere_z);\n set(handle, 'FaceColor', [152,186,220]/255);\n set(handle, 'FaceAlpha', .5);\n set(handle, 'EdgeColor', [152,186,220]/255);\n set(handle, 'EdgeAlpha', .5);\n daspect([1 1 1]);\n box off;\n axis off;\n hold on;\n % Add the chosen points\n Y = 1.02*X';\n plot3(Y(1, :), Y(2, :), Y(3, :), 'r.', 'MarkerSize', 25);\n % And connect the points which are at minimal distance,\n % within some tolerance.\n min_distance = real(acos(maxdot));\n connected = real(acos(XXt)) <= 1.20*min_distance;\n [Ic, Jc] = find(triu(connected, 1));\n for k = 1 : length(Ic)\n i = Ic(k); j = Jc(k);\n plot3(Y(1, [i j]), Y(2, [i j]), Y(3, [i j]), 'k-');\n end\n hold off;\n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/examples/packing_on_the_sphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7762821183434285}} {"text": "function inside = circle_sector_contains_point_2d ( r, center, theta1, theta2, p )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SECTOR_CONTAINS_POINT_2D : is a point inside a circular sector?\n%\n% Discussion:\n%\n% A circular sector is formed by a circular arc, and the two straight line\n% segments that join its ends to the center of the circle.\n%\n% A circular sector is defined by\n%\n% ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 = R**2\n%\n% and\n%\n% Theta1 <= Theta <= Theta2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2,1), the center of the circle.\n%\n% Input, real THETA1, THETA2, the angles defining the arc,\n% in radians. Normally, THETA1 < THETA2.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, logical INSIDE, is TRUE if the point is inside or on the\n% circular sector, FALSE otherwise.\n%\n inside = 0;\n%\n% Is the point inside the (full) circle?\n%\n if ( ( p(1,1) - center(1,1) ) * ( p(1,1) - center(1,1) ) ...\n + ( p(2,1) - center(2,1) ) * ( p(2,1) - center(2,1) ) <= r * r )\n%\n% Is the point's angle within the arc's range?\n% Try to force the angles to lie between 0 and 2 * PI.\n%\n theta = r8_atan ( p(2,1) - center(2,1), p(1,1) - center(1,1) );\n\n if ( r8_modp ( theta - theta1, 2.0 * pi ) <= ...\n r8_modp ( theta2 - theta1, 2.0 * pi ) )\n\n inside = 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/geometry/circle_sector_contains_point_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.776282103958492}} {"text": "function out=proj_Lorentz(x)\n%PROJ_LORENTZ computes the orthogonal projection onto the Lorentz cone {x:||x(1,..,n)||<=x(n+1)}\n%\n% Usage: \n% out = PROJ_LORENTZ(x)\n% ===========================================\n% Input:\n% x - (n+1)-length vector to be projected \n% ===========================================\n% Output:\n% out - projection vector\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n%reading the user \nif (nargin < 1)\n error ('usage: proj_Lorentz(x)') ;\nend\nn = length(x)-1;\ns = x(n+1) ;\nx = x(1:n) ;\n\nif (norm(x,s) >= abs(s))\n outx = (norm(x,2) + s)/(2*norm(x,2)) * x;\n outs = (norm(x,2) + s)/2 ;\nelse\n if (norm(x,2) <= s)\n outx = x ;\n outs = s ;\n else\n % s < norm(x,2) < -s\n outx = zeros(n,1) ;\n outs = 0 ;\n end\nend\n\nout = [outx; outs] ;\n\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/proj_Lorentz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7762820991641322}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Bayesian Linear Regression 1D Example %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 1) Generate 1D Regression Datasets %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Generate some data\nclear all;close all;clc;\nnbSamples = 50;\nX = linspace(0,4,nbSamples);\nw = [0.5 25];\ny = X * w(1) + normrnd(0,0.2,1,nbSamples) + w(2);\n\n\noptions = [];\noptions.points_size = 20;\noptions.title = 'Training data'; \n\nif exist('h1','var') && isvalid(h1), delete(h1);end\nh1 = ml_plot_data([X(:),y(:)],options);\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 2) Train BLR Model %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Train Baysian Gaussian Linear regressin\nvar = 0.2; % variance in the noise of the data\nSigma_p = eye(2,2);\nXb = [X];\nyb = y;\n[w,invA] = train_blr(Xb',y',var,Sigma_p);\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 3) Test BLR Model %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n%% Prediction\n\nx_test = [linspace(0,4,100);ones(1,100)];\ny_test = x_test' * w;\nSigma = x_test' * invA * x_test;\n\n\nif exist('h2','var') && isvalid(h2), delete(h2);end\nif exist('h3','var') && isvalid(h3), delete(h3);end\n\n\nh2 = figure; \n\nsubplot(1,2,1);\nbox on;\nplot_gaussian_contour(gca,zeros(2,1),Sigma_p);\nxlabel('b','FontSize',11);\nylabel('a','FontSize',11);\ntitle('Prior weights','FontSize',11);\ngrid on;\naxis square;\naxis_limits = axis;\n\nsubplot(1,2,2);\nbox on;\nplot_gaussian_contour(gca,w,invA);\nxlabel('b','FontSize',11);\nylabel('a','FontSize',11);\ntitle('Posterior weights','FontSize',11);\ngrid on;\naxis square;\n\nh3 = figure;\nhold on;box on;\nscatter(X,y,20,'filled');\nhp = plot(x_test(1,:),y_test,'--r','LineWidth',2);\ngrid on;\naxis square;\nlegend(hp,'regression line');\ntitle('y = b * x + a');\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/examples/regression/BLR_1D_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7762106189376519}} {"text": "function [N,errL2,errH1,erruIuh] = cubePoissoncvtmeshnew\n% CUBEPOISSON solves Poisson equation in a cube.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; clear all;\n%% Parameters\nmaxIt = 4; N = zeros(maxIt,1); \nerrL2 = zeros(maxIt,1); errH1 = zeros(maxIt,1); erruIuh = zeros(maxIt,1);\n\n%% Get the data of the pde\npde = sincosdata3;\n% pde = polydata3;\n\n%% Finite Element Method \nfor k = 1:maxIt\n [node,elem] = cvtuniformmesh(2^k);\n % solve the equation\n option.solver = 'direct';\n [u,Du,A,eqn] = Poisson3(node,elem,pde,[],[],option); \n N(k) = size(node,1);\n % compute error\n errL2(k) = getL2error3(node,elem,pde.exactu,u);\n errH1(k) = getH1error3(node,elem,pde.Du,Du);\n uI = pde.exactu(node); % nodal interpolation\n erruIuh(k) = sqrt((u-uI)'*eqn.AD*(u-uI));\nend\n\n%% Plot convergence rates\nfigure(2);\nr1 = showrate(N,errH1,2,'-*');\nhold on;\nr2 = showrate(N,errL2,2,'k-+');\nr3 = showrate(N,erruIuh,2,'m-+');\nlegend('||Du-Du_h||',['N^{' num2str(r1) '}'], ...\n '||u-u_h||',['N^{' num2str(r2) '}'], ...\n '||DuI-Du_h||',['N^{' num2str(r3) '}'], 'LOCATION','Best');\n%%\n% The error in H1 and L2 norm converges at optimal rate. But no\n% superconvergence on criss-cross grids.\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/example/3D/cubePoissoncvtmesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8688267711434708, "lm_q1q2_score": 0.7761311318299071}} {"text": "% Mathematics Q454519\n% https://math.stackexchange.com/questions/454519\n% Least Squares with L2 Linear Norm Regularization (Not Squared)\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 22/08/2017\n% * First release.\n\n\n%% General Parameters\n\nrun('InitScript.m');\n\nfigureIdx = 0; % 2010\n\nif nargin < 1, n = 0; end\nif nargin < 2, a = 1/2 + sqrt(-3)/6; end\n\n% Constants\nb = 1 - a;\nc = 1/2 + sqrt(-3)/2;\nd = 1 - c;\n\n% Generate point sequence\nz = 1;\nfor k = 1:n\n z = conj(z);\n z = [a*z; b*z+a];\nend\n\n% Close snowflake\nz = [0; z; 1-c*z; 1-c-d*z];\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27577-fractal-curves/snowflake.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7760818243913071}} {"text": "function [ as, bs, cs ] = sphere01_triangle_vertices_to_sides ( v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% SPHERE01_TRIANGLE_VERTICES_TO_SIDES computes spherical triangle sides on unit sphere.\n%\n% Discussion:\n%\n% We can use the ACOS system call here, but the ARC_COSINE routine\n% will automatically take care of cases where the input argument is\n% (usually slightly) out of bounds.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real V1(3), V2(3), V3(3), the vertices of the spherical\n% triangle.\n%\n% Output, real AS, BS, CS, the (geodesic) length of the sides\n% of the triangle.\n%\n as = r8_acos ( v2(1:3)' * v3(1:3) );\n bs = r8_acos ( v3(1:3)' * v1(1:3) );\n cs = r8_acos ( v1(1:3)' * v2(1: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/sphere_triangle_monte_carlo/sphere01_triangle_vertices_to_sides.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7760818227459678}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n% periodic signals\n\nt=1:5;\nx=sin(t);\nT=2*pi;\nfor k=1:10\nxk(k,:)=sin(t+k*T);\nend\nxk\n\n%Sum of periodic continuous time signals \n t=0:.1:6*pi;\n x=cos(t)+sin(3*t);\n plot(t,x)\n\n \n %\tConstruction of periodic signals \n figure\n [s,t]=gensig('square',3,20,0.01);\n plot(t,s)\n ylim([-.3 1.3])\n \n figure\n [s,t]=gensig('pulse',2,10);\n plot(t,s)\n ylim([-.3 1.3])\n\n figure\n t=0:0.1:10;\n s=square(t);\n plot(t,s);\n ylim([-1.3 1.3])\n \n figure\n s2=square(2*pi*t);\n plot(t,s2);\n ylim([-1.3 1.3]) ; \n \n figure\n t=0:0.1:20;\n s=sawtooth(t);\n plot(t,s);\n ylim([-1.3 1.3])\n\n \n figure\n t=0:.1:10;\n x=t.*exp(-t);\n xp=repmat(x,1,8);\n tp=linspace(0,80,length(xp));\n plot(tp,xp)\n \n figure\n N=10;\n x=[1 1 -1 -1];\n xp=repmat(x,1,N);\n n=0:length(xp)-1;\n stem(n,xp);\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c241.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7760332717216205}} {"text": "function [V3D] = Vandermonde3D(N, r, s, t);\n\n% function [V3D] = Vandermonde3D(N, r, s, t);\n% Purpose : Initialize the 3D Vandermonde Matrix, V_{ij} = phi_j(r_i, s_i, t_i);\n\nV3D = zeros(length(r),(N+1)*(N+2)*(N+3)/6);\n\n% Transfer to (a,b) coordinates\n[a, b, c] = rsttoabc(r, s, t);\n\n% build the Vandermonde matrix\nsk = 1;\n\nfor i=0:N % old ordering\n for j=0:N - i\n for k=0:N - i - j\n V3D(:,sk) = Simplex3DP(a,b,c,i,j,k);\n sk = sk+1;\n end\n end\nend\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/Vandermonde3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212402, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7759898208793279}} {"text": "function [ a, b, c, d ] = plane_normal2imp_3d ( pp, normal )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL2IMP_3D converts a normal form plane to implicit form in 3D.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is\n%\n% PP, a point on the plane, and\n% N, the unit normal to the plane.\n%\n% The implicit form of a plane in 3D is\n%\n% A * X + B * Y + C * Z + D = 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane.\n%\n% Input, real NORMAL(3), the unit normal vector to the plane.\n%\n% Output, real A, B, C, D, the implicit plane parameters.\n%\n a = normal(1);\n b = normal(2);\n c = normal(3);\n d = - a * pp(1) - b * pp(2) - c * pp(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/geometry/plane_normal2imp_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7759852492498149}} {"text": "function [u,X,T,uf,t]=forcmove(a,v,tmax,nt)\n\n% [u,X,T,uf,t]=forcmove(a,v,tmax,nt)\n% See Article 9.4 \n% This function computes the dynamic response \n% of a taut string subjected to a force moving\n% along the string with constant speed. The\n% string is fixed at x=0 and and x=+infinity.\n% The system is initially at rest when the \n% force is imposed at the left end and moves\n% to the right at constant speed. If the force\n% speed is larger than the wave propagation \n% speed, then no disturbance occurs ahead of\n% the force. If the force moves slower than the \n% wave propagation speed, then the deflection \n% propagates ahead of the force at the speed \n% of wave propagation. \n% \n% v - speed of the moving load \n% a - speed of wave propagation in the\n% string\n% tmax - maximum time for which the \n% solution is computed\n% u - matrix of deflection values where\n% time and position vary row-wise and\n% column-wise, respectively\n% T,X - matrices of time and position values\n% corresponding to the deflection \n% matrix U\n% uf - deflection values where the force acts\n% t - vector of times (same as colunms of T)\n\nif nargin==0, a=.8; v=1; tmax=10; nt=15; end \n\n% Obtain solution values and plot results\n[u,X,T,uf,t]=ustring(a,v,tmax,nt); \nif a>v, xf=X(:,2); uf=u(:,2); xw=X(:,3); \nelse, xf=X(:,3); uf=u(:,3); end\nclose, subplot(211)\nwaterfall(X,T,-u), xlabel('x axis')\nylabel('time'), zlabel('deflection')\ntitl=['INVERTED MOTION SURFACE FOR A = ',...\n num2str(a),' AND V = ',num2str(v)]; \ntitle(titl), grid on, hold on\nplot3(xf,t,-uf,'.k',xf,t,-uf,'k')\ncolormap([0 0 0]), view([-10,30]), shg\numin=min(u(:)); umax=max(u(:)); xmax=X(1,4);\nrange=[0,xmax,2*umin,2*umax]; hold on \nTitl='T = %4.2f'; subplot(212) , axis off\n\n% Use a dense set of points for animation \nnt=80; [uu,XX,TT,uuf,tt]=ustring(a,v,tmax,nt);\numax=max(abs(uu(:))); uu=uu/umax; uuf=uuf/umax;\nXX=XX/xmax; range=[0,1,-1,0.5]; h=.4;\narx=h*[0,.02,-.02,0,0]; ary=h*[0,.25,.25,0,1];\nfor j=1:nt\n uj=uu(j,:); xj=XX(j,:);\n xfj=v/xmax*tt(j); ufj=uuf(j);\n plot(xj,uj,'k',xfj+arx,ufj+ary,'-k')\n axis off, time=(sprintf(Titl,tt(j))); \n text(.45,.25,time), axis(range), drawnow\n pause(.05), figure(gcf), if jv\n X(:,2)=xf; X(:,3)=xw; u(:,2)=uf;\nelse\n X(:,2)=xw; X(:,3)=xf; u(:,2)=uw; \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/6558-dynamics-of-some-classical-system-models/dynamics/forcmove.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7759852328241175}} {"text": "function variance = semicircular_variance ( a, b )\n\n%*****************************************************************************80\n%\n%% SEMICIRCULAR_VARIANCE returns the variance of the Semicircular PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < B.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = b * b / 4.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/semicircular_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7759803834315627}} {"text": "function [ ndp, xdp, ydp ] = dif_deriv ( nd, xd, yd )\n\n%*****************************************************************************80\n%\n%% DIF_DERIV computes the derivative of a polynomial in divided difference form.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 June 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl deBoor,\n% A Practical Guide to Splines,\n% Springer, 2001,\n% ISBN: 0387953663,\n% LC: QA1.A647.v27.\n%\n% Parameters:\n%\n% Input, integer ND, the size of the input table.\n%\n% Input, real XD(ND), the abscissas for the divided\n% difference table.\n%\n% Input, real YD(ND), the divided difference table.\n%\n% Output, integer NDP, the size of the output table, which is ND-1.\n%\n% Input, real XDP(NDP), the abscissas for the divided\n% difference table for the derivative.\n%\n% Output, real YDP(NDP), the divided difference\n% table for the derivative.\n%\n\n% Using a temporary copy of the difference table, shift the\n% abscissas to zero.\n%\n xd_temp(1:nd) = xd(1:nd);\n yd_temp(1:nd) = yd(1:nd);\n\n [ xd_temp, yd_temp ] = dif_shift_zero ( nd, xd_temp, yd_temp );\n%\n% Construct the derivative.\n%\n ndp = nd - 1;\n\n xdp(1:ndp) = 0.0;\n\n for i = 1 : ndp\n ydp(i) = i * yd_temp(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/hermite/dif_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.775980382871138}} {"text": "%% UNO Rosenbrock\nclc\n%Objective\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nx0 = [0 1]';\n\nopts = [];\nopts.algorithm = nloptSolver('LN_PRAXIS');\nopts.maxfeval = 1000;\nopts.maxtime = 1;\nopts.display = 2;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% UNO Rosenbrock [GRAD]\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.gradient = @(x) mklJac(nlprob.objective,x);\nx0 = [0 1]';\n\nopts = [];\nopts.algorithm = nloptSolver('LD_LBFGS');\nopts.maxfeval = 100;\nopts.maxtime = 1;\nopts.display = 2;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% BOUNDED Rosenbrock\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.lb = [-5;-5];\nnlprob.ub = [1;0.8];\nx0 = [0 0]';\n\nopts = [];\nopts.algorithm = nloptSolver('LN_PRAXIS');\nopts.maxfeval = 1000;\nopts.maxtime = 10;\nopts.display = 2;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% BOUNDED GRAD Rosenbrock\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.gradient = @(x) mklJac(nlprob.objective,x);\nnlprob.lb = [-5;-5];\nnlprob.ub = [1;0.8];\nx0 = [0 0]';\n\nopts = [];\nopts.algorithm = nloptSolver('LD_LBFGS');\nopts.maxfeval = 1000;\nopts.maxtime = 10;\nopts.display = 2;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% NLCON HS71\nclc\n%Objective\nobj = @(x) x(1)*x(4)*sum(x(1:3)) + x(3); \n%Linear Constraints\nlb = ones(4,1);\nub = 5*ones(4,1);\n%Nonlinear Constraints\nnlcon = @(x) [prod(x); sum(x.^2)]; \n\nnlprob =[];\nnlprob.objective = obj;\nnlprob.nlcon = nlcon;\nnlprob.nlrhs = [25;40];\nnlprob.nle = [1;0];\nnlprob.lb = lb;\nnlprob.ub = ub;\n\nopts = [];\nopts.algorithm = nloptSolver('LN_COBYLA');\nopts.maxfeval = 1000;\nopts.maxtime = 2;\nopts.display = 2;\nnlprob.options = opts;\n\nx0 = zeros(4,1);\n\n[x,f,e,i] = nlopt(nlprob,x0,opts)\n\n%% NLCON GRAD HS71\n%Objective & Gradient\nobj = @(x) x(1)*x(4)*sum(x(1:3)) + x(3);\ngrad = @(x) [ x(1)*x(4) + x(4)*sum(x(1:3));\n x(1)*x(4);\n x(1)*x(4) + 1;\n x(1)*sum(x(1:3)) ]; \n%Linear Constraints\nlb = ones(4,1);\nub = 5*ones(4,1);\n%Nonlinear Constraints\nnlcon = @(x) [prod(x); sum(x.^2)];\nnljac = @(x) [prod(x)./x'; 2*x']; \n\nnlprob =[];\nnlprob.objective = obj;\nnlprob.gradient = grad;\nnlprob.nlcon = nlcon;\nnlprob.nljac = nljac;\nnlprob.nlrhs = [25;40];\nnlprob.nle = [1;0];\nnlprob.lb = lb;\nnlprob.ub = ub;\n\nopts = [];\nopts.algorithm = nloptSolver('LD_SLSQP');\nopts.maxfeval = 1000;\nopts.maxtime = 2;\nopts.display = 2;\nnlprob.options = opts;\n\nx0 = [1 5 5 1]';\n\n[x,f,e,i] = nlopt(nlprob,x0,opts)\n\n%% NLP1 Hock & Schittkowski #71\nclc\n%Objective & Gradient\nobj = @(x) x(1)*x(4)*sum(x(1:3)) + x(3);\ngrad = @(x) [ x(1)*x(4) + x(4)*sum(x(1:3));\n x(1)*x(4);\n x(1)*x(4) + 1;\n x(1)*sum(x(1:3)) ]; \n%Linear Constraints\nlb = ones(4,1);\nub = 5*ones(4,1);\n%Nonlinear Constraints\nnlcon = @(x) [ prod(x);\n sum(x.^2)];\nnljac = @(x) [ prod(x)./x';\n 2*x' ]; \nnlrhs = [25 40]';\nnle = [1 0]'; % (>=, ==)\n%Setup Options\nopts = optiset('solver','nlopt','warnings','on','display','iter','solverOpts',nloptset('algorithm','LD_SLSQP'));\n%Build & Solve\nOpt = opti('obj',obj,'grad',grad,'nlmix',nlcon,nlrhs,nle,'nljac',nljac,'bounds',lb,ub,'options',opts)\nx0 = [1 5 5 1]';\n[x,fval,exitflag,info]= solve(Opt,x0)\n\n%% LP [-31.4]\nclc\n% clear all\n%Objective & Constraints\nf = -[6 5]';\nA = ([1,4; 6,4; 2, -5]); \nb = [16;28;6]; \n\nnlprob = [];\nnlprob.objective = @(x) f'*x;\nnlprob.gradient = @(x) f;\n\nnlprob.nlcon = @(x) A*x;\nnlprob.nljac = @(x) A;\nnlprob.nlrhs = b;\nnlprob.nle = [-1;-1;-1];\n\nnlprob.lb = [0;0];\nnlprob.ub = [10;10];\n\nopts = [];\nopts.algorithm = nloptSolver('LD_SLSQP');\nopts.maxfeval = 100;\nopts.maxtime = 2;\nopts.display = 2;\nnlprob.options = opts;\n\nx0 = [0;0];\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% LP1\nclc\n%Objective & Constraints\nf = -[6 5]';\nA = ([1,4; 6,4; 2, -5]); \nb = [16;28;6]; \n%Build Object\nOpt = opti('obj',@(x) f'*x,'grad',@(x) f,'ineq',A,b,'bounds',[0;0],[10;10],'options',optiset('solver','nlopt','solverOpts',nloptset('algorithm','LD_SLSQP')))\n%Build & Solve\n[x,fval,exitflag,info] = solve(Opt,[0;0]) \n%Plot\nplot(Opt)\n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n%% Auglag NLP\nclc\nfun = @(x) log(1+x(1)^2) - x(2);\ngrad = @(x)[[(2*x(1))/(x(1)^2+1)];[-1]];\nnlcon = @(x) (1 + x(1)^2)^2 + x(2)^2 - 4;\nnljac = @(x)[[4*x(1)*(x(1)^2+1),2*x(2)]];\nnlrhs = 0;\nnle = 0;\nx0 = [2;2];\n\nnlprob = [];\nnlprob.objective = fun;\nnlprob.gradient = grad;\n\nnlprob.nlcon = nlcon;\nnlprob.nljac = nljac;\nnlprob.nlrhs = nlrhs;\nnlprob.nle = nle;\n\nopts = [];\nopts.algorithm = nloptSolver('LD_AUGLAG');\nopts.maxfeval = 120;\nopts.maxtime = 2;\nopts.display = 2;\n\nopts.local_optimizer.algorithm = nloptSolver('LD_LBFGS');\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% Error checking\nclc\nclear\nnlprob.objective = @(x) -1;\nnlprob.lb = [-1;-1];\nnlprob.ub = [1;1];\n\nnlprob.nlcon = @(x) [-1;-1];\nnlprob.nlrhs = [-1;-1];\nnlprob.nle = [1;1];\n\nnlprob.options.algorithm = 25;\nx0 = [1;1];\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% Stop Val Checking\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.lb = [-5;-5];\nnlprob.ub = [1;1];\nx0 = [0 0]';\n\nopts = [];\nopts.algorithm = nloptSolver('LN_PRAXIS');\nopts.maxfeval = 1000;\nopts.maxtime = 10;\nopts.display = 2;\nopts.stopval = 1e-6;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% Vector Storage Checking\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.gradient = @(x) mklJac(nlprob.objective,x);\nnlprob.lb = [-5;-5];\nnlprob.ub = [1;0.8];\nx0 = [0 0]';\n\nopts = [];\nopts.algorithm = nloptSolver('LD_LBFGS');\nopts.maxfeval = 1000;\nopts.maxtime = 10;\nopts.display = 2;\nopts.vector_storage = 1;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n\n%% Initial Pop Testing\nclc\n%Objective\nnlprob = [];\nnlprob.objective = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\nnlprob.lb = [0;0];\nnlprob.ub = [1;1];\nx0 = [0 0]';\n\nopts = [];\nopts.algorithm = nloptSolver('GN_CRS2_LM');\nopts.maxfeval = 1000;\nopts.maxtime = 10;\nopts.display = 1;\nopts.initial_pop = 30;\nnlprob.options = opts;\n\n[x,f,e,i] = nlopt(nlprob,x0)\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/test_nlopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.775980376255978}} {"text": "function [m,v]=v_chimv(n,l,s)\n%V_CHIMV approximate mean and variance of non-central chi distribution [m,v]=(n,l,s)\n%\n% Inputs:\tn = degrees of freedom\n% l = non-centrality parameter = sqrt(sum(mean^2)) [default 0]\n% (can be a vector or matrix to calculate many different values at once)\n% s = standard deviation of Gaussian [default 1]\n%\n% Outputs: m = mean of chi distribution\n% v = variance of chi distribution\n%\n% If x=c+randn(n,1) is a column vector of Gaussian random numbers with mean vector c, then\n% z=sqrt(x'*x) has a chi distributon with n degrees of freedom and non-centrality parameter\n% l=sqrt(c'*c). The mean and variance of a chi distribution are given precisely by\n%\n% m = sqrt(2)*exp(gammaln(0.5*n+0.5)-gammaln(0.5*n))*hypergeom(-0.5,0.5*n,-0.5*l^2)\n% = sqrt(pi/2) L(0.5,0.5*n-1,-0.5*l^2)\n% v = n+l^2-m^2\n%\n% where L(n,a,x) is the generalized Laguerre polynomial L_n^{(a)}(x) but this is very slow\n% to calculate so this routine approximates these expressions.\n%\n% For n=1, the accuracy is high; for n>1, accuracy improves with increasing n.\n% Accuracy is worst when the non-centrality parameter, l, is close to s*sqrt(n).\n% Worst case errors as a function of n are:\n% n: 1 2 3 5 10\n% worst case error in m: 1e-15 0.007 0.004 0.0015 0.0005\n\n% Copyright (C) Mike Brookes 2014\n% Version: $Id: v_chimv.m 4969 2014-08-05 18:24:30Z 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 ab pp qq nab\nif isempty(ab)\n nab=200; % cache a few low values of n\n pp=[ 0.595336298258636 -1.213013700592756 -0.018016200037799 1.999986150447582 0];\n qq=[ -0.161514114798972 0.368983655790737 -0.136992134476950 -0.499681107630725 2];\n ni=1./(1:nab);\n ab=[polyval(qq,ni);polyval(pp,ni)];\nend\nif nargin<3\n s=1;\n if nargin<2\n l=0;\n end\nend\nls=l/s;\nl2=(ls).^2;\ns2=s^2;\nif n<=nab\n if n==1\n m=l.*(1-2*normcdf(-ls))+2*s*normpdf(-ls);\n else\n m=sqrt(l2+n-1+(ab(1,n)+ab(2,n)*l2).^(-1))*s;\n end\nelse\n m=sqrt(l2+n-1+(polyval(qq,1/n)+polyval(pp,1/n)*l2).^(-1))*s;\nend\nv=(n+l2)*s2-m.^2;\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_chimv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7758904986549734}} {"text": "function point = intersectThreePlanes(plane1, plane2, plane3)\n%INTERSECTTHREEPLANES Return intersection point between 3 planes in space.\n%\n% LINE = intersectThreePlanes(PLANE1, PLANE2, PLANE3)\n% Returns the point or straight line belonging to three planes.\n% PLANE: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n% POINT: [x0 y0 z0]\n% IF rank of the coefficient matrix r1 = 3 and\n% Rank of the augmented matrix r2 = 3 return point\n% Otherwise returns point with NaN values.\n%\n% See also \n% planes3d, intersectPlanes, intersectLinePlane\n\n% ------\n% Author: Roozbeh Geraili Mikola\n% E-mail: roozbehg@berkeley.edu or roozbehg@live.com\n% Created: 2017-09-20\n% Copyright 2017-2022\n\n% plane normal\nn1 = normalizeVector3d(cross(plane1(:,4:6), plane1(:, 7:9), 2));\nn2 = normalizeVector3d(cross(plane2(:,4:6), plane2(:, 7:9), 2));\nn3 = normalizeVector3d(cross(plane3(:,4:6), plane3(:, 7:9), 2));\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);\nd3 = dot(n3, plane3(:,1:3), 2);\n\n% create coefficient and augmented matrices\nA = [n1;n2;n3];\nD = [d1;d2;d3];\nAD = [n1,d1;n2,d2;n3,d3];\n\n% calculate rank of the coefficient and augmented matrices\nr1 = rank(A);\nr2 = rank(AD);\n\n% if rank of the coefficient matrix r1 = 3 and\n% rank of the augmented matrix r2 = 3 return point\n% and if r1 = 2 and r2 = 2 return line, \n% otherwise returns point with NaN values.\nif r1 == 3 && r2 == 3\n % Intersecting at a point\n point = (A\\D)';\nelse\n point = [NaN NaN NaN];\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/intersectThreePlanes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7758804067899848}} {"text": "function unique_num = point_tol_unique_count ( m, n, a, tol )\n\n%*****************************************************************************80\n%\n%% POINT_TOL_UNIQUE_COUNT counts the tolerably unique points.\n%\n% Discussion:\n%\n% The input data is an M x N array A, representing the M-dimensional\n% coordinates of N points.\n%\n% This function uses a simple but expensive approach. The first point\n% is accepted as unique. Each subsequent point is accepted as unique\n% only if it is at least a tolerance away from all accepted unique points.\n% This means the expected amount of work is O(N^2).\n%\n% The output is the number of unique points in the list.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows.\n%\n% Input, integer N, the number of columns.\n%\n% Input, real A(M,N), the array of N columns of data.\n%\n% Input, real TOL, a tolerance.\n%\n% Output, integer UNIQUE_NUM, the number of unique points.\n%\n unique(1:n) = 1;\n unique_num = n;\n\n for i = 2 : n\n\n for j = 1 : i - 1\n if ( unique(j) )\n dist = sqrt ( sum ( ( a(1:m,i) - a(1:m,j) ).^2 ) );\n if ( dist <= tol )\n unique(i) = 0;\n unique_num = unique_num - 1;\n break\n end\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/point_merge/point_tol_unique_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.775814456277811}} {"text": "function npart = setpart_enum ( m )\n\n%*****************************************************************************80\n%\n%% SETPART_ENUM enumerates the partitions of a set of M elements.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer M, the number of elements in the set.\n% M must be positive. However, for the enumeration routine only,\n% it is legal to call with any value of M.\n%\n% Output, integer NPART, the number of partitions of the set.\n%\n if ( m < 0 )\n\n npart = 0;\n\n elseif ( m == 0 )\n\n npart = 1;\n\n else\n\n offset = 1;\n b(0+offset) = 1;\n for j = 1 : m\n b(j+offset) = 0;\n for i = 0 : j - 1\n b(j+offset) = b(j+offset) + i4_choose ( j - 1, i ) * b(i+offset);\n end\n end\n\n npart = b(m+offset);\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/setpart_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7758065198133728}} {"text": "function H = sndspd_mean(z,ssp,d)\n% harmonic_mean\n%\n% Val Schmidt\n% Center for Coastal and Ocean Mapping\n% University of New Hampshire\n% 2012\n%\n% A routine to calculate the harmonic mean sound speed.\n% \n% z: Vector of depth values. (m)\n% ssp: Vector of sound speed values at the associated depths. (m/s)\n% d: [Optional] maximum depth (m) (see below)\n%\n% Suppose one is given a sound speed profile (sound speeds [ssp] and depths [z]). \n% One wishes to know how long it will take a sound pulse (say from a sonar)\n% to travel down through the water column. \n%\n% Most people will realize that one cannot simply average the sound speeds\n% and divide by the total depth. However many will incorrectly assume that\n% a depth-weighted mean sound will produce the correct answer.\n% Unfortunately it does not. \n%\n% One must instead divide the total depth by the sum of the time it takes\n% to the sound to pass through each layer of constant sound speed. This is\n% called the 'harmonic mean'. The harbmonic mean is calculated like so.\n%\n% | i=n | -1\n% | SUM delta z(i) |\n% | i=1 --------- |\n% | c(i) |\n% C_harmonic = | ------------------- |\n% | i=n |\n% | SUM delta z(i) |\n% | i=1 |\n% | |\n%\n% When the maximum depth, 'd', is specified, two possible things may result\n% depending on whether d is greater or less than the maximum depth in z.\n%\n% Sometimes one has a complete sound speed profile, but only needs the\n% harmonic sound speed to some max depth less than the maximum depth of the\n% profile. One may then specify the maximum depth as the argument 'd', and\n% the function will return a harmonic mean to only that depth.\n%\n% Alternatively, one frequently has a sound speed profile for the upper\n% portion of the water column only, but desireds a harmonic sound speed all\n% the way to the bottom. Below some max depth temperature and salnity are\n% constant and sound speed increases nearly linearly (to about 1 part in\n% 10^4) with increasing depth. In this case, one may specify a the bottom\n% depth, d. The function will then approximate the the sound speed at the\n% bottom linearly from the final value in the ssp vector and calculate a\n% harmonic sound speed for the entire path.\n%\n% When the sound speed profile is a constant linear gradient rather than \n% discrete values one can calculate the time required to traverse the\n% layer directly rather than approximating the gradient in discrete steps.\n% That time is given by \n%\n% 1 c(i+1) \n% t = - ln ( ------ )\n% g c(i)\n%\n% This value is then added to the summation of travel times (with a\n% corresponding addition to the summation of depth differences) in the\n% haronic mean calculation above.\n\n%%\n\n% Initialize a variable. variables\nt=0;\n\n% Mackenzie Formula first-order term for sound speed as a function of\n% depth.\nD1=.0163;\n\n% Check some details.\nif ( ~isequal( size(z),size(ssp) ) )\n error('ERROR input vectors are not of same size');\nend\n\n% The algorithm below will produce incorrect results if the first depth\n% value is not zero. So we force it to be zero, shifting the other depths\n% appropriately.\ntop=z(1);\nz=z-top;\n\n% One can optionally specify a max bottom depth. This value may be less\n% than, or deeper than, the lowest depth in the z vector. If it is less than\n% than z(end), the harmonic mean to the depth, d is calculated. If it is more\n% than z(end), the sound speed profile is extended to the depth d using the\n% first-order depth dependent term from the Mackenzie equation and the\n% results of the Harmonic mean calculation for a gradient.\n\nif ( nargin==3 )\n\n % First we shift the d value as we did the z values to make sure\n % everything matches.\n d=d-top;\n \n % If d is less than the max depth in z truncate the z and ssp vectors\n % to that depth. \n if (d < max(z) )\n idx=find( z <= d);\n z=z(idx);\n ssp=ssp(idx);\n \n % Otherwise we calculate the extra time in this final layer.\n else\n\n % We need the sound speed at hte specified bottom.\n ss_bottom = ssp(end) + ( d - z(end) ) * D1;\n \n % This is the equation for the time spent in a layer having a gradient\n % sound speed, D1, and where the difference in sound speed from the top to\n % the bottom of the layer is delta_ss.\n t= 1/D1 *log( ss_bottom / ssp(end) );\n \n end\n \nelse\n % Give d the max depth regardless.\n d=z(end);\nend\n\n\n% Calculate the harmonic mean sound speed.\nH = ( (sum(diff(z)./ssp(1:(length(ssp)-1))) + t ) / d )^(-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/36358-calculate-the-harmonic-mean-sound-speed-vertically-through-a-profile/sndspd_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7758065103955776}} {"text": "function node_rhs = rhs ( node_num, node_xy )\n\n%*****************************************************************************80\n%\n%% RHS gives the right-hand side of the differential equation.\n%\n% Discussion:\n%\n% This routine is set up for the L-shaped region, with exact solution\n% U = X^2 + Y^2. Hence, the right hand side of the equation is\n% exactly -4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM),\n% the coordinates of the points.\n%\n% Output, real NODE_RHS(NODE_NUM,1), the value of the\n% right hand side function at the points.\n%\n node_rhs(1:node_num,1) = -4.0 ...\n + node_xy(1,1:node_num).^2 ...\n + node_xy(2,1:node_num).^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/fem2d_poisson_sparse_ell/rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.775806500557772}} {"text": "function IQR=interquartileRange(x,dim,definition)\n%%INTERQUARTILERANGE Determine the interquartile range of the values in x.\n% This is notionally the difference between the value in the\n% 75th percentile (the third quartile) and the 25th percentile\n% (the first quartile) of the data. However, the strict\n% definition varies, which is why there are multiple options.\n%\n%INPUTS: x A vector, matrix or hypermatrix of real values. The\n% interquartile range is only taken over a particular dimension.\n% dim An optional parameter specifying the dimensions across which\n% the interquartile range is found. If this value is omitted or an\n% empty matrix is passed, then the interquartile range is computed\n% across the first non-singleton dimension of x.\n% definition This selects the definition fo the interquartile range that is\n% to be used. Let n be the number of points in dimension dim of x.\n% The following definitions are considering each independent\n% vector in dimension dim being processed. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) If an\n% odd number of points is passed, then the first quartile is the\n% median of ordered (ascending) points up to floor(n/2) and the\n% third quartile is the median of ordered points from ceil(n/2)\n% to n. Thus, the median is assigned to the upper half. If an\n% even number of points is passed, then the first quartile is\n% the median of the ordered points up to n/2 and the third\n% quartile is the median of ordered points n/2+1 to n. Thus, the\n% halves are split.\n% 1 This is the same as 0, except when given an odd number of\n% points, the middle point is omitted, not assigned to the upper\n% quartile. If only 1 point is given, 0 is returned.\n% 2 This is the same as 0 and 1 except when given an odd number of\n% points, the median point is included in both the lower and the\n% upper quartile. This type of interquartile range is also known\n% as the midhinge.\n% 3 The first and third quartiles are given by percentileVal with\n% its definition=0.\n% 4 The first and third quartiles are given by percentileVal with\n% its definition=1.\n% 5 This uses the kthOrderStat to get the 1+floor(0.25*(n-1)) and\n% 1+ceil(0.75*(n-1)) order statistics.\n% 6 In the set of ordered points, let the split point be\n% k50=ceil(n/2). The lower quartile value is the one at index\n% ceil(k50/2) and the upper quartile value is the one at index\n% k50+ceil((n-k50)/2). This is identical to considering the\n% points part of an empirical distribution and choosing the\n% percentiles using EmpiricalD.invCDF. If none aling directly\n% with 1/4 and 3/4, choose the next highest point.\n%\n%OUTPUTS: IQR The interquartile range values. This is a matrix with the\n% same dimensions as x except dimension dim has become unitary.\n% If dimension dim is a singleton, then IRQ will be zero for\n% all definitions.\n%\n%EXAMPLE:\n%Here, one sees some of the differences:\n% for def=0:6\n% IQR=interquartileRange([1,2,3,4,5],[],def)\n% end\n% one will get 2.5, 3, 2, 2.5, 2, 2, and 2.\n%\n%September 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isempty(x))\n IQR=[];\n return;\nend\n\n%Select the first non-singleton dimension if dim is not provided.\nif(nargin<2||isempty(dim))\n dim=find(size(x)>1,1);\n if(isempty(dim))\n dim=1;\n end\nend\n\nif(nargin<3||isempty(definition))\n definition=0;\nend\n\nn=size(x,dim);\n\nif(n==1)%If the interquartile range is a singleton, then zero is returned\n %for all methods.\n IQR=zeros(size(x));\n return;\nend\n\nswitch(definition)\n case 0%The definition used in Mathematica and in Matlab's IQR function.\n %The middle point for an odd number of points is assigned to the\n %third quartile.\n idxVec=repmat({':'},1,ndims(x));\n\n x=sort(x,dim,'ascend');\n if(mod(n,2)==0)%Split the halves\n idxVec{dim}=1:(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=(n/2+1):n;\n Q3=median(x(idxVec{:}),dim);\n else%Assign the median point to the third quartile.\n idxVec{dim}=1:floor(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=ceil(n/2):n;\n Q3=median(x(idxVec{:}),dim);\n end\n case 1%Alternative successive median definition 1.\n idxVec=repmat({':'},1,ndims(x));\n \n x=sort(x,dim,'ascend');\n if(mod(n,2)==0)%Split the halves\n idxVec{dim}=1:(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=(n/2+1):n;\n Q3=median(x(idxVec{:}),dim);\n else%Omit the median point.\n idxVec{dim}=1:floor(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=(ceil(n/2)+1):n;\n Q3=median(x(idxVec{:}),dim);\n end\n case 2%Alternative successive median definition 2.\n idxVec=repmat({':'},1,ndims(x));\n \n if(mod(n,2)==0)%Split the halves\n idxVec{dim}=1:(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=(n/2+1):n;\n Q3=median(x(idxVec{:}),dim);\n else%Include the median point in both the upper and the lower\n %quartiles.\n idxVec{dim}=1:ceil(n/2);\n Q1=median(x(idxVec{:}),dim);\n \n idxVec{dim}=(ceil(n/2)):n;\n Q3=median(x(idxVec{:}),dim);\n end\n \n case 3%The percentile definition, option 0.\n Q1=percentileVal(x,25,dim,0);\n Q3=percentileVal(x,75,dim,0);\n case 4%The percentile definition, option 1.\n Q1=percentileVal(x,25,dim,1);\n Q3=percentileVal(x,75,dim,1);\n case 5%The order statistic definition.\n [Q1,x]=kthOrderStat(x,1+floor(0.25*(n-1)),dim);\n Q3=kthOrderStat(x,1+ceil(0.75*(n-1)),dim);\n case 6\n idxVec=repmat({':'},1,ndims(x));\n \n x=sort(x,dim,'ascend');\n \n k50=ceil(n/2);\n k25=ceil(k50/2);\n k75=k50+ceil((n-k50)/2);\n\n idxVec{dim}=k25;\n Q1=x(idxVec{:});\n \n idxVec{dim}=k75;\n Q3=x(idxVec{:});\n otherwise\n error('Unknown definition of the interquartile range specified.')\nend\n\nIQR=Q3-Q1;\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/Robust_Statistics/interquartileRange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.775803496708466}} {"text": "%% Analyzing Neural Time Series Data\n% Matlab code for Chapter 12\n% Mike X Cohen\n% \n% This code accompanies the book, titled \"Analyzing Neural Time Series Data\" \n% (MIT Press). Using the code without following the book may lead to confusion, \n% incorrect data analyses, and misinterpretations of results. \n% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code. \n\n%% Figure 12.1\n\nload sampleEEGdata\n\ntime = -1:1/EEG.srate:1;\nf = 4; % frequency of sine wave in Hz\n\n% create sine wave (actually, a cosine wave, for reasons that will become\n% clear in Chapter 13)\nsine_wave = cos(2*pi*f.*time);\n\n% make a Gaussian\ns=4/(2*pi*f);\ngaussian_win = exp(-time.^2./(2*s^2));\n\nfigure\nplot(time,sine_wave.*gaussian_win)\n\n%% Figure 12.2\n\nfigure\nsubplot(511)\nplot(squeeze(EEG.data(47,:,1)))\naxis tight\n\nsubplot(512)\nsine_wave = cos(2*pi*12.*time);\nplot(sine_wave)\naxis tight\n\nsubplot(513)\n% boxcar envelope\nboxcar = zeros(size(sine_wave));\nmidpoint = (length(time)-1)/2;\nboxcar(midpoint-round(EEG.srate/12/5):midpoint+round(EEG.srate/12/1.25)) = 1;\nplot(sine_wave.*boxcar)\naxis tight\n\nsubplot(514)\n% boxcar envelope\nboxcar = zeros(size(sine_wave));\nmidpoint = (length(time)-1)/2;\nboxcar(midpoint-50:midpoint+50) = 1;\nplot(sine_wave.*boxcar)\naxis tight\n\nsubplot(515)\n% redefine gaussian for new sine wave\ns=1.5/(2*pi*12); gaussian_win = exp(-time.^2./(2*s^2));\nplot(time,sine_wave.*gaussian_win)\naxis tight\n\n%% Figure 12.3\n\nsrate = 500; % sampling rate in Hz\nf = 10; % frequency of the sine wave in Hz\ntime = -1:1/srate:1; % time, from -1 to 1 second in steps of 1/sampling-rate\n\nsine_wave = exp(2*pi*1i*f.*time); % complex wavelet\n\n% make a Gaussian\ns=6/(2*pi*f);\ngaussian_win = exp(-time.^2./(2*s^2));\n\n% and together they make a wavelet!\nwavelet = sine_wave .* gaussian_win;\n\n% make plots containing each component\nfigure\nsubplot(311)\nplot(time,real(sine_wave)) % only plot the real component... we�ll learn about this later\ntitle('Sine wave')\n\nsubplot(312)\nplot(time,gaussian_win) % plots the Gaussian window\ntitle('Gaussian window')\n \nsubplot(313)\nplot(time,real(wavelet)); % plots the wavelet\ntitle('My first wavelet!')\nxlabel('Time (ms)')\n\n%% Figure 12.4\n\nnum_wavelets = 80; % number of frequency bands\nlowest_frequency = 2; % in Hz\nhighest_frequency = 100; % in Hz\n\nfrequencies=linspace(lowest_frequency,highest_frequency,num_wavelets);\n% note: the \"linspace\" function creates linearly spaced numbers between the first and second \n% inputs, with the number of steps corresponding to the third input. \nfigure, plot(frequencies,'-*')\nxlabel('Frequency order')\nylabel('Frequency in Hz')\n\n\n% initialize wavelet family\nwavelet_family = zeros(num_wavelets,length(time));\n \n% Loop through frequencies and make a family of wavelets.\nfor fi=1:num_wavelets\n \n % create a sine wave at this frequency\n sinewave = exp(2*1i*pi*frequencies(fi).*time); % the \"1i\" makes it a complex wavelet\n \n % create a Gaussian window\n gaus_win = exp(-time.^2./(2*(6/(2*pi*frequencies(fi)))^2));\n \n % create wavelet via element-by-element multiplication of the sinewave and gaussian window\n wavelet_family(fi,:) = sinewave.*gaus_win;\n \n % note that you can also do this on one line:\n wavelet_family(fi,:) = exp(2*1i*pi*frequencies(fi).*time) .* exp(-time.^2./(2*(6/(2*pi*frequencies(fi)))^2));\nend\n\n% Plot a few wavelets\nfigure\nsubplot(2,1,1)\nplot(time,real(wavelet_family(1:round(rand*30):end,:))') \ntitle('A few wavelets...')\n \n% Note that in the subplot command you don't need commas if you have fewer than 10 \n% rows/cols and if you are not using any variables.\nsubplot(212)\nplot(time,real(wavelet_family(30,:)))\nhold on\nplot(time,imag(wavelet_family(30,:)),':')\ntitle('Real and imaginary parts of one wavelet')\nlegend({'real';'imaginary'})\n\n\n% finally, image the wavelet family.\nfigure\nimagesc(time,frequencies,real(wavelet_family))\naxis xy % equivalent to \"set(gca,'ydir','normal')\nxlabel('Time (s)')\nylabel('Frequency (Hz)')\n\n%% bonus feature\n\n% Running this cell will generate a movie that shows how a line -- in this\n% case, a wavelet -- goes from a line that goes up and down, to a colored\n% 'flat' line in a 2-D image. This is the principle that underlies viewing\n% time-frequency plots. \n\nfigure, set(gcf,'color','k')\nsurf(repmat(real(wavelet),2,1))\nshading interp\naxis off\naxis([0 length(time) -20 21 -1 1])\nview([ -4 4 ])\n \nfor i=4:2:90\n view([ -4 i ])\n pause(.1)\nend\n \nrotate3d\n\n%% Figure 12.5\n\n% EEG data from one trial (electrode FCz)\neegdata = squeeze(EEG.data(47,:,10));\n\n% create wavelet\ntime = -1:1/EEG.srate:1;\nf = 6; % frequency of sine wave in Hz\nsine_wave = exp(1i*2*pi*f.*time);\ns = 4.5/(2*pi*f); \ngaussian_win = exp(-time.^2./(2*s^2));\nwavelet = sine_wave .* gaussian_win;\n% half of the wavelet size, useful for chopping off edges after convolution.\nhalfwaveletsize = ceil(length(wavelet)/2);\n\n% convolve with data\n% compute Gaussian\nn_conv = length(wavelet) + EEG.pnts - 1;\n\nfft_w = fft(wavelet,n_conv);\nfft_e = fft(eegdata,n_conv);\nift = ifft(fft_e.*fft_w,n_conv)*sqrt(s)/10; % sqrt... is an empirical scaling factor that works here\nwavelet_conv_data = real(ift(halfwaveletsize:end-halfwaveletsize+1));\n\n% create filter and apply to data \n% (more on how to interpret this code in a few chapters!)\nnyquist = EEG.srate/2;\ntransition_width = 0.2; % percent\nfilter_low = 4; % Hz\nfilter_high = 8; % Hz\nffrequencies = [ 0 filter_low*(1-transition_width) filter_low filter_high filter_high*(1+transition_width) nyquist ]/nyquist;\nidealresponse = [ 0 0 1 1 0 0 ];\nfilterweights = firls(round(3*(EEG.srate/filter_low)),ffrequencies,idealresponse);\neeg_4to8 = filtfilt(filterweights,1,double(eegdata));\n\n\n\n% now plot all the pieces\nfigure\n\nplot(EEG.times,eegdata)\nhold on\nplot(EEG.times,wavelet_conv_data,'r','linew',2)\nplot(EEG.times,eeg_4to8,'m','linew',2)\nset(gca,'xlim',[-200 1200],'ydir','r')\nxlabel('Time (ms)'), ylabel('Voltage (\\muV)')\nlegend({'Raw data';'wavelet convolved';'band-pass filtered'},0)\n\n%% Figure 12.6\n\n% make a theta-band-centered wavelet\ntime = -1:1/EEG.srate:1;\nn_conv = EEG.pnts + length(time) - 1;\nn2p1 = floor(n_conv/2)+1; % n2p1 = n/2+1\n\nf = 6;\ns = 6/(2*pi*f);\nwavelet = exp(2*pi*1i*f.*time) .* exp(-time.^2./(2*s^2));\nhalfwaveletsize = ceil(length(wavelet)/2);\n\n\neegdata = squeeze(EEG.data(47,:,10));\n\nfigure\n\nsubplot(311)\nplot(EEG.times,eegdata)\nset(gca,'xlim',[-500 1200])\n\nsubplot(323)\nfft_w = fft(wavelet,n_conv);\nhz = linspace(0,EEG.srate/2,n2p1);\nplot(hz,abs(fft_w(1:n2p1))./max(abs(fft_w(1:n2p1))),'k')\nhold on\n\nfft_e = fft(eegdata,n_conv);\nhz = linspace(0,EEG.srate/2,n2p1);\nplot(hz,abs(fft_e(1:n2p1))./max(abs(fft_e(1:n2p1))),'r')\nset(gca,'xlim',[0 40],'ylim',[0 1.05])\ntitle('individual power spectra')\n\nsubplot(324)\nplot(hz,abs(fft_e(1:n2p1)).*abs(fft_w(1:n2p1)))\nset(gca,'xlim',[0 40])\n\nsubplot(313)\nplot(EEG.times,eegdata)\nhold on\nift = ifft(fft_e.*fft_w,n_conv)*sqrt(s)/10;\nplot(EEG.times,real(ift(halfwaveletsize:end-halfwaveletsize+1)),'r')\nset(gca,'xlim',[-500 1200])\n\n%% Figure 12.7\n\n% create 10 Hz wavelet (kernel)\ntime = -EEG.pnts/EEG.srate/2 : 1/EEG.srate : EEG.pnts/EEG.srate/2-1/EEG.srate;\nf = 10; % frequency of sine wave in Hz\ns = 4/(2*pi*f);\nwavelet = cos(2*pi*f.*time) .* exp(-time.^2./(2*s^2));\n\n% signal is one sine cycle\ntimeS = 0:1/EEG.srate:(1/f); % one cycle is 1/f\nsignal = sin(2*pi*f.*timeS);\n\n% now zero-pad signal\nsignal = [ zeros(1,EEG.pnts/2-length(timeS)/2) signal zeros(1,EEG.pnts/2-length(timeS)/2) ];\n\nfigure\n\n% plot waves\nsubplot(321)\nplot(wavelet)\nset(gca,'xlim',[200 length(time)-200])\n\nsubplot(323)\nplot(signal)\nset(gca,'xlim',[200 length(time)-200])\n\nsubplot(325)\nplot(conv(wavelet,signal,'same'))\nset(gca,'xlim',[200 length(time)-200],'ylim',[-12 12])\n\n\n% now plot dot products at selected phase lags\nsubplot(322)\nplot(wavelet(round(100/f)-2:end),'r')\nhold on\nplot(signal)\nset(gca,'xlim',[200 length(time)-200])\ntitle([ 'dot product: ' num2str( fix(sum(wavelet(round(100/f)-2:end).*signal(1:end-round(100/f)+3))) ) ])\n\nsubplot(324)\nplot(wavelet(round(2.3*(100/f)-2):end),'r')\nhold on\nplot(signal)\nset(gca,'xlim',[200 length(time)-200])\ntitle([ 'dot product: ' num2str( fix(sum(wavelet(round(2.3*(100/f)-2):end).*signal(1:end-round(2.3*(100/f)-3))) )) ])\n\nsubplot(326)\nplot(wavelet,'r')\nhold on\nplot(signal)\nset(gca,'xlim',[200 length(time)-200])\ntitle([ 'dot product: ' num2str( fix(sum(wavelet.*signal)) ) ])\n\n%% end\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/chapter12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7757836117145082}} {"text": "%SE2 Create planar translation and rotation transformation\n%\n% T = SE2(X, Y, THETA) is an SE(2) homogeneous transformation (3x3) \n% representing translation X and Y, and rotation THETA in the plane.\n%\n% T = SE2(XY) as above where XY=[X,Y] and rotation is zero\n%\n% T = SE2(XY, THETA) as above where XY=[X,Y]\n%\n% T = SE2(XYT) as above where XYT=[X,Y,THETA]\n%\n% See also TRANSL2, ROT2, ISHOMOG2, ISROT2, TRPLOT2.\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction t = se2(a, b, c, varargin)\n\n opt.deg = false;\n \n opt = tb_optparse(opt, varargin);\n \n if length(a) == 3\n x = a(1);\n y = a(2);\n th = a(3);\n elseif length(a) == 2\n x = a(1);\n y = a(2);\n if nargin < 2\n th = 0;\n else\n th = b;\n end\n else\n x = a;\n y = b;\n if nargin < 3\n th = 0;\n else\n th = c;\n end\n end\n\n if opt.deg \n th = th * pi/180.0;\n end\n cth = cos(th);\n sth = sin(th);\n R = [cth -sth; sth cth];\n\n t = [R [x; y]; 0 0 1];\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/se2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7757239612455394}} {"text": "function T=dewPointTemp4Pres(p,algChoice)\n%%DEWPOINTTEMP4PRES For a given partial vapor pressure of water, find the\n% dew point temperature. that is the temperature at which\n% the air would be saturated with water, in equilibrium.\n%\n%INPUTS: p The (partial) pressure of the water vapor for which the dew\n% point temperature is desired in units of Newtons per square\n% meter (Pascals).\n% algChoice An optional parameter specifying the algorithm to use. The\n% choices are\n% 0 The corrected version of the Clausius-Clapeyron equation for\n% use over land or in the upper air.\n% 1 The empirical Magnus-type equation for use over water or in\n% the upper air (-40C to 50C temperature).\n% 2 The empirical Magnus-type equation for use over ice (-80C to\n% 0C temperature)\n% If algChoice is omitted, then the default value of 0, the\n% corrected Clausius-Clapeyron equation is used. Choice 0 is taken\n% from [1]. Choices 1 and 2, are taken from [2].\n%\n%As is the case in the function dewPointPres4Temp, which is the inverse of\n%this function, formulae 0 is from [1], where the numerical inversion\n%method given in equations 44 and 45 in Section 5 of the paper are used.\n%\n%Formulas 1 and 2 are obtained by solving for the inverse of the Magnus\n%approximations given in [2]. Simple, explicit solutions for the function\n%inverses can be found.\n%\n%Note that the function dewPointPres4Temp is the inverse of this function.\n%\n%REFERENCES:\n%[1] D. Koutsoyiannis, \"Clausius-Clapeyron equation and saturation vapour\n% pressure: simple theory reconcided with practice,\" European Journal of\n% Physics, vol. 33, no. 2, pp. 295-305, Mar. 2012.\n%[2] O. A. Alduchov and R. E. Eskridge, \"Improved Magnus Form Approximation\n% of Saturation Vapor Pressure,\" Journal of Applied Meteorology, vol.\n% 35, no. 4, pp. 601-609, Apr. 1996.\n%\n%February 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(algChoice))\n algChoice=0;\nend\n\nswitch(algChoice)\n case 1\n %This evaluates the inverse of Equation 21 in the Alduchov and\n %Eskridge paper.\n \n p=p/100;%Convert to hectoPascals.\n logRat=log(p/6.1094);\n \n T=-243.04*logRat./(logRat-17.625);\n %Convert the temperature to degrees Kelvin.\n T=T-Constants.absoluteZero;\n case 2\n %This evaluates the inverse of Equation 23 in the Alduchov and\n %Eskridge paper for the saturation temperature over ice.\n \n p=p/100;%Convert to hectoPascals.\n logRat=log(p/6.1121);\n \n T=-273.86*logRat./(logRat-22.587); \n %Convert the temperature to degrees Kelvin.\n T=T-Constants.absoluteZero;\n otherwise\n %The inverse of Equation 23 in the Koutsoyiannis paper is not\n %simple to find. However, the paper provides iterative solutions in\n %the form of Equations 44 and 45 for specific values related to\n %water. For general values, the initial estimate in Equation 44 is\n %T0/T=1+1/(alpha/(R*T0)-(cL-cP)/R)*ln(p0/p);\n %and the iteration to refine the ratio is\n %T0/T_{new}=1+(R*T0/alpha)*ln(p0/p)+((cL-cP)/R)/(alpha/(R*T0))*ln(T0/T_{old})\n %where R is the specific gas constant of water vapor with units of\n %J/(kg*K), T0 is the temperature at the triple point of water, with\n %units of Kelvin, p0 is the pressure at the triple point of water\n %in hecoPascals, cP and cL are the specific heat of water vapor and\n %liquid water at constant pressure with units of J/(kg*K), and\n %alpha=L0+(cL-cP)*T0, where L0 is the latent heat of water for a\n %constant pressure at the triple point with units of J/kg.\n %\n %In the implementation here, the specific numerical from the paper\n %are used. This means that alpha has been tweaked a little bit to\n %better match their real data.\n\n numIter=27;\n\n p0=6.11657*100;%The pressure at the triple point of water in Pascals.\n T0=273.16;%The temperature at the triple point of water in Kelvin.\n \n LPRat=log(p0./p);\n \n TRat=1+1/(24.921-5.06)*LPRat;\n for curIter=1:numIter\n TRat=1+(1/(24.921))*LPRat+(5.06/24.921).*log(TRat);\n end\n T=T0./TRat;\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/Atmosphere_and_Refraction/dewPointTemp4Pres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8354835411997896, "lm_q1q2_score": 0.7756702789889449}} {"text": "function X = circle_graph_layout(G,radius)\n% CIRCLE_LAYOUT Layout the vertices of a graph on a circle\n% \n% X = circle_layout(G) generates a layout of graph with vertices uniformly\n% placed on the circle. This function does no interesting layout and just\n% places the vertices around the circle in order.\n%\n% X = circle_layout(G,radius) places the vertices with a radius other than\n% 1.0.\n%\n% Example:\n% G = cycle_graph(6);\n% X = circle_graph_layout(G);\n% gplot(G,X);\n\n% David F. Gleich\n% Copyright, Stanford University, 2008\n\n%% History\n% 2008-09-25: Initial coding\n%%\n\nif ~exist('radius','var') || isempty(radius), radius = 1.0; end;\npi = 3.14159;\nn = num_vertices(G);\nX = zeros(n,2);\nX(:,1) = radius*cos( (0:n-1)'*2*pi/n );\nX(:,2) = radius*sin( (0:n-1)'*2*pi/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/circle_graph_layout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7756702694812195}} {"text": "function [T2Hot1] = T2Hot1(X,alpha)\n%Hotelling's T-Squared test for one multivariate sample. \n%\n% Syntax: function [T2Hot1] = T2Hot1(X,alpha) \n% \n% Inputs:\n% X - multivariate data matrix. \n% alpha - significance level (default = 0.05).\n%\n% Output:\n% n - sample-size.\n% p - variables.\n% T2 - Hotelling's T-Squared statistic.\n% Chi-sqr. or F - the approximation statistic test.\n% df's - degrees' of freedom of the approximation statistic test.\n% P - probability that null Ho: is true.\n%\n%\n% Example: For the example given by Johnson and Wichern (1992, p. 183), \n% with 20 cases (n = 20) and three variables (p = 3). We are interested\n% to test if there is any difference against the expected mean vector\n% [4 50 10] at a significance level = 0.10.\n% -------------- --------------\n% x1 x2 x3 x1 x2 x3\n% -------------- --------------\n% 3.7 48.5 9.3 3.9 36.9 12.7\n% 5.7 65.1 8.0 4.5 58.8 12.3\n% 3.8 47.2 10.9 3.5 27.8 9.8\n% 3.2 53.2 12.0 4.5 40.2 8.4\n% 3.1 55.5 9.7 1.5 13.5 10.1\n% 4.6 36.1 7.9 8.5 56.4 7.1\n% 2.4 24.8 14.0 4.5 71.6 8.2\n% 7.2 33.1 7.6 6.5 52.8 10.9\n% 6.7 47.4 8.5 4.1 44.1 11.2\n% 5.4 54.1 11.3 5.5 40.9 9.4\n% -------------- --------------\n%\n% Total data matrix must be:\n% X=[3.7 48.5 9.3;5.7 65.1 8.0;3.8 47.2 10.9;3.2 53.2 12.0;3.1 55.5 9.7;\n% 4.6 36.1 7.9;2.4 24.8 14.0;7.2 33.1 7.6;6.7 47.4 8.5;5.4 54.1 11.3;\n% 3.9 36.9 12.7;4.5 58.8 12.3;3.5 27.8 9.8;4.5 40.2 8.4;1.5 13.5 10.1;\n% 8.5 56.4 7.1;4.5 71.6 8.2;6.5 52.8 10.9;4.1 44.1 11.2;5.5 40.9 9.4];\n%\n% Calling on Matlab the function: \n% T2Hot1(X)\n% Immediately it ask:\n% -Do you have an expected mean vector? (y/n):\n% For this example we must to put:\n% y (meaning 'yes')\n% Then it ask:\n% -Give me the expected mean vector:\n% Giving the mean vector:\n% [4 50 10]\n% Otherwise (n; meaning 'no') it consider a zero mean vector.\n%\n% Answer is:\n% ------------------------------------------------------------------------------------\n% Sample-size Variables T2 F df1 df2 P\n% ------------------------------------------------------------------------------------\n% 20 3 9.7388 2.9045 3 17 0.0649\n% ------------------------------------------------------------------------------------\n% Mean vectors results significant.\n%\n%\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n% And the special collaboration of the post-graduate students of the 2002:2\n% Multivariate Statistics Course: Karel Castro-Morales, Alejandro Espinoza-Tenorio,\n% Andrea Guia-Ramirez.\n%\n% Copyright (C) December 2002\n%\n% References:\n% \n% Johnson, R. A. and Wichern, D. W. (1992), Applied Multivariate Statistical Analysis.\n% 3rd. ed. New-Jersey:Prentice Hall. pp. 180-181,199-200.\n%\n\nif nargin < 1, \n error('Requires at least one input argument.'); \nend;\n\nif nargin < 2, \n alpha = 0.05; \nend; \n\nif (alpha <= 0 | alpha >= 1)\n fprintf('Warning: significance level must be between 0 and 1\\n');\n return;\nend;\n\n[n,p]=size(X);\n\nask=input('Do you have an expected mean vector? (y/n): ','s');\nif ask=='y'\n mu=input('Give me the expected mean vector: ');\nelse\n mu=zeros([1,p]);\nend;\n \nif n <= p,\n error('Warning: requires that sample-size (n) must be greater than the number of variables (p).');\n return;\nelse\n \n m=mean(X); %Mean vector from data matrix X.\n S=cov(X); %Covariance matrix from data matrix X.\n T2=n*(m-mu)*inv(S)*(m-mu)'; %Hotelling's T-Squared statistic.\n \n if n >= 50 %Chi-square approximation. \n X2=T2;\n v=p; %Degrees of freedom.\n P=1-chi2cdf(X2,v); %Probability that null Ho: is true.\n disp(' ')\n fprintf('----------------------------------------------------------------------------\\n');\n disp(' Sample-size Variables T2 Chi-sqr. df P')\n fprintf('----------------------------------------------------------------------------\\n');\n fprintf('%8.i%13.i%15.4f%14.4f%11.i%14.4f\\n\\n',n,p,T2,X2,v,P);\n fprintf('----------------------------------------------------------------------------\\n');\n if P >= alpha;\n disp('Mean vectors results not significant.');\n else\n disp('Mean vectors results significant.');\n end;\n else %F approximation.\n F=(n-p)/((n-1)*p)*T2; \n v1=p; %Numerator degrees of freedom.\n v2=n-p; %Denominator degrees of freedom.\n P=1-fcdf(F,v1,v2); %Probability that null Ho: is true.\n disp(' ')\n fprintf('-------------------------------------------------------------------------------------\\n');\n disp(' Sample-size Variables T2 F df1 df2 P')\n fprintf('-------------------------------------------------------------------------------------\\n');\n fprintf('%8.i%13.i%15.4f%11.4f%9.i%14.i%14.4f\\n\\n',n,p,T2,F,v1,v2,P);\n fprintf('-------------------------------------------------------------------------------------\\n');\n if P >= alpha;\n disp('Mean vectors results not significant.');\n else\n disp('Mean vectors results significant.');\n end;\n end;\nend;\n\nreturn;\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/ref functions/HotellingT2/T2Hot1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7756702694812194}} {"text": "function [ as, bs, cs ] = sphere_triangle_vertices_to_sides ( r, v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_VERTICES_TO_SIDES computes spherical triangle sides.\n%\n% Discussion:\n%\n% We can use the ACOS system call here, but the ARC_COSINE routine\n% will automatically take care of cases where the input argument is\n% (usually slightly) out of bounds.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 April 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real V1(3), V2(3), V3(3), the vertices of the spherical\n% triangle.\n%\n% Output, real AS, BS, CS, the (geodesic) length of the sides\n% of the triangle.\n%\n dim_num = 3;\n\n as = r * r8_acos ( v2(1:dim_num)' * v3(1:dim_num) / r.^2 );\n bs = r * r8_acos ( v3(1:dim_num)' * v1(1:dim_num) / r.^2 );\n cs = r * r8_acos ( v1(1:dim_num)' * v2(1:dim_num) / r.^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_triangle_vertices_to_sides.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7756101141773728}} {"text": "function [ mO ] = ImageFilteringFrequencyDomain( mI, mH, paddingMode )\n% ----------------------------------------------------------------------------------------------- %\n% [ mO ] = ImageFilteringFrequencyDomain( mI, mH, paddingMode )\n% Applies Image Filtering in the Frequency Domain.\n% Input:\n% - mI - Input Image.\n% Structure: Matrix.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - mH - Filtering Kernel.\n% Structure: Matrix.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - paddingMode - Padding Mode.\n% Sets whether the padding is by Zeros,\n% Symmetric, Replicate or Circular mode.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, 4}.\n% Output:\n% - mI - Output Image.\n% Structure: Matrix.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References:\n% 1. MATLAB's 'imfilter()' - https://www.mathworks.com/help/images/ref/imfilter.html.\n% Remarks:\n% 1. A\n% TODO:\n% 1. \n% Release Notes:\n% - 1.0.000 04/04/2019 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nPADDING_MODE_ZEROS = 1;\nPADDING_MODE_SYMMETRIC = 2;\nPADDING_MODE_REPLICATE = 3;\nPADDING_MODE_CIRCULAR = 4;\n\nnumRows = size(mI, 1);\nnumCols = size(mI, 2);\n\nnumRowsKernel = size(mH, 1);\nnumColsKernel = size(mH, 2);\n\nradiusRows = floor(numRowsKernel / 2);\nradiusCols = floor(numColsKernel / 2);\n\nvPadRadius = [radiusRows; radiusCols];\n\nswitch(paddingMode)\n case(PADDING_MODE_ZEROS)\n % Size of the Linear Convolution Support\n numRowsL = numRows + numRowsKernel - 1;\n numColsL = numCols + numColsKernel - 1;\n \n % Equivalent of Full Linear Convolution (Zero Padding Built In).\n % This is due the fact padding with zeors at the end with symmetric\n % assumption and shifting yield correct result.\n mO = ifft2(fft2(mI, numRowsL, numColsL) .* fft2(mH, numRowsL, numColsL), 'symmetric');\n \n firstRowIDx = ceil((numRowsKernel + 1) / 2);\n firstColIDx = ceil((numColsKernel + 1) / 2);\n \n mO = mO(firstRowIDx:(firstRowIDx + numRows - 1), firstColIDx:(firstColIDx + numCols - 1));\n case({PADDING_MODE_SYMMETRIC, PADDING_MODE_REPLICATE})\n % Padding to apply \"Linear Convolution\" on the image pixels.\n mI = PadArray2D(mI, vPadRadius, paddingMode);\n \n numRowsPad = numRows + (2 * radiusRows);\n numColsPad = numCols + (2 * radiusCols);\n \n mHC = mH;\n mHC(numRowsPad, numColsPad) = 0;\n mHC = circshift(mHC, [-radiusRows, -radiusCols]);\n \n mO = ifft2(fft2(mI) .* fft2(mHC), 'symmetric');\n mO = mO((radiusRows + 1):(radiusRows + numRows), (radiusCols + 1):(radiusCols + numCols));\n case(PADDING_MODE_CIRCULAR)\n mHC = mH;\n mHC(numRows, numCols) = 0;\n mHC = circshift(mHC, [-radiusRows, -radiusCols]);\n \n mO = ifft2(fft2(mI) .* fft2(mHC), 'symmetric');\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/Q56407/ImageFilteringFrequencyDomain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7755581917661653}} {"text": "function a = c8mat_house ( n, x )\n\n%*****************************************************************************80\n%\n%% C8MAT_HOUSE constructs a complex Householder elementary reflector matrix.\n%\n% Formula:\n%\n% A = I - ( 2 * X * hermitian ( X ) ) / ( conjg ( X ) * X )\n%\n% Example:\n%\n% N = 5, X = ( 1, 1, 1, 0, -1 )\n%\n% 1/2 -1/2 -1/2 0 1/2\n% -1/2 1/2 -1/2 0 1/2\n% -1/2 -1/2 1/2 0 1/2\n% 0 0 0 1 0\n% 1/2 1/2 1/2 0 1/2\n%\n% Properties:\n%\n% A is hermitian: hermitian ( A ) = A.\n%\n% Because A is hermitian, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is unitary: hermitian ( A ) * A = A * hermitian ( A ) = I.\n%\n% inverse ( A ) = A.\n%\n% det ( A ) = -1.\n%\n% LAMBDA(1) = -1.\n%\n% If X is the vector used to define A, then X is an eigenvector\n% of A associated with the eigenvalue of -1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, complex X(N), the vector that defines the\n% Householder matrix.\n%\n% Output, complex A(N,N), the matrix.\n%\n a = c8mat_identity ( n );\n\n xdot = real ( x(1:n) * x(1:n)' );\n\n if ( 0.0 < xdot )\n\n for i = 1 : n\n for j = 1 : n\n a(i,j) = a(i,j) - 2.0 * x(i) * x(j)' / xdot;\n end\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/c8mat_house.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7755444331390382}} {"text": "function d = bayesgauss(X,C,M,P)\n%BAYESGAUSS Bayes classifier for Gaussian patterns.\n% D = BAYESGAUSS(X,C,M,P) computes Bayes Gaussian decision functions\n% of the n-dimensional patterns in the rows of X. C is an array of\n% size n-by-n-by-Nc containing Nc covariance matrices of size n-by-n,\n% where Nc is the number of classes. M is a matrix of size Nc-by-n,\n% whose rows are the corresponding mean vectors. A covariance matrix\n% and a mean vector must be specified for each class. X is of size\n% K-by-n, where K is the number of patterns to be classified. P is a\n% 1-by-Nc vector containing the probabilities of occurrence of each\n% class. If P is not included in the argument, the classes are assumed\n% to be equally likely.\n%\n% In the output, D is a column vector of length K. Its ith element is\n% the class number assigned to the ith vector in X during\n% classification.\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% Verify the number of inputs.\nnarginchk(3,4) \nn = size(C,1); % Dimension of patterns.\n\n% Protect against the possibility that the class number is included\n% as an (n + 1)th element of the vectors.\nX = double(X(:,1:n));\n% Number of pattern classes.\nNc = size(C,3);\n% Number of patterns to classify.\nK = size(X,1); \nif nargin == 3\n P(1:Nc) = 1/Nc; % Classes assumed equally likely.\nelse\n if sum(P) ~= 1 \n error('Elements of P must sum to 1.'); \n end\nend\n% Compute the determinants.\nDM = zeros(1,Nc); % Preallocate memory for loop speed.\nfor J = 1:Nc \n DM(J) = det(C(:,:,J)); \nend\n \n% Evaluate the decision functions. Note the use of function mahalanobis\n% discussed in Section 14.2.\nD = zeros(K,Nc); % Preallocate memory for loop speed.\nfor J = 1:Nc\n Cm = C(:,:,J);\n Mm = M(J,:);\n L(1:K,1) = log(P(J));\n DET(1:K,1) = 0.5*log(DM(J));\n if P(J) == 0\n D(1:K,J) = -inf;\n else\n D(:,J) = L - DET - 0.5*mahalanobis(X,Cm,Mm);\n end\nend\n\n% Find the coordinates of the maximum value in each row. The location of\n% a maximum gives the class of the corresponding pattern vector.\n[i,j] = find(D == max(D,[],2));\n\n% Re-use X. Its first element in a row is the pattern number, and the\n% second is the class to which the pattern was assigned.\nX = [i,j]; \n\n% Eliminate multiple classifications of the same patterns. Since the\n% class assignment when two or more decision functions give the same\n% value is arbitrary, we need to keep only one. Function unique\n% eliminates duplicates and returns the array sorted by rows. This\n% re-establishes the original order of the patterns.\n[~,idx] = unique(X(:,1));\nX = X(idx,:);\n% X is now sorted, with the 2nd column giving the class of the pattern\n% number in the 1st col.; i.e., X(j,1) refers to the jth input pattern,\n% and X(j,2) is its class number.\n\n% Output the result of classification. d is a column vector with length\n% equal to the total number of input patterns. The elements of d are the\n% classes into which the patterns (in their original order) were\n% classified.\nd = X(:,2);\n\n \n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/bayesgauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.77545827447563}} {"text": "function [X,names]=elipcyl \n% [X,names]=elipcyl defines elliptic\n% cylinder coordinates\nsyms et ps z real; names=[et ps z];\nX=[cosh(et)*cos(ps); \n sinh(et)*sin(ps); z];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15903-curvilinear-coordinates/cc/elipcyl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7754478565777105}} {"text": "function [R, G, B] = Lab2RGB(L, a, b)\n% function [R, G, B] = Lab2RGB(L, a, b)\n% Lab2RGB takes matrices corresponding to L, a, and b in CIELab space\n% and transforms them into RGB. This transform is based on ITU-R \n% Recommendation BT.709 using the D65 white point reference.\n% and the error in transforming RGB -> Lab -> RGB is approximately\n% 10^-5. 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\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 = fY > T1;\nfY = (~YT) .* (L / 903.3) + YT .* fY;\nY = fY;\n\n% Alter fY slightly for further calculations\nfY = YT .* (fY .^ (1/3)) + (~YT) .* (7.787 .* fY + 16/116);\n\n% Compute X\nfX = a / 500 + fY;\nXT = fX > T2;\nX = (XT .* (fX .^ 3) + (~XT) .* ((fX - 16/116) / 7.787));\n\n% Compute Z\nfZ = fY - b / 200;\nZT = fZ > T2;\nZ = (ZT .* (fZ .^ 3) + (~ZT) .* ((fZ - 16/116) / 7.787));\n\nX = X * 0.950456;\nZ = Z * 1.088754;\n\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(MAT * [X; Y; Z], 1), 0);\n\nR = reshape(RGB(1,:), M, N) * 255;\nG = reshape(RGB(2,:), M, N) * 255;\nB = reshape(RGB(3,:), M, N) * 255; \n\nif ((nargout == 1) | (nargout == 0))\n R = uint8(round(cat(3,R,G,B)));\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/external/lab2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175634, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7754020517824382}} {"text": "% Example 6.4: Regressor selection problem\n% Section 6.3.1, Figure 6.7\n% Original by Lieven Vandenberghe\n% Adapted for CVX Argyris Zymnis - 10/2005\n%\n% Solves\n% minimize ||A*x-b||_2\n% subject to card(x) <= k\n%\n% where card(x) denotes the number of nonzero elements in x,\n% by first solving (for some value of alpha close to ||x_ln||_1)\n% minimize ||A*x-b||_2\n% subject to ||x||_1 <= alpha\n%\n% and iteratively decreasing alpha so as to get card(x) = k\n% The sparsity pattern is then fixed in A and b and\n% minimize ||A*x-b||_2\n%\n% is solved\n\nrand('state',0);\nrandn('state',0);\n\nm = 10;\nn = 20;\n\nA = randn(m,n);\nb = A*[randn(round(m/2),1); zeros(n-round(m/2),1)];\nb = b + 0.1*norm(b)*randn(m,1);\n\nif (1) %%%%%%%%%%%%\n\n% tradeoff curve for heuristic\n%\n% min. ||Ax-b||_2\n% s.t. ||x||_1 <= alpha\n\nxln = A'*((A*A')\\b);\nlnorm = norm(xln,1);\nnopts = 100;\nalphas = linspace(0,lnorm,nopts);\nresiduals_heur = norm(b);\ncard_heur = 0;\n\n\nfor k=2:(nopts-1)\n alpha = alphas(k);\n\n cvx_begin quiet\n variable x(n)\n minimize(norm(A*x-b))\n subject to\n norm(x,1) <= alpha; %#ok\n cvx_end\n\n x(abs(x) < 1e-3*max(abs(x))) = 0; %#ok\n ind = find(abs(x));\n sparsity = length(ind);\n fprintf(1,'Current sparsity pattern k = %d \\n',sparsity);\n x = zeros(n,1); x(ind) = A(:,ind)\\b;\n card_heur = [card_heur, sparsity]; %#ok\n residuals_heur = [residuals_heur, norm(A*x-b)]; %#ok\nend;\n\nobj1 = norm(b);\nobj2 = 0;\nobj1 %#ok\n\ni=1;\nfor k=1:m-1\n if any(card_heur == k)\n obj2(i+1) = k; %#ok\n obj1(i+1) = min(residuals_heur(card_heur ==k));\n i=i+1;\n end;\nend;\nobj2(i) = m; obj1(i) = 0;\n\nend; %%%%%%%%%%%%%%%%%%%\n\n\n% globally optimal tradeoff\n\n\nif (1) %%%%%%%%%%%%%\n\nbestx = zeros(n,m);\nbestres = zeros(1,m);\n\nfor k=1:m-1\n k %#ok\n % enumerate sparsity patterns with exactly k nonzeros\n bestres(k) = Inf;\n ind = 1:k %#ok\n nocases = 1;\n done = 0;\n while ~done\n done = 1;\n for i=0:k-1\n if (ind(k-i) < n-i),\n ind(k-i:k) = ind(k-i)+(1:i+1);\n done = 0;\n break;\n end;\n end;\n if done, break; end;\n x = zeros(n,1);\n x(ind) = A(:,ind)\\b;\n if (norm(A*x-b) < bestres(k)),\n bestres(k) = norm(A*x-b);\n bestx(:,k) = x;\n end;\n nocases = nocases + 1;\n end;\n nocases %#ok\n factorial(n)/(factorial(n-k)*factorial(k)) %#ok\nend;\n\nx = A\\b;\nbestres(m) = norm(A*x-b);\nbestres = [norm(b) bestres];\n\nend; %%%%%%%%%\n\nfigure\nhold off\nobj1dbl =[];\nobj2dbl =[];\nfor i=1:length(obj1)-1\n obj1dbl = [obj1dbl, obj1(i), obj1(i)]; %#ok\n obj2dbl = [obj2dbl, obj2(i), obj2(i+1)]; %#ok\nend;\nobj1dbl = [obj1dbl, obj1(length(obj1))];\nobj2dbl = [obj2dbl, obj2(length(obj1))];\n\nbestobj1 = bestres;\nbestobj2 = 0:m;\nbestobj1dbl =[];\nbestobj2dbl =[];\nfor i=1:length(bestobj1)-1\n bestobj1dbl = [bestobj1dbl, bestobj1(i), bestobj1(i)]; %#ok\n bestobj2dbl = [bestobj2dbl, bestobj2(i), bestobj2(i+1)]; %#ok\nend;\nbestobj1dbl = [bestobj1dbl, bestobj1(length(bestobj1))];\nbestobj2dbl = [bestobj2dbl, bestobj2(length(bestobj1))];\n\nplot(obj1dbl,obj2dbl,'-', bestobj1dbl, bestobj2dbl,'--');\nhold on\nplot(obj1,obj2,'o', bestobj1, bestobj2,'o');\naxis([0 ceil(2*norm(b))/2 0 m+1])\nxlabel('x');\nylabel('y');\nhold off\n\n%print -deps sparse_regressor_global_helv.eps\n%save regressor_results\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch06_approx_fitting/regressor_cvx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225518, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7753737469698534}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_gregorian2 ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_GREGORIAN2 converts a JED to a Gregorian YMDF date.\n%\n% Discussion:\n%\n% The theory behind this routine is very clean. The Gregorian\n% calendar has cycles of 1, 4, 100 and 400 years, and we can\n% analyze a date by determining where it lies within these cycles.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 July 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Reingold, Nachum Dershowitz, Stewart Clamen,\n% Calendrical Calculations, II: Three Historical Calendars,\n% Software - Practice and Experience,\n% Volume 23, Number 4, pages 383-404, April 1993.\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F, the YMDF date.\n%\n g1 = 365;\n g4 = 1461;\n g100 = 36524;\n g400 = 146097;\n\n jed_epoch = epoch_to_jed_gregorian ( );\n\n j = floor ( jed - jed_epoch );\n f1 = ( jed - jed_epoch ) - j;\n\n d0 = j;\n n400 = 0;\n\n while ( d0 < 0 )\n d0 = d0 + g400;\n n400 = n400 - 1;\n end\n\n n400 = n400 + floor ( d0 / g400 );\n d1 = i4_modp ( d0, g400 );\n\n n100 = floor ( d1 / g100 );\n d2 = i4_modp ( d1, g100 );\n\n n4 = floor ( d2 / g4 );\n d3 = i4_modp ( d2, g4 );\n\n n1 = floor ( d3 / g1 );\n d4 = i4_modp ( d3, g1 );\n\n if ( n100 == 4 || n1 == 4 )\n j1 = 366;\n y1 = 400 * n400 + 100 * n100 + 4 * n4 + n1;\n else\n j1 = d4 + 1;\n y1 = 400 * n400 + 100 * n100 + 4 * n4 + n1 + 1;\n end\n%\n% Any year before 1 AD must be moved one year further back, since\n% this calendar does not include a year 0.\n%\n y1 = y_astronomical_to_common ( y1 );\n\n [ y, m, d, f ] = yjf_to_ymdf_gregorian ( y1, j1, f1 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calpak/jed_to_ymdf_gregorian2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7753450202240867}} {"text": "function oev = eci2orb1 (mu, r, v)\n\n% convert eci state vector to six classical orbital\n% elements via equinoctial elements\n\n% input\n\n% mu = central body gravitational constant (km**3/sec**2)\n% r = eci position vector (kilometers)\n% v = eci velocity vector (kilometers/second)\n\n% output\n\n% oev(1) = semimajor axis (kilometers)\n% oev(2) = orbital eccentricity (non-dimensional)\n% (0 <= eccentricity < 1)\n% oev(3) = orbital inclination (radians)\n% (0 <= inclination <= pi)\n% oev(4) = argument of perigee (radians)\n% (0 <= argument of perigee <= 2 pi)\n% oev(5) = right ascension of ascending node (radians)\n% (0 <= raan <= 2 pi)\n% oev(6) = true anomaly (radians)\n% (0 <= true anomaly <= 2 pi)\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\npi2 = 2.0 * pi;\n\n% position and velocity magnitude\n\nrmag = norm(r);\n\nvmag = norm(v);\n\n% position unit vector\n\nrhat = r / rmag;\n\n% angular momentum vectors\n\nhv = cross(r, v);\n\nhhat = hv / norm(hv);\n\n% eccentricity vector\n\nvtmp = v / mu;\n\necc = cross(vtmp, hv);\n\necc = ecc - rhat;\n\n% semimajor axis\n\nsma = 1.0 / (2.0 / rmag - vmag * vmag / mu);\n\np = hhat(1) / (1.0 + hhat(3));\n\nq = -hhat(2) / (1.0 + hhat(3));\n\nconst1 = 1.0 / (1.0 + p * p + q * q);\n\nfhat(1) = const1 * (1.0 - p * p + q * q);\nfhat(2) = const1 * 2.0 * p * q;\nfhat(3) = -const1 * 2.0 * p;\n\nghat(1) = const1 * 2.0 * p * q;\nghat(2) = const1 * (1.0 + p * p - q * q);\nghat(3) = const1 * 2.0 * q;\n\nh = dot(ecc, ghat);\n\nxk = dot(ecc, fhat);\n\nx1 = dot(r, fhat);\n\ny1 = dot(r, ghat);\n\n% orbital eccentricity\n\neccm = sqrt(h * h + xk * xk);\n\n% orbital inclination\n\ninc = 2.0 * atan(sqrt(p * p + q * q));\n\n% true longitude\n\nxlambdat = atan3(y1, x1);\n\n% check for equatorial orbit\n\nif (inc > 0.00000001)\n raan = atan3(p, q);\nelse\n raan = 0.0;\nend\n\n% check for circular orbit\n\nif (eccm > 0.00000001)\n argper = mod(atan3(h, xk) - raan, pi2);\nelse\n argper = 0.0;\nend\n\n% true anomaly\n\ntanom = mod(xlambdat - raan - argper, pi2);\n\n% load orbital element vector\n\noev(1) = sma;\noev(2) = eccm;\noev(3) = inc;\noev(4) = argper;\noev(5) = raan;\noev(6) = tanom;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39179-two-impulse-phasing-analysis/eci2orb1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7753318402228919}} {"text": "%% Example 9.18: Hermite expansion of Benes SDE\n%\n% Copyright: \n% 2018 - Simo Särkkä and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%% Plot the Hermite expansion example\n\n x0 = 1/2;\n trans_dens = @(xx,t) 1./sqrt(2*pi*t).*cosh(xx)./cosh(x0).*exp(-0.5*t).*exp(-1./(2*t).*(xx-x0).^2);\n\n %\n % % Symbolic solution (requires the Symbolic Math Toolbox)\n % syms x;\n % f = matlabFunction(tanh(x));\n % df = matlabFunction(diff(tanh(x),1));\n % d2f = matlabFunction(diff(tanh(x),2));\n % d3f = matlabFunction(diff(tanh(x),3));\n % d4f = matlabFunction(diff(tanh(x),4));\n % d5f = matlabFunction(diff(tanh(x),5));\n %\n \n f = @(x) tanh(x);\n df = @(x) 1 - tanh(x)^2;\n d2f = @(x) 2*tanh(x)*(tanh(x)^2 - 1);\n d3f = @(x) -2*(tanh(x)^2 - 1)^2 - 4*tanh(x)^2*(tanh(x)^2 - 1);\n d4f = @(x) 16*tanh(x)*(tanh(x)^2 - 1)^2 + 8*tanh(x)^3*(tanh(x)^2 - 1);\n d5f = @(x) -16*(tanh(x)^2 - 1)^3 - 16*tanh(x)^4*(tanh(x)^2 - 1) - 88*tanh(x)^2*(tanh(x)^2 - 1)^2;\n \n xx = -15:0.1:15;\n\n figure(1); clf; hold on\n \n % Solve at t=2\n t = 2;\n herm_x = herm_exp(f(x0),df(x0),d2f(x0),d3f(x0),d4f(x0),d5f(x0),t,xx,x0);\n\n % Exact density\n fill(xx,trans_dens(xx,t),1,'FaceColor',[.7 .7 .7],'EdgeColor',[.7 .7 .7])\n \n % Series approximation\n plot(xx,herm_x,'-k','LineWidth',1)\n\n ylim([-0.21 0.25]); \n legend('Exact density','Series approximation','Location','south');\n xlabel('$x$');\n ylabel('$p(x)$');\n\n figure(2); clf; hold on\n\n % Solve at t=5 \n t = 5;\n herm_x = herm_exp(f(x0),df(x0),d2f(x0),d3f(x0),d4f(x0),d5f(x0),t,xx,x0);\n\n % Exact density\n fill(xx,trans_dens(xx,t),1,'FaceColor',[.7 .7 .7],'EdgeColor',[.7 .7 .7])\n \n % Series approximation\n plot(xx,herm_x,'-k','LineWidth',1)\n \n ylim([-0.21 0.25]);\n xlabel('$x$');\n ylabel('$p(x)$');\n ", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch09_ex18_hermite_expansion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7751978144027417}} {"text": "% EX_ARTICLE_SECTION_512: short example with a non-isoparametric approach, and a non-NURBS geometry.\n%\n% Example to solve the problem\n%\n% - div ( grad (u)) = (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2) in Omega\n% u = 0 on Gamma\n%\n% with Omega = (1 < x^2+y^2 < 4) & (x > 0) & (y > 0)\n% and exact solution u = (x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x))\n%\n% This solves the example of Section 5.1.2 in the article\n%\n% C. De Falco, A. Reali, R. Vazquez\n% GeoPDEs: a research tool for IsoGeometric Analysis of PDEs\n%\n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2011, 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n\ngeometry = geo_load ({@ring_polar_map, @ring_polar_map_der});\n\nknots = kntuniform ([9 9], [4 4], [3 3]);\n[qn, qw] = msh_set_quad_nodes (knots, msh_gauss_nodes ([5 5]));\nmsh = msh_cartesian (knots, qn, qw, geometry);\n\nspace = sp_bspline (knots, [4 4], msh);\n\nmat = op_gradu_gradv_tp (space, space, msh);\nrhs = op_f_v_tp (space, msh, @(x, y) (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2));\n\ndrchlt_dofs = [];\nfor iside = 1:4\n drchlt_dofs = union (drchlt_dofs, space.boundary(iside).dofs);\nend\nint_dofs = setdiff (1:space.ndof, drchlt_dofs);\n\nu = zeros (space.ndof, 1);\nu(int_dofs) = mat(int_dofs, int_dofs) \\ rhs(int_dofs);\n\nsp_to_vtk (u, space, geometry, [20 20], 'laplace_solution.vts', 'u')\nerr = sp_l2_error (space, msh, u, @(x,y)(x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x)))\n\n%!demo\n%! ex_article_section_512;\n\n%!test\n%! geometry = geo_load ({@ring_polar_map, @ring_polar_map_der});\n%! knots = kntuniform ([9 9], [4 4], [3 3]);\n%! [qn, qw] = msh_set_quad_nodes (knots, msh_gauss_nodes ([5 5]));\n%! msh = msh_cartesian (knots, qn, qw, geometry);\n%! space = sp_bspline (knots, [4 4], msh);\n%! mat = op_gradu_gradv_tp (space, space, msh, @(x, y) ones (size (x))); \n%! rhs = op_f_v_tp (space, msh, @(x, y) (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2));\n%! drchlt_dofs = [];\n%! for iside = 1:4\n%! drchlt_dofs = union (drchlt_dofs, space.boundary(iside).dofs);\n%! end\n%! int_dofs = setdiff (1:space.ndof, drchlt_dofs);\n%! u = zeros (space.ndof, 1);\n%! u(int_dofs) = mat(int_dofs, int_dofs) \\ rhs(int_dofs);\n%! err = sp_l2_error (space, msh, u, @(x,y)(x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x)));\n%! assert (msh.nel, 64)\n%! assert (space.ndof, 144)\n%! assert (err, 2.82510645627626e-07, 1e-16)", "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/ex_article_section_512.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7751443703704851}} {"text": "function S = eliminator(n, ROWS)\n%\n%ELIMINATOR\n% \n% Returns a matrix S that is called eliminator.\n% S is a matrix such that S*A (assuming that this product \n% exists) will not contain rows listed in row vector ROWS.\n% Numbers of rows in ROWS can be unsorted.\n%\n% Example: \n% A = hilb(6);\n% S = eliminator(6, [4 6 2]);\n% B = S * A; \n% Matrix B will contain rows 1, 3, 5 from the matrix A,\n% matrix B will not contain rows 2, 4, 6 from matrix A.\n% \n% (C) 2000 Igor Podlubny, Blas Vinagre, Tomas Skovranek \n%\n% See:\n% [1] I. Podlubny, A.Chechkin, T. Skovranek, YQ Chen, \n% B. M. Vinagre Jara, \"Matrix approach to discrete \n% fractional calculus II: partial fractional differential \n% equations\". http://arxiv.org/abs/0811.1355\n% [2] R.G. Cooke, Infinite Matrices and Sequence Spaces, \n% MacMillan and Co., London, 1950. 347 pp.\n\n\n\nS = eye(n); \nr = sort(ROWS);\nm = size(r,2);\n\nfor k = m:(-1):1\n if r(k)-1 == 0 \n S = S((r(k)+1):(size(S,1)-k+1),:);\n elseif r(k) == size(S,1)\n S = S(1:(r(k)-1),:);\n else\n S = [S(1:(r(k)-1),:); S((r(k)+1):(size(S,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/22071-matrix-approach-to-discretization-of-odes-and-pdes-of-arbitrary-real-order/eliminator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7751443630653263}} {"text": "function pdf = bernoulli_pdf ( x, a )\n\n%*****************************************************************************80\n%\n%% BERNOULLI_PDF evaluates the Bernoulli PDF.\n%\n% Discussion:\n%\n% PDF(X)(A) = A**X * ( 1.0D+00 - A )**( X - 1 )\n%\n% X = 0 or 1.\n%\n% The Bernoulli PDF describes the simple case in which a single trial\n% is carried out, with two possible outcomes, called \"success\" and\n% \"failure\"; the probability of success is A.\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, integer X, the number of successes on a single trial.\n% X = 0 or 1.\n%\n% Input, real A, the probability of success on one trial.\n% 0.0D+00 <= A <= 1.0.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0 )\n pdf = 0.0;\n elseif ( x == 0 )\n pdf = 1.0 - a;\n elseif ( x == 1 )\n pdf = a;\n else\n pdf = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/bernoulli_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7751443612297907}} {"text": "function pp = sphere_imp_point_project_3d ( r, center, p )\n\n%*****************************************************************************80\n%\n%% SPHERE_IMP_POINT_PROJECT_3D projects a point onto an implicit sphere in 3D.\n%\n% Discussion:\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% 23 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real CENTER(3), the center of the sphere.\n%\n% Input, real P(3), a point.\n%\n% Output, real PP(3), the projected point.\n%\n dim_num = 3;\n\n if ( r == 0.0 )\n\n pp(1:dim_num) = center(1:dim_num);\n\n elseif ( p(1:dim_num) == center(1:dim_num) )\n\n pp(1:dim_num) = center(1:dim_num) + r / sqrt ( dim_num );\n\n else\n\n norm = sqrt ( sum ( ( p(1:dim_num) - center(1:dim_num) ).^2 ) );\n \n pp(1:dim_num) = center(1:dim_num) + r * ( p(1:dim_num) - center(1:dim_num) ) / norm;\n\n end\n\n return\nend\n", "meta": {"author": "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_point_project_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7751073431668792}} {"text": "function w = w0_func(z,N)\n% Based on:\n% FADDEEVA Faddeeva function\n% W = FADDEEVA(Z) is the Faddeeva function, aka the plasma dispersion\n% function, for each element of Z. The Faddeeva function is defined as:\n%\n% w(z) = exp(-z^2) * erfc(-j*z)\n%\n% where erfc(x) is the complex complementary error function.\n%\n% W = FADDEEVA(Z,N) can be used to explicitly specify the number of terms\n% to truncate the expansion (see (13) in [1]). N = 16 is used as default.\n%\n% Example:\n% x = linspace(-10,10,1001); [X,Y] = meshgrid(x,x); \n% W = faddeeva(complex(X,Y)); \n% figure; \n% subplot(121); imagesc(x,x,real(W)); axis xy square; caxis([-1 1]); \n% title('re(faddeeva(z))'); xlabel('re(z)'); ylabel('im(z)'); \n% subplot(122); imagesc(x,x,imag(W)); axis xy square; caxis([-1 1]);\n% title('im(faddeeva(z))'); xlabel('re(z)'); ylabel('im(z)'); \n%\n% Reference:\n% [1] J.A.C. Weideman, \"Computation of the Complex Error Function,\" SIAM\n% J. Numerical Analysis, pp. 1497-1518, No. 5, Vol. 31, Oct., 1994 \n% Available Online: http://www.jstor.org/stable/2158232\n\n% Called by: crbs6.m, crbs7.m\n\n\nif nargin<2, N = []; end\nif isempty(N), N = 50; end\n\nw = zeros(size(z)); % initialize output\n\n%%%%%\n% for purely imaginary-valued inputs, use erf as is if z is real\nidx = real(z)==0; %\nw(idx) = exp(-z(idx).^2).*erfc(imag(z(idx)));\n\nif all(idx), return; end\nidx = ~idx;\n\n%%%%%\n% for complex-valued inputs\n\n% make sure all points are in the upper half-plane (positive imag. values)\nidx1 = idx & imag(z)<0;\nz(idx1) = conj(z(idx1));\n\nM = 2*N;\nM2 = 2*M;\nk = (-M+1:1:M-1)'; % M2 = no. of sampling points.\nL = sqrt(N/sqrt(2)); % Optimal choice of L.\n\ntheta = k*pi/M;\nt = L*tan(theta/2); % Variables theta and t.\nf = exp(-t.^2).*(L^2+t.^2);\nf = [0; f]; % Function to be transformed.\na = real(fft(fftshift(f)))/M2; % Coefficients of transform.\na = flipud(a(2:N+1)); % Reorder coefficients.\n\nZ = (L+1i*z(idx))./(L-1i*z(idx));\np = polyval(a,Z); % Polynomial evaluation.\nw(idx) = 2*p./(L-1i*z(idx)).^2 + (1/sqrt(pi))./(L-1i*z(idx)); % Evaluate w(z).\n\n% convert the upper half-plane results to the lower half-plane if necesary\nw(idx1) = conj(2*exp(-z(idx1).^2) - w(idx1));\n\nw=-w*sqrt(-1)*pi; % converts to 'w0_func' used in crbs_molecular.m\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29108-coherent+spontaneous-rayleigh-brillouin-scattering-spectra/s6s7_RBS/w0_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7751073270201677}} {"text": "% Mathematics Q561696\n% https://math.stackexchange.com/questions/561696\n% Solving Non Negative Least Squares by Analogy with Least Squares (MATLAB)\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 05/08/2017\n% * First release.\n\n\n%% General Parameters\n\nrun('InitScript.m');\n\nfigureIdx = 0; %= 0;\ncvx_end\n\ndisp([' ']);\ndisp(['CVX Solution Summary']);\ndisp(['The CVX Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(cvx_optval)]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX.'), ' ]']);\ndisp([' ']);\n\n\n%% Solution by Projected Gradient Descent\n\nvX = zeros([numCols, 1]);\n\nfor ii = 1:numIterations\n vX = vX - ((stepSize / sqrt(ii)) * mA.' * (mA * vX - vB));\n vX = max(vX, 0);\nend\n\nobjVal = sum((mA * vX - vB) .^ 2);\n\ndisp([' ']);\ndisp(['Projected Gradient Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(objVal)]);\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/Mathematics/Q561696/Q561696.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7751009852952141}} {"text": "function [ w, seed ] = direction_uniform_nd ( dim_num, seed )\n\n%*****************************************************************************80\n%\n%% DIRECTION_UNIFORM_ND generates a random direction vector in ND.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real W(DIM_NUM), a random direction vector,\n% with unit norm.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n\n%\n% Get N values from a standard normal distribution.\n%\n [ w, seed ] = r8vec_normal_01 ( dim_num, seed );\n%\n% Compute the length of the vector.\n%\n norm = sqrt ( sum ( w(1:dim_num).^2 ) );\n%\n% Normalize the vector.\n%\n w(1:dim_num) = w(1:dim_num) / norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/direction_uniform_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7751009762802306}} {"text": "function Cn = correlation_image(Y,sz,d1,d2,flag_norm, K)\n\n% construct correlation image based on neighboing pixels\n% Y: raw data\n% sz: define the relative location of neighbours. it can be scalar, 2\n% element vector or a binary matrix\n% scalar: number of nearest neighbours, either 4 or 8, default 4\n% 2 element vector: [rmin, rmax], the range of neighbours. the\n% distance between the neighbour and the pixel is d, dmin <= r <\n% dmax.\n% matrix: a squared matrix (2k+1)*(2k+1)indicating the location of neighbours\n% d1,d2: spatial dimensions\n% flag_norm: indicate whether Y has been normalized and centered ( 1 is\n% yes, 0 is no)\n% K: scalar, the rank of the random matrix for projection\n\n% Author: Eftychios A. Pnevmatikakis, Simons Foundation, 2015\n% with modifications from Pengcheng Zhou, Carnegie Mellon University, 2015.\n% It uses convolution and random projection for speeding up the\n% computation.\n\n%% preprocess the raw data\nif ~exist('flag_norm', 'var') || isempty(flag_norm)\n flag_norm = false;\nend\n\nif ~exist('sz', 'var') || isempty(sz)\n sz = [0,1,0; 1,0,1; 0,1,0];\nend\n\n% center data \nY = bsxfun(@minus, double(Y), mean(Y, ndims(Y))); \nif ~ismatrix(Y)\n [d1, d2, T] = size(Y);\nelse\n T = size(Y, 2);\nend\n\nif exist('K', 'var') && (~isempty(K))\n Y = double(reshape(Y, [], T))*randn(T, K); \n % centering\n mY = mean(Y,2);\n Y = bsxfun(@minus, Y, mY); % normalizing\n flag_norm = false; \nend\nif ~flag_norm\n sY = sqrt(mean(Y.*Y, ndims(Y)));\n sY(sY==0) = 1; % avoid nan values\n Y = bsxfun(@times, Y, 1./sY);\nend\nif ismatrix(Y)\n Y = reshape(Y, d1, d2, []);\nend\n\n%% construct a matrix indicating location of the matrix\nif isscalar(sz)\n if sz == 8 % 8 nearest neighbours\n sz = [1,1,1; 1,0,1; 1,1,1];\n elseif sz==4\n sz = [0,1,0; 1,0,1; 0,1,0];\n end\nelseif length(sz(:)) == 2\n % the specified neighbours has a distance within the domain [dmin,\n % dmax)\n sz = ceil(sz);\n dmin = min(sz); dmax = max(sz);\n rsub = (-dmax+1):(dmax-1); % row subscript\n csub = rsub; % column subscript\n [cind, rind] = meshgrid(csub, rsub);\n R = sqrt(cind.^2+rind.^2);\n sz = (R>=dmin) .* (R Use nanmean(M(:)) to get the average global Moran's I.\n%\n% See Anselin (1995, 'LISA.', Geogr. Analysis 27(2),p.93f) for details on \n% standardized variables in calculation of local Moran's I. \n%\n% EXAMPLE: M = moransI(rand(20,20),ones(5,5),'true')\n%\n% Felix Hebeler, Geography Dept.,de University Zurich, March 2006.\n\n%% Check if standardising should be done\nif exist('s','var')\n if strcmp(s,'true');\n grid=zscore(grid);\n elseif strcmp(s,'false')\n %do nothing\n else\n error('Invalid option for s: set [true] to calculated zscores to determine local Moran or leave blank if values are already standardized.');\n end\nend\nif (mod(size(W,1),2)| mod(size(W,2),2))~=1\n error('Weight matrix W needs to have uneven size (eg. 5x5)') \nend\n%% Do local Morans I calc of the grid.\nM = NaN(size(grid,1),size(grid,2));\nwsx=floor(size(W,1)/2);\nwsy=floor(size(W,2)/2);\n% Do local morans I calc for moving window ws\nfor row=1+wsy:1:size(grid,1)-wsy;\n for col=1+wsx:1:size(grid,2)-wsx;\n M(row,col) = get_moran(grid(row-wsx:row+wsx,col-wsy:col+wsy),W);\n end\nend\n\n%% calculate local Moran's I\nfunction m=get_moran(raster,W)\nncols= size(raster,2);\nnrows= size(raster,1);\nzi = raster(ceil(nrows/2),ceil(ncols/2));% value of center cell (note: no weight applied!)\nif (isnan(zi));\n m=NaN; \n return; \nend;\nraster=raster.* W; % Weight values in window\nraster(ceil(nrows/2),ceil(ncols/2))=0; %set center cell to zero to exclude zi from sum\nzj = nansum(raster(:)); % sum of weighted values excluding zi\nm = zi * zj; % calculate local Moran's I and return", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13663-morans-i/morans_I.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7749910771086699}} {"text": "function [dcos] = triang2(pp,tt)\n%TRIANG2 calc. enclosed angles for a 2-simplex triangulation\n%embedded in the two-dimensional plane.\n% [ADEG] = TRIANG2(VERT,TRIA) returns the enclosed angles\n% associated with each triangle, where ADEG is a T-by-3\n% array of the angles subtended at each vertex, VERT is a\n% V-by-2 array of XY coordinates, and TRIA is a T-by-3 ar-\n% ray of vertex indexing, where each row defines a triang-\n% le, such that VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and\n% VERT(TRIA(II,3),:) are the coordinates of the II-TH tri-\n% angle. Angles are returned in degrees.\n%\n% See also TRISCR2, TRIAREA, TRIBAL2\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 08/07/2018\n\n%---------------------------------------------- basic checks\n if (~isnumeric(pp) || ~isnumeric(tt) )\n error('triang2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ndims(tt) ~= +2 )\n error('triang2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(pp,2)~= +2 || size(tt,2) < +3 )\n error('triang2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nnod = size(pp,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(tt(:,1:3))) < +1 || ...\n max(max(tt(:,1:3))) > nnod )\n error('triang2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n\n%----------------------------------- compute enclosed angles\n dcos = zeros(size(tt,1),3) ;\n\n ev12 = pp(tt(:,2),:)-pp(tt(:,1),:) ;\n ev23 = pp(tt(:,3),:)-pp(tt(:,2),:) ;\n ev31 = pp(tt(:,1),:)-pp(tt(:,3),:) ;\n\n lv11 = sqrt(sum(ev12.^2,2));\n lv22 = sqrt(sum(ev23.^2,2));\n lv33 = sqrt(sum(ev31.^2,2));\n\n ev12 = ev12 ./ ...\n lv11(:,ones(1,size(pp,2)));\n ev23 = ev23 ./ ...\n lv22(:,ones(1,size(pp,2)));\n ev31 = ev31 ./ ...\n lv33(:,ones(1,size(pp,2)));\n\n dcos(:,1) = sum(-ev12.*ev23,2);\n dcos(:,2) = sum(-ev23.*ev31,2);\n dcos(:,3) = sum(-ev31.*ev12,2);\n\n dcos(:,1) = max(-1.,dcos(:,1));\n dcos(:,1) = min(+1.,dcos(:,1));\n dcos(:,2) = max(-1.,dcos(:,2));\n dcos(:,2) = min(+1.,dcos(:,2));\n dcos(:,3) = max(-1.,dcos(:,3));\n dcos(:,3) = min(+1.,dcos(:,3));\n\n dcos = acos(dcos) * 180. / pi ;\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-cost/triang2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7749227730515751}} {"text": "function vecCross = crossMat(vec)\n%\n% Computes the cross-product matrix of a 3x1 vector\n%\t\n if(size(vec,1) ~= 3 || size(vec,2) ~= 1)\n error('Input vector must be 3x1');\n end\n\n vecCross = [ 0, \t\t-vec(3), \tvec(2);\n\t\t\t\t vec(3),\t0,\t\t\t-vec(1);\n\t\t\t\t -vec(2),\tvec(1),\t\t0 ];\nend", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/msckf/utils/crossMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7749227635559764}} {"text": "function [tfr,t,f]=tfrideal(iflaws,t,N,trace)\n%TFRIDEAL Ideal TFR for given instantaneous frequency laws.\n%\t[TFR,T,F]=TFRIDEAL(IFLAWS,T,N,TRACE) generates the ideal\n%\ttime-frequency representation corresponding to the\n%\tinstantaneous frequency laws of the components of a signal. \n%\n%\tIFLAWS : (M,P)-matrix where each column corresponds to\n%\t\t the instantaneous frequency law of an (M,1)-signal,\n%\t\t These P signals do not need to be present at the same time.\n%\t\t The values of IFLAWS must be between 0 and 0.5.\n%\tT : the time instant(s) (default : 1:M).\n%\tN : number of frequency bins (default : M).\n%\tTRACE : if nonzero, the progression of the algorithm is shown\n% (default : 0).\n%\tTFR : output time-frequency matrix, of size (N,length(t)).\n%\t\t If nargout=0, a contour plot of TFR is automatically\n%\t\t displayed on the screen.\n%\tF : vector of normalized frequencies.\n%\n%\tExample :\n% N=140; t=0:N-1; [x1,if1]=fmlin(N,0.05,0.3); \n% [x2,if2]=fmsin(70,0.35,0.45,60);\n% if2=[zeros(35,1)*NaN;if2;zeros(35,1)*NaN];\n% tfrideal([if1 if2]); \n%\n%\tSee also PLOTIFL, PLOTSID, and all the time-frequency \n% representations listed in the CONTENTS file (TFR*)\n\n%\tO. Lemoine, F. Auger - March, April 1996.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin==0),\n error('at least one parameter required');\nend;\n\n[ifrow,ifcol]=size(iflaws);\n\nif (nargin==1),\n t=1:ifrow; N=ifrow; trace=0;\nelseif (nargin==2),\n N=ifrow; trace=0;\nelseif (nargin==3),\n trace=0;\nend;\n\n[trow,tcol]=size(t);\nif (trow~=1),\n error('T must only have one row'); \nend;\n\ntfr=zeros(N,tcol);\n\nif any(any(iflaws>0.5)) | any(any(iflaws<0)),\n error('The values of IFLAWS must be between 0 and 0.5');\nend\n\nif trace, disp('Ideal time-frequency distribution'); end;\n\nfor icol=1:tcol,\n if trace, disprog(icol,tcol,10); end;\n ti= t(icol); \n for fi=1:ifcol,\n if isnan(iflaws(ti,fi)),\n tfr(fi,icol)=NaN;\n else\n tfr(round(iflaws(ti,fi)*2*(N-1))+1,icol)=1;\n end\n end\nend;\n\nif (nargout==0),\n f=(0:N-1)/(2*N); \n axes(gca); contour(t,f,tfr,1,'k');\n xlabel('Time'); ylabel('Normalized frequency');\n title('Ideal time-frequency representation');\n grid;\nelseif (nargout==3),\n f=(0.5*(0:N-1)/N)';\nend;\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrideal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7748293306887819}} {"text": "function [f, e] = fv(B, nk, thmax, noplot)\n%FV Field of values (or numerical range).\n% FV(A, NK, THMAX) evaluates and plots the field of values of the\n% NK largest leading principal submatrices of A, using THMAX\n% equally spaced angles in the complex plane.\n% The defaults are NK = 1 and THMAX = 16.\n% (For a `publication quality' picture, set THMAX higher, say 32.)\n% The eigenvalues of A are displayed as `x'.\n% Alternative usage: [F, E] = FV(A, NK, THMAX, 1) suppresses the\n% plot and returns the field of values plot data in F, with A's\n% eigenvalues in E. Note that NORM(F,INF) approximates the\n% numerical radius,\n% max {abs(z): z is in the field of values of A}.\n\n% Theory:\n% Field of values FV(A) = set of all Rayleigh quotients. FV(A) is a\n% convex set containing the eigenvalues of A. When A is normal FV(A) is\n% the convex hull of the eigenvalues of A (but not vice versa).\n% z = x'Ax/(x'x), z' = x'A'x/(x'x)\n% => REAL(z) = x'Hx/(x'x), H = (A+A')/2\n% so MIN(EIG(H)) <= REAL(z) <= MAX(EIG(H)),\n% with equality for x = corresponding eigenvectors of H. For these x,\n% RQ(A,x) is on the boundary of FV(A).\n%\n% Based on an original routine by A. Ruhe.\n%\n% References:\n% R. A. Horn and C. R. Johnson, Topics in Matrix Analysis, Cambridge\n% University Press, 1991; sec. 1.5.\n% A. S. Householder, The Theory of Matrices in Numerical Analysis,\n% Blaisdell, New York, 1964; sec. 3.3.\n% C. R. Johnson, Numerical determination of the field of values of a\n% general complex matrix, SIAM J. Numer. Anal., 15 (1978),\n% pp. 595-602.\n\nif nargin < 2 | isempty(nk), nk = 1; end\nif nargin < 3 | isempty(thmax), thmax = 16; end\nthmax = thmax - 1; % Because code below uses thmax + 1 angles.\n\niu = sqrt(-1);\n[n, p] = size(B);\nif n ~= p, error('Matrix must be square.'), end\nf = [];\nz = zeros(2*thmax+1,1);\ne = eig(B);\n\n% Filter out cases where B is Hermitian or skew-Hermitian, for efficiency.\nif isequal(B,B')\n\n f = [min(e) max(e)];\n\nelseif isequal(B,-B')\n\n e = imag(e);\n f = [min(e) max(e)];\n e = iu*e; f = iu*f;\n\nelse\n\nfor m = 1:nk\n\n ns = n+1-m;\n A = B(1:ns, 1:ns);\n\n for i = 0:thmax\n th = i/thmax*pi;\n Ath = exp(iu*th)*A; % Rotate A through angle th.\n H = 0.5*(Ath + Ath'); % Hermitian part of rotated A.\n [X, D] = eig(H);\n [lmbh, k] = sort(real(diag(D)));\n z(1+i) = rq(A,X(:,k(1))); % RQ's of A corr. to eigenvalues of H\n z(1+i+thmax) = rq(A,X(:,k(ns))); % with smallest/largest real part.\n end\n\n f = [f; z];\n\nend\n% Next line ensures boundary is `joined up' (needed for orthogonal matrices).\nf = [f; f(1,:)];\n\nend\nif thmax == 0; f = e; end\n\nif nargin < 4\n\n ax = cpltaxes(f);\n plot(real(f), imag(f)) % Plot the field of values\n axis(ax);\n axis('square');\n\n hold on\n plot(real(e), imag(e), 'x') % Plot the eigenvalues too.\n hold off\n\nend\n\nfunction z = rq(A,x)\n%RQ Rayleigh quotient.\n% RQ(A,x) is the Rayleigh quotient of A and x, x'*A*x/(x'*x).\n\nz = x'*A*x/(x'*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/base/utilities/matrixcomp/fv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.7748293050198903}} {"text": "function y = geo_mean( x, dim, w )\n\n%GEO_MEAN Geometric mean.\n% Y=GEO_MEAN(X), where X is a vector, computes the geometrix mean of X. If any\n% of the elements of X are negative, then Y=-Inf. Otherwise, it is equivalent\n% to Y=PROD(X).^(1/LENGTH(X)). All elements must be real.\n%\n% For matrices, GEO_MEAN(X) is a row vector containing the geometric means of\n% the columns. For N-D arrays, GEO_MEAN(X) is an array of the geometric means\n% taken along the first non-singleton dimension of X.\n%\n% GEO_MEAN(X,DIM) takes the geometric mean along the dimension DIM of X.\n%\n% GEO_MEAN(X,DIM,W), where W is a vector of nonnegative integers, computes a\n% weighted geometric mean Y = PROD(X.^W)^(1/SUM(W)). This is more efficient\n% than replicating the values of X W times. Note that W must be a vector,\n% even if X is a matrix, and its length must be the same as SIZE(X,DIM).\n%\n% Disciplined convex programming information:\n% GEO_MEAN is concave and nondecreasing; therefore, when used in CVX\n% specifications, its argument must be concave.\n\n%\n% Check arguments\n%\n\nerror( nargchk( 1, 3, nargin ) );\nif ~isreal( x ), \n error( 'First argument must be real.' ); \nelseif nargin < 2,\n dim = cvx_default_dimension( size( x ) );\nelseif ~cvx_check_dimension( dim ),\n error( 'Second argument must be a positive integer.' );\nend\nsx = size( x );\nnx = sx( dim );\n\n%\n% Third argument check\n%\n\nif nargin < 3 || isempty( w ),\n w = [];\nelseif numel( w ) ~= length( w ) || ~isnumeric( w ) || ~isreal( w ) || any( w < 0 ) || any( w ~= floor( w ) ),\n error( 'Third argument must be a vector of nonnegative integers.' );\nelseif length( w ) ~= nx,\n error( 'Third argument must be a vector of length %d.', nx );\nelse\n w = reshape( w, 1, nx );\nend\n\nif nx == 0,\n sx( dim ) = 1;\n y = ones( sx );\nelse\n if nx == 1,\n y = x;\n elseif isempty( w ) || ~any( diff( w ) ),\n y = exp( sum( log( max( x, realmin ) ), dim ) * ( 1 / nx ) );\n elseif dim == 1,\n y = exp( w * log( max( x, realmin ) ) * ( 1 / sum( w ) ) );\n else\n pvec = [ dim, 1 : dim - 1, dim + 1 : ndims( x ) ];\n y = ipermute( exp( w * log( max( permute( x, pvec ), realmin ) ) * ( 1 / sum( w ) ) ), pvec );\n end\n xmin = min( x, [], dim );\n y( xmin < 0 ) = -Inf;\n y( xmin == 0 ) = 0;\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/geo_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7748169705073545}} {"text": "function p = part_table ( n )\n\n%*****************************************************************************80\n%\n%% PART_TABLE tabulates the number of partitions of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the integer to be partitioned.\n% N must be positive.\n%\n% Output, integer P(1:N+1), P(I+1) is the number of partitions of I.\n%\n offset = 1;\n\n p = zeros ( n + 1, 1 );\n\n p(0+offset) = 1;\n p(1+offset) = 1;\n\n for i = 2 : n\n\n sign = 1;\n psum = 0;\n w = 1;\n j = 1;\n wprime = w + j;\n\n while ( w < n )\n\n if ( 0 <= i - w )\n if ( sign == 1 )\n psum = psum + p(i-w+offset);\n else\n psum = psum - p(i-w+offset);\n end\n end\n\n if ( wprime <= i )\n\n if ( sign == 1 )\n psum = psum + p(i-wprime+offset);\n else\n psum = psum - p(i-wprime+offset);\n end\n\n end\n\n w = w + 3 * j + 1;\n j = j + 1;\n wprime = w + j;\n sign = - sign;\n\n end\n\n p(i+offset) = psum;\n\n end\n\n return\nend\n", "meta": {"author": "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_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7748169550064362}} {"text": "function [rectx,recty,area,perimeter] = minboundrect(x,y,metric)\n% minboundrect: Compute the minimal bounding rectangle of points in the plane\n% usage: [rectx,recty,area,perimeter] = minboundrect(x,y,metric)\n%\n% arguments: (input)\n% x,y - vectors of points, describing points in the plane as\n% (x,y) pairs. x and y must be the same lengths.\n%\n% metric - (OPTIONAL) - single letter character flag which\n% denotes the use of minimal area or perimeter as the\n% metric to be minimized. metric may be either 'a' or 'p',\n% capitalization is ignored. Any other contraction of 'area'\n% or 'perimeter' is also accepted.\n%\n% DEFAULT: 'a' ('area')\n%\n% arguments: (output)\n% rectx,recty - 5x1 vectors of points that define the minimal\n% bounding rectangle.\n%\n% area - (scalar) area of the minimal rect itself.\n%\n% perimeter - (scalar) perimeter of the minimal rect as found\n%\n%\n% Note: For those individuals who would prefer the rect with minimum\n% perimeter or area, careful testing convinces me that the minimum area\n% rect was generally also the minimum perimeter rect on most problems\n% (with one class of exceptions). This same testing appeared to verify my\n% assumption that the minimum area rect must always contain at least\n% one edge of the convex hull. The exception I refer to above is for\n% problems when the convex hull is composed of only a few points,\n% most likely exactly 3. Here one may see differences between the\n% two metrics. My thanks to Roger Stafford for pointing out this\n% class of counter-examples.\n%\n% Thanks are also due to Roger for pointing out a proof that the\n% bounding rect must always contain an edge of the convex hull, in\n% both the minimal perimeter and area cases.\n%\n%\n% See also: minboundcircle, minboundtri, minboundsphere\n%\n%\n% default for metric\nif (nargin<3) || isempty(metric)\n metric = 'a';\nelseif ~ischar(metric)\n error 'metric must be a character flag if it is supplied.'\nelse\n % check for 'a' or 'p'\n metric = lower(metric(:)'); \n ind = strmatch(metric,{'area','perimeter'}); \n if isempty(ind) \n error 'metric does not match either ''area'' or ''perimeter'''\n end\n \n % just keep the first letter.\n metric = metric(1);\nend\n\n% preprocess data\nx=x(:);\ny=y(:);\n\n% not many error checks to worry about\nn = length(x); \nif n~=length(y) \n error 'x and y must be the same sizes'\nend\n\n\n\n% if var(x)==0\n \n% start out with the convex hull of the points to\n% reduce the problem dramatically. Note that any\n% points in the interior of the convex hull are\n% never needed, so we drop them.\nif n>3 \n \n %%%%%%%%%%%%%%%%%%%%%%%%%\n if (var(x)== 0|| var(y)==0)\n if var(x)== 0\n x = [x-1;x(1); x+1 ];\n y = [y ;y(1);y];\n flag = 1;\n else\n y = [y-1;y(1); y+1 ];\n x = [x ;x(1);x];\n flag = 1;\n end\n \n else\n flag = 0;\n %%%%%%%%%%%%%%%%%%%%%%\n edges = convhull(x,y); % 'Pp' will silence the warnings\n \n end\n\n % exclude those points inside the hull as not relevant\n % also sorts the points into their convex hull as a\n % closed polygon\n \n %%%%%%%%%%%%%%%%%%%%\n if flag == 0 \n %%%%%%%%%%%%%%%%%%%% \n \n x = x(edges);\n y = y(edges);\n %%%%%%%%%%%%%%%%%%\n end\n %%%%%%%%%%%%%\n % probably fewer points now, unless the points are fully convex\n nedges = length(x) - 1; \nelseif n>1\n % n must be 2 or 3\n nedges = n;\n x(end+1) = x(1);\n y(end+1) = y(1);\nelse\n % n must be 0 or 1\n nedges = n;\nend\n\n% now we must find the bounding rectangle of those\n% that remain.\n\n% special case small numbers of points. If we trip any\n% of these cases, then we are done, so return.\nswitch nedges\n case 0\n % empty begets empty\n rectx = [];\n recty = [];\n area = [];\n perimeter = [];\n return\n case 1\n % with one point, the rect is simple.\n rectx = repmat(x,1,5);\n recty = repmat(y,1,5);\n area = 0;\n perimeter = 0;\n return\n case 2\n % only two points. also simple.\n rectx = x([1 2 2 1 1]);\n recty = y([1 2 2 1 1]);\n area = 0;\n perimeter = 2*sqrt(diff(x).^2 + diff(y).^2);\n return\nend\n% 3 or more points.\n\n% will need a 2x2 rotation matrix through an angle theta\nRmat = @(theta) [cos(theta) sin(theta);-sin(theta) cos(theta)];\n\n% get the angle of each edge of the hull polygon.\nind = 1:(length(x)-1);\nedgeangles = atan2(y(ind+1) - y(ind),x(ind+1) - x(ind));\n% move the angle into the first quadrant.\nedgeangles = unique(mod(edgeangles,pi/2));\n\n% now just check each edge of the hull\nnang = length(edgeangles); \narea = inf; \nperimeter = inf;\nmet = inf;\nxy = [x,y];\nfor i = 1:nang \n % rotate the data through -theta \n rot = Rmat(-edgeangles(i));\n xyr = xy*rot;\n xymin = min(xyr,[],1);\n xymax = max(xyr,[],1);\n \n % The area is simple, as is the perimeter\n A_i = prod(xymax - xymin);\n P_i = 2*sum(xymax-xymin);\n \n if metric=='a'\n M_i = A_i;\n else\n M_i = P_i;\n end\n \n % new metric value for the current interval. Is it better?\n if M_i= 1583\n%\n% Syntax: \tISLEAP(YEAR)\n% \n% Inputs:\n% YEAR - Year of interest (default = current year). \n% You can input a vector of years.\n% Outputs:\n% Logical vector.\n%\n% Example: \n%\n% Calling on Matlab the function: isleap\n%\n% Answer is: 0\n%\n%\n% Calling on Matlab the function: x=isleap([2007 2008])\n%\n% Answer is:\n% x = 0 1\n%\n% Created by Giuseppe Cardillo\n% giuseppe.cardillo-edta@poste.it\n% Modified after Simon Jan suggestions\n% To cite this file, this would be an appropriate format:\n% Cardillo G. (2007) Isleap: a simple routine to test if a year is a leap\n% year.\n% http://www.mathworks.com/matlabcentral/fileexchange/14172\n\n\n\n%Input Error handling\nswitch nargin\n case 0\n c=clock; Year=c(1); clear c\n case 1\n if ~isvector(Year) || ~all(isnumeric(Year)) || ~all(isfinite(Year)) || isempty(Year)\n error('Warning: Year values must be numeric and finite')\n end\n if ~isequal(Year,round(Year))\n error('Warning: Year values must be integer')\n end\n L=Year-1583;\n if L(L<0)\n error('Warning: Every value of Year must be >1582')\n end\n otherwise\n error('stats:Isleap:TooMuchInputs','Year must be a scalar or a vector.');\nend\n\n% The Gregorian calendar has 97 leap years every 400 years: \n% Every year divisible by 4 is a leap year. \n% However, every year divisible by 100 is not a leap year. \n% However, every year divisible by 400 is a leap year after all. \n% So, 1700, 1800, 1900, 2100, and 2200 are not leap years, \n% but 1600, 2000, and 2400 are leap years.\nx = ~mod(Year, 4) & (mod(Year, 100) | ~mod(Year, 400)); \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/14172-isleap-function/isleap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7747682336795813}} {"text": "function ex2 (n)\n%EX2: create an n-by-n 2D mesh, four different ways\n\n% Example:\n% ex2\n% See also: cs_demo\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nif (nargin < 1)\n n = 30 ;\nend\n\nsubplot (1,2,1) ;\n\n% method 1: create an n-by-n 2D mesh for the 2nd difference operator\ntic\nii = zeros (5*n^2, 1) ;\njj = zeros (5*n^2, 1) ;\nxx = zeros (5*n^2, 1) ;\nk = 1 ;\nfor j = 0:n-1\n for i = 0:n-1\n s = j*n+i + 1 ;\n ii (k:k+4) = [(j-1)*n+i j*n+(i-1) j*n+i j*n+(i+1) (j+1)*n+i ] + 1 ;\n jj (k:k+4) = [s s s s s] ;\n xx (k:k+4) = [-1 -1 4 -1 -1] ;\n k = k + 5 ;\n end\nend\n\n% remove entries beyond the boundary\nkeep = find (ii >= 1 & ii <= n^2 & jj >= 1 & jj <= n^2) ;\nii = ii (keep) ;\njj = jj (keep) ;\nxx = xx (keep) ;\nA = sparse (ii,jj,xx) ;\nt1 = toc ; disp (t1) ;\n% subplot (2,2,1) ; \nspy (A)\ntitle (sprintf ('%d-by-%d 2D mesh\\n', n, n)) ;\n\n% method 2, using no for loops\ntic\nnn = 1:n^2 ;\ni2 = [nn-n ; nn-1 ; nn ; nn+1 ; nn+n] ;\nj2 = repmat (nn, 5, 1) ;\nx2 = repmat ([-1 -1 4 -1 -1]', 1, n^2) ;\nkeep = find (i2 >= 1 & i2 <= n^2 & j2 >= 1 & j2 <= n^2) ;\ni2 = i2 (keep) ;\nj2 = j2 (keep) ;\nx2 = x2 (keep) ;\nC = sparse (i2,j2,x2) ;\nt2 = toc ; disp (t2) ;\n\n% subplot (2,2,2) ; plot (j2) ;\n% title ('2D fast j2') ;\ndisp (A-C) ;\n\nany (ii-i2)\nany (jj-jj)\n\n% method 3: create an n-by-n-by-n 3D mesh for the 2nd difference operator\ntic\n[A, keep, ii, jj, xx] = mesh3d1 (n) ;\nii = ii (keep) ;\njj = jj (keep) ;\nxx = xx (keep) ;\nt3 = toc ; disp (t3) ;\ntic\nE = sparse (ii,jj,xx) ;\nt3b = toc ; disp (t3b) ;\nsubplot (1,2,2) ; spy (E) ;\ntitle (sprintf ('%d-by-%d-by-%d 3D mesh\\n', n, n, n)) ;\n\n% method 4, using no for loops\ntic\nnn = 1:n^3 ;\ni2 = [nn-n^2 ; nn-n ; nn-1 ; nn ; nn+1 ; nn+n ; nn+n^2] ;\nj2 = repmat (nn, 7, 1) ;\nx2 = repmat ([-1 -1 -1 6 -1 -1 -1]', 1, n^3) ;\nkeep = find (i2 >= 1 & i2 <= n^3 & j2 >= 1 & j2 <= n^3) ;\ni2 = i2 (keep) ;\nj2 = j2 (keep) ;\nx2 = x2 (keep) ;\nt4 = toc ; disp (t4) ;\ntic\nF = sparse (i2,j2,x2) ;\nt4b = toc ; disp (t4b) ;\ndisp (E-F) ;\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/ex2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7747682314483857}} {"text": "% EX_MAXWELL_SRC_PERIODIC_SQUARE: solve Maxwell source problem in the unit square.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nclear problem_data \n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_square.txt';\n% The domain must also have the right continuity conditions on the periodic\n% sides, otherwise the convergence rate may deteriorate. \n% See the example in ex_laplace_square_periodic.\n\n% Type of boundary conditions\nproblem_data.nmnn_sides = [];\nproblem_data.drchlt_sides = [3 4];\nproblem_data.periodic_directions = [1];\n\n% Physical parameters\nproblem_data.c_stiff = @(x, y) ones(size(x));\nproblem_data.c_mass = @(x, y) pi^2 * ones(size(x));\n\n% Source and boundary terms\nproblem_data.f = @(x, y) cat(1, zeros (1, size (x, 1), size (x, 2)), ...\n reshape (17*pi^2*sin(4*pi*x), [1, size(x)]));\nproblem_data.g = @(x, y, ind) zeros (2, size (x, 1), size (x, 2));\nproblem_data.h = @(x, y, ind) zeros (2, size (x, 1), size (x, 2));\n\n% Exact solution (optional)\nproblem_data.uex = @(x, y) cat(1, zeros (1, size (x, 1), size (x, 2)), ...\n reshape ( sin(4*pi*x), [1, size(x)]));\nproblem_data.curluex = @(x, y) 4*pi*cos(4*pi*x);\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nclear method_data \nmethod_data.degree = [3 3]; % Degree of the bsplines\nmethod_data.regularity = [2 2]; % Regularity of the splines\nmethod_data.nsub = [9 9]; % Number of subdivisions\nmethod_data.nquad = [4 4]; % Points for the Gaussian quadrature rule\n\n% 3) CALL TO THE SOLVER\n[geometry, msh, space, u] = solve_maxwell_src (problem_data, method_data);\n\n% 4) POST-PROCESSING\nvtk_pts = {linspace(0, 1, 30), linspace(0, 1, 30)};\n% 4.1) EXPORT TO PARAVIEW\noutput_file = 'maxwell_square_periodic_Deg3_Reg2_Sub8';\nfprintf ('The result is saved in the file %s \\n \\n', output_file);\nsp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')\n\n% 4.2) Plot in Matlab. Comparison with the exact solution\n[eu, F] = sp_eval (u, space, geometry, vtk_pts);\n[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));\neu2 = problem_data.uex (X, Y);\n\nsubplot(1,2,1)\nquiver (X, Y, squeeze(eu(1,:,:)), squeeze(eu(2,:,:)))\naxis equal tight\ntitle('Computed solution')\nylim([0,1]); xlim([0,1]);\nsubplot(1,2,2)\nquiver (X, Y, squeeze(eu2(1,:,:)), squeeze(eu2(2,:,:)))\naxis equal tight\ntitle('Exact solution')\nylim([0,1]); xlim([0,1]);\n\n[error_hcurl, error_l2] = ...\n sp_hcurl_error (space, msh, u, problem_data.uex, problem_data.curluex)\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/examples/maxwell/ex_maxwell_src_periodic_square.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7747682281759731}} {"text": "%% Defining Tensorial Properties\n%\n% Physical laws describe the relationship between physical properties. The\n% most simplest laws are linear ones and are of the form\n%\n% $$ y = \\mathbf A x $$\n%\n% where $x$ and $y$ are the physical properties and $\\mathbf A$ is a\n% material constant. In a typical example $y$ could be the force applied to\n% a spring, $x$ the displacement and $A$ describes the stiffnes of the\n% spring which is essentially Hooks law.\n%\n% As soon as we consider more general forces and displacements they can not\n% be described anymore by scalar numbers $x$ and $y$ but vectors or\n% matrices are required. In its most general form the displacment is\n% describes by a $\\sigma_{ij}$ and the\n% force is described by a stiffness matrix $\\varepsilon_{kl}$. In this setting\n% the linear relationship between the two matrices is described by the\n% $\\mathbf\n% C_{ijkl}$ which can be seen as a 4 dimensional generalization of a matrix.\n%\n% More, general a tensor of rank $r$ is a \"matrix\" of dimension $r$. If\n% $r=0$ we speek of scalars, if $r=1$ these are vectors and for $r=2$ they\n% are classical $3 \\times 3$ matrices. \n%\n% In the following we explain how tensors of arbitrary rank can be defined\n% in MTEX. Independent of the rank any tensor is represented in MTEX by a\n% variable of type @tensor.\n%\n%\n%% Scalars (tensors of zero rank)\n%\n% In physics, properties like temperature or density are not connected \n% to any specific direction of the body they are measured. These \n% non-directional physical quantities are called scalars, and they are\n% defined by a single number. In MTEX, a scalar is defined by:\n\nM = 5;\nt = tensor(M,'rank',0)\n\n%% Vectors (tensors of first rank)\n% \n% In contrast to scalars, other physical quantities can only be defined in\n% reference to a specific direction. If we need to specify completely the\n% mechanical force acting into a point for example, we need to specify \n% the magnitude and its direction. As an alternative, we can choose three\n% mutually perpendicular axes (A1,A2 and A3) and give the vector components\n% along them. In MTEX, this is done by:\n\nt = tensor([1;2;3],'rank',1)\n\n%%\n% where 1, 2 and 3 are the components related to the axes A1, A2 and A3.\n% As rank 1 tensors are essentialy vectors we can freely convert tensors to\n% @vector3d and vice verca. \n\n% define a tensor from a vector\nt = tensor(vector3d.X)\n\n% convert a tensor into a vector\nvector3d(t)\n\n%% Matrices (tensors of second rank)\n%\n% We have now to expand the idea of a vector to three-dimensional space.\n% Let's take the example of stress (force per unit of area). Imagine a cube\n% of material subjected to load as shown below. As can be seen, one can\n% measure ther stresses in this cube in various directions, and in various\n% planes. These measurements will for a second rank sensor, where each\n% component is associated with a pair of axes, taken in an specific order.\n% The generalized second rank stress tensor can be written as\n%\n% $$\n% \\sigma_{ij} = \n% \\left[\\begin{array}{ccc}\n% \\sigma_{11} & \\sigma_{12} & \\sigma_{13} \\\\\n% \\sigma_{21} & \\sigma_{22} & \\sigma_{23} \\\\\n% \\sigma_{31} & \\sigma_{32} & \\sigma_{33} \\\\\n% \\end{array}\\right]\n% $$\n%\n% In MTEX, a second-rank tensor where only the main diagonal components are\n% of interest is defined as\n\nt = tensor(diag([1,2,3]), 'rank',2)\n\n%%\n% If all the components are of interest, the definition is as follow\n\nM = [1 0.75 0.5;...\n 0.75 1 0.25;...\n 0.5 0.25 1];\n\nt = tensor(M,'rank',2)\n\n%% Tensors (tensors of third rank)\n%\n% Smart materials are materials that have one or more properties that\n% change significantly under external stimuli. A typical example is the\n% voltage resulting to applied stress that certain materials have, named\n% piezoeletric effect. This property is described as a third rank tensor\n% that relates induced electric displacement vector to the second-order\n% stress tensor. This is expressed in the form $P_i=d_{ijk} \\sigma_{jk}$.\n% In MTEX, a third rank tensor can be described as\n\nM =[[-1.9222 1.9222 0 -0.1423 0 0 ];...\n [ 0 0 0 0 0.1423 3.8444];...\n [ 0 0 0 0 0 0 ]];\n\nt = tensor(M,'rank',3)\n \n%% Tensors (tensors of fourth rank)\n%\n% Fourth rank tensors are tensors that describe the relation between 2\n% second rank tensors. A typical example is the tensor describing the\n% elastic properties of materials, which translate the linear relationship\n% between the second rank stress and infinitesimal strain tensors. The\n% Hooke's Law describing the shape changes in a material subject to stress\n% can be written as $\\sigma_{ij}=c_{ijkl} \\epsilon_{kl}$, where $c_{ijkl}$\n% is a fourth rank tensor.\n%\n% The four indices (ijkl) of the elastic tensor have values between 1 and\n% 3, so that there are $3^4=81$ coefficients. As the stress and strain\n% tensors are symmetric, both stress and strain second rank tensors only\n% have 6 independent values rather than 9. In addition, crystal symmetry\n% reduces even more the number of independent components on the elastic\n% tensor, from 21 in the case of triclinic phases, to 3 in the case of\n% cubic materials. In MTEX, a fourth rank tensor can be defined as:\n\nM = [[320 50 50 0 0 0];...\n [ 50 320 50 0 0 0];...\n [ 50 50 320 0 0 0];...\n [ 0 0 0 64 0 0];...\n [ 0 0 0 0 64 0];...\n [ 0 0 0 0 0 64]];\n\nC = tensor(M,'rank',4) \n\n%%\n% Note the repetition in values in this matrix is related to crystal\n% symmetry, in this case, a cubic example, where only $C_{11}$, $C_{12}$\n% and $C_{44}$ are independent components.\n%\n%% Specific tensors\n%\n% MTEX includes specific classes for the following tensors.\n%\n% || *name* || *rank* || *symbol* || *name* || *rank* || *symbol* ||\n% || @complianceTensor || 4 || $S_{ijkl}$ || @stiffnessTensor || 4 || $C_{ijkl}$ ||\n% || @strainTensor || 2 || $\\sigma_{ij}$ || @stressTensor || 2 || $\\varepsilon_{ij}$ ||\n% || @strainRateTensor || 2 || $E$ || @velocityGradientTensor || 2 || $L$ ||\n% || @curvatureTensor || 2 || $\\kappa_{ij}$ || @deformationGradientTensor || 2 || $F$ ||\n% || @refractiveIndexTensor || 2 || $\\chi$ || @ChristoffelTensor || 2 || $M_{ij}$ || \n% || @dislocationDensityTensor || 2 || $\\alpha$ || || 2 || $M_{ij}$ ||\n% || || 3 || $\\varepsilon_{ijk}$ || @spinTensor || 2 || $\\Omega$ ||\n%\n% Those specific tensors are defined by the syntax\n\nM = [0 0 0;...\n 0 0 0; ...\n 0 0 1];\n\ne = strainTensor(M)\n\n%%\n% In many cases shortcuts exist like\n\ne = stressTensor.uniaxial(vector3d.Z)\n\n%%\n% The advantage of using these specific tensor classes is that some tensor\n% operations like \n% are defined only for specific tensor classes.\n%\n%% Predefined tensors\n%\n% For certain applications, one may want to have a tensor where all the\n% components are 1. In MTEX this is computed as\n\nt = tensor.ones('rank',2)\n\n%%\n% *Identity tensor*\n%\n% The Identity tensor is a second order tensor that has ones n the main \n% diagonal and zeros otherwise. The identity matrix has some special\n% properties, including (i) When multiplied by itself, the result is itself\n% and (ii) rows and columns are linearly independent. In MTEX, this matrix\n% can be computed as\n\nt = tensor.eye('rank',2)\n\n%%\n% *Random tensors*\n%\n% One can also define a tensor in which the components are pseudorandom, by\n% using the function ||\n\nt = tensor.rand('rank',2)\n\n%%\n% *The Levi Civita tensor*\n%\n% The Levi-Civita symbol $\\epsilon_{ijk}$ is a third rank tensor and is\n% defined by 0, if $i=j$, $j=k$ or $k=1$, by 1, if $(i,j,k)=(1,2,3)$,\n% $(2,3,1)$ or $(3,1,2)$ and by $-1$, if $(i,j,k)=(3,2,1)$, $(1,3,2)$ or\n% $(2,1,3)$. The Levi-Civita symbol allows the cross product of two vectors\n% in 3D Euclidean space and the determinant of a square matrix to be\n% expressed in Einstein's index notation. With MTEX the Levi Civita tensor\n% is expressed as\n\nt = tensor.leviCivita\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/Tensors/TensorDefinition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.774768228175973}} {"text": "function [yUpdate, PInvUpdate]=infoFilterUpdate(yPred,PInvPred,z,R,H)\n%%INFOFILTERUPDATE Perform the measurement update step in the standard \n% linear information filter. Using an information filter\n% means that instead of propagating a state x and its\n% covariance matrix P, one propagates inv(P) and \n% y=inv(P)*x.\n%\n%INPUTS: yPred The xDimX1 predicted information state. The information\n% state is the inverse covariance matrix times the target\n% state.\n% PInvPred The xDimXxDim inverse of the predicted state covariance\n% matrix.\n% z The zDimX1 vector measurement.\n% R The zDimXzDim measurement covariance matrix. This must be\n% positive definite.\n% H The zDimXxDim measurement matrix for a linear measurement\n% model. That is z=H*x+w, where w is measurement noise having\n% covariance matrix R.\n%\n%OUTPUTS: yUpdate The xDimX1 updated (posterior) information state vector.\n% PInvUpdate The updated xDimXxDim inverse state covariance matrix.\n%\n%The information filter is algebraically equivalent to the standard linear\n%Kalman filter, but allows for track propagation with very uncertain\n%states, such as when starting tracks. The implementation of the update\n%given here is from the flow chart given in Appendix H of [1].\n%\n%The standard information filter has the implied linear measurement\n%equation\n%z=H*x+w\n%where z is the measurement, w is the zero-mean Gaussian measurement noise\n%with covariance matrix R and x is the true state. However, instead of\n%propagating the true state x with its covariance matrix P, the information\n%filter propagates\n%y=inv(P)*x\n%and instead of propagating the true covariance matrix P, it propagates\n%PInv=inv(P)\n%which means that the filter can be used even when PInv is singular.\n%\n%More information on information filtering is given in Chapter 7.2 of [2].\n%\n%EXAMPLE:\n%In this example, we feed two measurements to the information filter and\n%show that the result has a consistent NEES and the RMSE is the same as the\n%second measurement.\n% T=1;%Sample period.\n% numRuns=1000;\n% %Parameters for the noise process dynamics and measurement.\n% H=[eye(2,2),zeros(2,2)];\n% zDim=size(H,1);\n% xDim=size(H,2);\n% R=diag([40;40]);\n% SR=chol(R,'lower');\n% \n% %Statistics for the initial state.\n% x0Mean=[1e3;0;75;-50];\n% x0Cov=diag([1e3^2;100^2;25^2;25^2]);\n% x0S=chol(x0Cov,'lower');\n% \n% %Parameters for the state dynamics.\n% q=processNoiseSuggest('PolyKal-ROT',9.8,1);\n% F=FPolyKal(T,xDim,1);\n% Q=QPolyKal(T,xDim,1,q);\n% SQ=chol(Q,'lower');\n% \n% RMSEMeas=0;\n% RMSE=0;\n% NEES=0;\n% for curRun=1:numRuns\n% %Draw the initial state.\n% x1True=x0Mean+x0S*randn(xDim,1);\n% %Get the first measurement.\n% z1=H*x1True+SR*randn(zDim,1);\n% \n% x2True=F*x1True+SQ*randn(xDim,1);\n% z2=H*x2True+SR*randn(zDim,1);\n% \n% %Two-point initialization.\n% y0=zeros(xDim,1);\n% PInv0=zeros(xDim,xDim);\n% [yUpdate,PInvUpdate]=infoFilterUpdate(y0,PInv0,z1,R,H);\n% [yPred, PInvPred]=infoFilterDiscPred(yUpdate,PInvUpdate,F,Q);\n% [yUpdate,PInvUpdate]=infoFilterUpdate(yPred,PInvPred,z2,R,H);\n% xEst2=PInvUpdate\\yUpdate;\n% \n% diff=xEst2-x2True;\n% NEES=NEES+diff'*PInvUpdate*diff;\n% RMSE=RMSE+sum(diff(1:2).^2);\n% diff=z2-x2True(1:2);\n% RMSEMeas=RMSEMeas+sum(diff(1:2).^2);\n% end\n% RMSEMeas=sqrt(RMSEMeas/numRuns)\n% RMSE=sqrt(RMSE/numRuns)\n% NEES=NEES/(xDim*numRuns)\n%One will see that RMSEMeas equal RMSE, because with just two measurements,\n%one cannot smmooth the position estimate syet. Additionally, NEES will be\n%close to 1 indicating covariance consistency.\n%\n%REFERENCES:\n%[1] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems \n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%[2] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n% Applications to Tracking and Navigation. New York: John Wiley and\n% Sons, Inc, 2001.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n yUpdate=yPred+H'/R*z;\n PInvUpdate=PInvPred+H'/R*H;\n %Ensure symmetry\n PInvUpdate=(PInvUpdate+PInvUpdate')/2;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Measurement_Update/Complete_Measurement_Updates/infoFilterUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7747682279379773}} {"text": "function [ x, odata, opts ] = solver_SLOPE( A, b, lambda, x0, opts )\n% SOLVER_SLOPE Sorted l1-regularized least squares problem, \n% [ beta, odata, opts ] = solver_SLOPE( X, y, lambda, beta0, opts )\n% Solves the l1-regularized least squares problem, using the sorted/ordered l1 norm, \n% minimize (1/2)*norm( A * x - b )^2 + norm( lasso.*sort(abs(x),'descend'), 1 )\n% using the Auslender/Teboulle variant with restart. X must be a matrix\n% or a linear operator, y must be a vector, and lambda must be a real\n% positive vector in decreasing order. \n% The initial point beta0 and option structure opts are both optional.\n%\n% SLOPE stands for Sorted L-One Penalized Estimation\n%\n% Reference:\n% \"Statistical Estimation and Testing via the Ordered l1 Norm\"\n% by M. Bogdan, E. van den Berg, W. Su, and E. J. Candès, 2013\n% http://www-stat.stanford.edu/~candes/OrderedL1/\n%\n% See also solver_L1RLS.m, solver_LASSO.m, prox_Sl1.m\n\nerror(nargchk(3,5,nargin));\nif nargin < 4, x0 = []; end\nif nargin < 5, opts = []; end\nif ~isfield( opts, 'restart' ), \n opts.restart = 100; \nend\n\n[x,odata,opts] = tfocs( smooth_quad, { A, -b }, prox_Sl1( lambda ), x0, opts );\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/solver_SLOPE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7747682241895735}} {"text": "function r= cauchyrnd(varargin)\n\n% USAGE: r= cauchyrnd(a, b, n, ...)\n% \n% Generate random numbers from the Cauchy distribution, r= a + b*tan(pi*(rand(n)-0.5)).\n% \n% ARGUMENTS:\n% a (default value: 0.0) must be scalars or size(x).\n% b (b>0, default value: 1.0) must be scalars or size(x).\n% n and onwards (default value: 1) specifies the dimension of the output.\n% \n% EXAMPLE:\n% r= cauchyrnd(0, 1, 10); % A 10 by 10 array of random values, Cauchy distributed.\n% \n% SEE ALSO: cauchycdf, cauchyfit, cauchyinv, cauchypdf.\n% \n% Copyright (C) Peder Axensten \n% \n% HISTORY:\n% Version 1.0, 2006-07-10.\n% Version 1.1, 2006-07-26.\n% - Added cauchyfit to the cauchy package. \n% Version 1.2, 2006-07-31:\n% - cauchyinv(0, ...) returned a large negative number but should be -Inf. \n% - Size comparison in argument check didn't work. \n% - Various other improvements to check list. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\t% Default values\n\ta=\t0.0;\n\tb=\t1.0;\n\tn=\t1;\n\t\n\t\n\t% Check the arguments\n\tif(nargin >= 1)\n\t\ta=\tvarargin{1};\n\t\tif(nargin >= 2)\n\t\t\tb=\t\t\tvarargin{2};\n\t\t\tb(b <= 0)=\tNaN;\t% Make NaN of out of range values.\n\t\t\tif(nargin >= 3),\tn=\t[varargin{3:end}];\t\tend\n\t\tend\n\tend\n\t\n\t\n\t% Generate\n\tr=\tcauchyinv(rand(n), a, 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/11749-cauchy/cauchyrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7747682202031736}} {"text": "function [xn,dxdf,dxdc,dxdk,dxdalpha] = normalize2(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\nk1 = kc(1);\nk2 = kc(2);\nk3 = kc(5);\np1 = kc(3);\np2 = kc(4);\n\nN = size(x_kk,2);\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\nv1 = - x_distort(1,:) / fc(1);\nv2 = - x_distort(2,:) / fc(1);\n\ndx_distortdfc = zeros(2*N,2);\ndx_distortdfc(1:2:end,1) = v1';\ndx_distortdfc(2:2:end,2) = v2';\n\nv1 = - x_distort(1,:) / fc(1);\nv2 = - x_distort(2,:) / fc(1);\n\ndx_distortdcc = zeros(2*N,2);\ndx_distortdcc(1:2:end,1) = -(1/fc(1)) * ones(N,1);\ndx_distortdcc(2:2:end,2) = -(1/fc(2)) * ones(N,1);\n\n% Second: undo skew\nx_distort(1,:) = x_distort(1,:) - alpha_c * x_distort(2,:);\n\ndx_distort2dfc = [ dx_distortdfc(:,1)-alpha_c *dx_distortdfc(:,2) dx_distortdfc(:,2)];\ndx_distort2dcc = [ dx_distortdcc(:,1)-alpha_c *dx_distortdcc(:,2) dx_distortdcc(:,2)];\n\ndx_distort2dalpha_c = zeros(2*N,1);\ndx_distort2dalpha_c(1:2:end) = -x_distort(2,:)';\n\nx = x_distort; \t\t\t\t% initial guess\n\nfor kk=1:20,\n \n r_2 = sum(x.^2);\n k_radial = 1 + k1 * r_2 + k2 * r_2.^2 + k3 * r_2.^3;\n delta_x = [2*p1*x(1,:).*x(2,:) + p2*(r_2 + 2*x(1,:).^2); p1 * (r_2 + 2*x(2,:).^2)+2*p2*x(1,:).*x(2,:)];\n x = (x_distort - delta_x)./(ones(2,1)*k_radial);\n \nend;\n\n\nxn = x;\n\n\ndxdk = zeros(2*N,5); % Approximation (no time)\ndxdf = dx_distort2dfc;\ndxdc = dx_distort2dcc;\ndxdalpha = dx_distort2dalpha_c;\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/normalize2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7747654784153399}} {"text": "function [x,w,P]=GaussRadau(kk)\nN = kk-1; % Compute for the number of points kk\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% lgrnodes.m\n%\n% Computes the Legendre-Gauss-Radau nodes, weights and the LGR Vandermonde \n% matrix. The LGR nodes are the zeros of P_N(x)+P_{N+1}(x). \n%\n% References on LGR nodes and weights: \n% C. Canuto, M. Y. Hussaini, A. Quarteroni, T. A. Tang, \"Spectral Methods\n% in Fluid Dynamics,\" Section 2.3. Springer-Verlag 1987\n%\n% F. B. Hildebrand , \"Introduction to Numerical Analysis,\" Section 8.11\n% Dover 1987\n%\n% Written by Greg von Winckel - 05/02/2004\n% Contact: gregvw@chtm.unm.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Truncation + 1\nN1=N+1;\n\n% Use Chebyshev-Gauss-Radau nodes as initial guess for LGR nodes\nx=-cos(2*pi*(0:N)/(2*N+1))';\n\n% The Legendre Vandermonde Matrix\nP=zeros(N1,N1+1);\n\n% Compute P_(N) using the recursion relation\n% Compute its first and second derivatives and \n% update x using the Newton-Raphson method.\n\nxold=2;\n\n% Free abscissae\nfree=2:N1;\n\nwhile max(abs(x-xold))>eps\n \n xold=x;\n \n P(1,:)=(-1).^(0:N1);\n \n P(free,1)=1; P(free,2)=x(free);\n \n for k=2:N1\n P(free,k+1)=( (2*k-1)*x(free).*P(free,k)-(k-1)*P(free,k-1) )/k;\n end\n \n x(free)=xold(free)-((1-xold(free))/N1).*(P(free,N1)+P(free,N1+1))...\n ./(P(free,N1)-P(free,N1+1));\nend\n\n% The Legendre-Gauss-Radau Vandermonde\nP=P(1:N1,1:N1);\n\n% Compute the weights\nw=zeros(N1,1);\nw(1)=2/N1^2;\nw(free)=(1-x(free))./(N1*P(free,N1)).^2;", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/QuadratureMethods/GaussRadau.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8539127455162774, "lm_q1q2_score": 0.7747654742628092}} {"text": "function p = polyfitweighted2(x,y,z,n,w)\n% polyfitweighted2.m \n% -------------------\n%\n% Find a least-squares fit of 2D data z(x,y) with an nth order \n% polynomial, weighted by w(x,y) .\n%\n% By S.S. Rogers (2006)\n%\n% Usage\n% ------\n%\n% P = polyfitweighted2(X,Y,Z,N,W) finds the coefficients of a polynomial \n% P(X,Y) of degree N that fits the data Z best in a least-squares \n% sense. P is a row vector of length (N+1)*(N+2)/2 containing the \n% polynomial coefficients in ascending powers, 0th order first.\n%\n% P = [p00 p10 p01 p20 p11 p02 p30 p21 p12 p03...]\n%\n% e.g. For a 3rd order fit, \n% the regression problem is formulated in matrix format as:\n%\n% wZ = V*P or\n%\n% 2 2 3 2 2 3\n% wZ = [w wx wy wx xy wy wx wx y wx y wy ] [p00\n% p10\n% p01\n% p20\n% p11\n% p02\n% p30\n% p21\n% p12\n% p03]\n%\n% *Note:* P is not in the format of standard Matlab 1D polynomials. Use\n% polval2.m to evaluate the polynomial in this format, at given values of\n% x,y.\n%\n% X,Y must be vectors\n% Z,W must be 2D arrays of size [length(X) length(Y)]\n%\n% based on polyfit.m by The Mathworks Inc. - see doc polyfit for more details\n%\n% Class support for inputs X,Y,Z,W:\n% float: double, single\n\nx = x(:);\ny = y(:);\n\nlx=length(x);\nly=length(y);\n\nif ~isequal(size(z),size(w),[ly lx])\n error('polyfitweighted2:XYSizeMismatch',...\n [' X,Y *must* be vectors' ...\n ' Z,W *must* be 2D arrays of size [length(X) length(Y)]'])\nend\n\ny=y*ones(1,lx);\nx=ones(ly,1)*x';\nx = x(:);\ny = y(:);\nz = z(:);\nw = w(:);\n\npts=length(z);\n\n% Construct weighted Vandermonde matrix.\nV=zeros(pts,(n+1)*(n+2)/2);\nV(:,1) = w;\n%V(:,1) = ones(pts,1);\nordercolumn=1;\nfor order = 1:n\n for ordercolumn=ordercolumn+(1:order)\n V(:,ordercolumn) = x.*V(:,ordercolumn-order);\n end\n ordercolumn=ordercolumn+1;\n V(:,ordercolumn) = y.*V(:,ordercolumn-order-1);\nend\n\n% Solve least squares problem.\n[Q,R] = qr(V,0);\nws = warning('off','all'); \np = R\\(Q'*(w.*z)); % Same as p = V\\(w.*z);\nwarning(ws);\nif size(R,2) > size(R,1)\n warning('polyfitweighted2:PolyNotUnique', ...\n 'Polynomial is not unique; degree >= number of data points.')\nelseif condest(R) > 1.0e10\n warning('polyfitweighted2:RepeatedPointsOrRescale', ...\n ['Polynomial is badly conditioned. Remove repeated data points\\n' ...\n ' or try centering and scaling as described in HELP POLYFIT.'])\nend\n%r = z - (V*p)./w;\np = p.'; % Polynomial coefficients are row vectors by convention.\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13719-2d-weighted-polynomial-fitting-and-evaluation/polyfitweighted2/polyfitweighted2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480668, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7747654673887997}} {"text": "function[upa,upb,upc,upd,upe,upf]=ellband(varargin)\n%ELLBAND Bandwidth of modulated elliptical signals in two or three dimensions.\n%\n% [A,B,C]=ELLBAND(KAPPA,LAMBDA,THETA,PHI) computes the instantaneous \n% bandwidth of the elliptical signal characterized by RMS amplitude \n% KAPPA, linearity LAMBDA, orientation THETA, and orbital phase PHI.\n%\n% The three output arguments are\n%\n% A - Amplitude modulation bandwidth \n% B - Deformation bandwidth\n% C - Precession bandwidth. \n%\n% and these satisfy UPSILON^2=A^2+B^2+C^2 where UPSILON is the joint \n% instantaneous bandwidth of the bivariate signal.\n%\n% The form of these terms is as follows:\n%\n% A = 1/KAPPA d/dt KAPPA \n% B = 1/2 * 1/SQRT(1-LAMBDA^2) * d/dt LAMBDA \n% C = LAMBDA d/dt THETA\n%\n% [A,B,C,UPSILON]=ELLBAND(KAPPA,LAMBDA,THETA,PHI) also returns the total \n% instantaneous bandwith UPSILON=SQRT(A^2+B^2+C^2).\n%\n% ELLBAND(...,DIM) performs the analysis with time running along\n% dimension DIM, as opposed to the default behavior of DIM=1.\n%\n% For details see Lilly and Olhede (2010).\n%\n% ELLBAND also works if the input arguments are cell arrays of numerical\n% arrays, in which case the output will be similarly sized cell arrays.\n% __________________________________________________________________\n%\n% Three dimensions\n%\n% ELLBAND can also compute the instantaneous bandwidth of modulated \n% elliptical signals in three dimensions.\n%\n% [A,B,C,D,E]=ELLBAND(KAPPA,LAMBDA,THETA,PHI,ALPHA,BETA) returns the\n% terms in the bandwidth from a modulated ellipical signal in a plane\n% with a normal vector having azimuth angle ALPHA and zenith angle BETA.\n% \n% The five output arguments are\n%\n% A - Amplitude modulation bandwidth, as in 2D \n% B - Deformation bandwidth, as in 2D\n% C - Precession bandwidth, as in 2D\n% D - Precession bandwidth with full 3D effects\n% E - Bandwidth due to motion of the normal to the plane\n%\n% and these, in principle, satisfy UPSILON^2=A^2+B^2+C^2+D^2+|E|^2 where \n% UPSILON is the joint instantaneous bandwidth of the trivariate signal.\n% See below for a caveat on this statement.\n%\n% Terms A--C are just as in the bivariate case. The new terms are:\n%\n% D = LAMBDA [d/dt THETA + COS(BETA) * d/dt ALPHA]\n% E = N^T X_+ / |X_+^H X_+| \n% \n% where N is the trivariate normal vector, X_+ is the trivariate analytic\n% signal vector, and \"T\" denotes the matrix transpose, and \"H\" the \n% Hermitian transpose. Note that term E may be complex-valued.\n%\n% Note that term C does not contribute to the full bandwidth, but is \n% output in order to compare the two-dimensional and three-dimensional\n% effects in the full precession bandwidth, term D.\n%\n% An important point is that the trivariate ellipse parameters can be \n% ill-defined for a nearly linear signal, and the elliptical bandwidth \n% terms can give erroneously large values at isolated points. To check\n% for this, compare with the joint bandwidth from INSTMOM.\n%\n% [A,B,C,D,E,UPSILON]=ELLBAND(KAPPA,LAMBDA,THETA,PHI,ALPHA,BETA) also \n% returns the total bandwith UPSILON=SQRT(A^2+B^2+C^2+D^2+|E|^2).\n%\n% For details see Lilly (2011).\n% __________________________________________________________________\n%\n% ELLBAND(DT,...) sets the sample interval DT, which defaults to DT=1.\n% DT may be a scalar, or if the input fields are cell arrays having\n% length N, DT may be a numerical array of length N. \n% \n% See also ANATRANS, WAVETRANS, INSTMOM.\n%\n% 'ellband --t' runs a test.\n% 'ellband --f' generates a figure from Lilly and Olhede (2010).\n%\n% Usage: [a,b,c]=ellband(kappa,lambda,theta,phi);\n% [a,b,c]=ellband(dt,kappa,lambda,theta,phi); \n% [a,b,c]=ellband(dt,kappa,lambda,theta,phi,dim); \n% [a,b,c,upsilon]=ellband(dt,kappa,lambda,theta,phi,dim); \n% [a,b,c,d,e]=ellband(kappa,lambda,theta,phi,alpha,beta); \n% [a,b,c,d,e]=ellband(dt,kappa,lambda,theta,phi,alpha,beta); \n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2006--2020 J.M. Lilly --- type 'help jlab_license' for details\n \n\nif strcmpi(varargin{1}, '--t')\n ellband_test,return\nend\n\nif strcmpi(varargin{1}, '--f')\n type makefigs_ellband\n makefigs_ellband;\n return\nend\n\nif ~iscell(varargin{end})&&length(varargin{end})==1\n dim=varargin{end};\n varargin=varargin(1:end-1);\nelse\n dim=1;\nend\n\nif length(varargin)==5||length(varargin)==7\n dt=varargin{1};\n varargin=varargin(2:end);\nelse\n dt=1;\nend\n\nkappa=varargin{1};\nlambda=varargin{2};\ntheta=varargin{3};\nphi=varargin{4};\nif length(varargin)>4\n alpha=varargin{5};\n beta=varargin{6};\n dims=3;\nelse\n alpha=[];\n beta=[];\n dims=2;\nend\n\n\n%Redo some initializing in case of cell arrays\nif iscell(kappa)\n if isempty(alpha)\n for i=1:length(kappa)\n alpha{i,1}=[];\n beta{i,1}=[];\n end\n end\n if length(dt)==1\n dto=dt;\n for i=1:length(kappa)\n dt(i)=dto;\n end\n end\nend\n\nif ~isempty(kappa)\n if iscell(kappa)\n [upa,upb,upc,upd,upe,upf]=vempty;\n for i=1:length(kappa)\n [upa{i,1},upb{i,1},upc{i,1},upd{i,1},upe{i,1},upf{i,1}]=...\n ellband_one(dt(i),kappa{i,1},lambda{i,1},theta{i,1},phi{i,1},alpha{i,1},beta{i,1},dim,dims);\n end\n else\n [upa,upb,upc,upd,upe,upf]=ellband_one(dt,kappa,lambda,theta,phi,alpha,beta,dim,dims);\n end\nelse\n upa=kappa;upb=kappa;upc=kappa;\n upd=kappa;upe=kappa;upf=kappa;\nend\n\nfunction[upa,upb,upc,upd,upe,upf]=ellband_one(dt,kappa,lambda,theta,phi,alpha,beta,dim,dims)\n\nomtheta=frac(vdiff(unwrap(theta,[],dim),dim),dt);\nzeta=sign(lambda).*sqrt(1-lambda.^2);\n\n%These do not seem much different\n%upa=frac((vdiff(kappa,dim)),kappa*dt);\nupa=frac((vdiff(log(kappa),dim)),dt); \nupb=frac(sqrt(frac(1,1-lambda.^2)).*(frac(1,2)*vdiff(lambda,dim)),dt);\n\nupb2=frac(sqrt(frac(1,1-zeta.^2)).*(frac(1,2)*vdiff(zeta,dim)),dt);\nupb(abs(lambda)>sqrt(1/2))=-upb2(abs(lambda)>sqrt(1/2));\n%To correct numerical instability when lambda is close to unity\n\n%This is the same\n%[a,b]=kl2ab(kappa,lambda);\n%upc=abs(frac(a.*b,a.^2+b.^2).*vdiff(log(abs(b./a)),1))./dt;\nupc=(lambda.*omtheta);\n\n%Replace isolated nans that may have been lost\nbool=isnan(kappa);\nupa(bool)=nan; \nupb(bool)=nan; \nupc(bool)=nan; \n\nif dims==3\n omalpha=frac(vdiff(unwrap(alpha,[],dim),dim),dt);\n ombeta=frac(vdiff(unwrap(beta,[],dim),dim),dt);\n \n upd=lambda.*(omtheta+omalpha.*cos(beta));\n \n [x,y,z]=ellsig(kappa,lambda,theta,phi,alpha,beta);\n \n %Now find x-tilde, 2-d vector\n [x,y,z]=vectmult(jmat3(-alpha,3),x,y,z);\n [x,y,z]=vectmult(jmat3(-beta,1),x,y,z);\n \n numer=-omalpha.*sin(beta).*x+ombeta.*y; \n denom=sqrt(abs(x).^2+abs(y).^2);\n upe=frac(numer,denom); \n upf=sqrt(upa.^2+upb.^2+upc.^2+upd.^2+abs(upe).^2);\n \n %Replace isolated nans that may have been lost\n upd(bool)=nan;\n upe(bool)=nan;\n upf(bool)=nan;\n \nelse \n upd=sqrt(upa.^2+upb.^2+upc.^2);\n upe=[];\n upf=[];\nend\n\nfunction[]=ellband_test\nellband_test1;\nellband_test2;\nellband_test3;\nellband_test4;\n\n\nfunction[]=ellband_test1\n\nload npg2006\nuse npg2006\n\n%Decide on frequencies\nfs=2*pi./(logspace(log10(10),log10(100),50)');\n\n%Compute wavelet transforms using generalized Morse wavelets\n[wx,wy]=wavetrans(real(cx),imag(cx),{1,2,4,fs,'bandpass'},'mirror');\n[wxr,wyr,ir,jr]=ridgewalk(dt,wx,wy,fs,sqrt(2*4),1);\n\n[kappa,lambda,theta,phi]=ellparams(wxr,wyr);\n[ba,bd,bp]=ellband(kappa,lambda,theta,phi); \n[a,om,upbar]=instmom([wxr wyr],1,2);\n\n\nwxr2=permute(wxr,[3 2 1]);\nwyr2=permute(wyr,[3 2 1]);\nclear wr2\nwr2(1,1,:)=wxr2;wr2(1,2,:)=wyr2;\n[kappa2,lambda2,theta2,phi2]=ellparams(wxr2,wyr2,3);\n[ba2,bd2,bp2]=ellband(kappa2,lambda2,theta2,phi2,3); \n[a2,om2,upbar2]=instmom(wr2,3,2);\nvcolon(kappa2,lambda2,theta2,phi2,ba2,bd2,bp2,a2,om2,upbar2);\nbool=aresame([kappa2 lambda2 theta2 phi2 ba2 bd2 bp2 a2 om2 upbar2],...\n [kappa lambda theta phi ba bd bp a om upbar]);\n\nreporttest('ELLBAND time running in pages', bool); \n\nvindex(upbar,ba,bd,bp,2:length(upbar)-1,1);\nerr=vsum((upbar-sqrt(ba.^2+bd.^2+bp.^2)).^2,1)./vsum(upbar.^2,1);\nreporttest('ELLBAND terms sum to bandwidth from INSTMOM', err<1e-5); \n\n\n\nfunction[]=ellband_test2\nt=(0:1:925)';\ncxe=zeros(length(t),3);\n\nkappa=3*exp(2*0.393*(t/1000-1));\nlambda=0.4+0*t;\nphi=(t/1000*5)*2*pi;\ntheta=pi/4+0*t;\n\nom=vdiff(phi,1); %Since theta is constant\n\n[x,y]=ellsig(kappa,lambda,theta,phi);\n[a,om,up]=instmom([x y],1,2);\n\nups=sqrt(vsum(abs(up).^2,2));\n[upsa,upsb,upsc]=ellband(kappa,lambda,theta,phi);\nb1=aresame(vmean([ups upsa upsb upsc]./[om om om om],1),[1 1 0 0]*0.025,1e-4);\n\nom=vdiff(phi,1); %Since theta is constant\n\nkappa=2.5+0*t;\nlambda=zeros(size(t));\nfor i=2:length(t)\n lambda(i)=real(lambda(i-1)+2*sqrt(1-lambda(i-1).^2)*0.025.*om(i));\nend\nlambda(1)=nan;\nlambda(lambda>1)=1; \n\n[x,y]=ellsig(kappa,lambda,theta,phi);\n[a,om,ups]=instmom([x y],1,2);\n\n[upsa,upsb,upsc]=ellband(kappa,lambda,theta,phi);\nb2=aresame(vmean([ups upsa upsb upsc]./[om om om om],1),[1 0 1 0]*0.025,1e-4);\n\n[kappa,lambda]=ab2kl(3+zeros(size(t)),2+zeros(size(t)));\n\ntheta=phi/14.45;\n\n[x,y]=ellsig(kappa,lambda,theta,phi);\n[a,om,ups]=instmom([x y],1,2);\n\n[upsa,upsb,upsc]=ellband(kappa,lambda,theta,phi);\nb3=aresame(vmean([ups upsa upsb upsc]./[om om om om],1),[1 0 0 1]*0.025,1e-4);\n\nreporttest('ELLBAND three panels of figure each have bandwidth 0.025',b1&&b2&&b3)\n\nfunction[]=ellband_test3\n\nkappao=10;\nlambdao=2/3;\nomtheta=linspace(-2,2,100);\nomphi=1;\n\ndt=0.1;\nt=[0:dt:100]';\n\n\nzo=ellsig(kappao,lambdao,0,omphi.*t);\npsi=sleptap(length(zo)); \n\nz=vzeros(length(zo),length(omtheta));\nfor i=1:length(omtheta)\n z(:,i)=rot(omtheta(i).*t).*zo;\nend\n\n%Taper for better computation\nz=z.*vrep(psi(:,1),size(z,2),2);\n[zp,zn]=anatrans(z,conj(z));\n\n[ap,omp,upp]=instmom(dt,zp);\n[an,omn,upn]=instmom(dt,zn);\n\nkappa=sqrt(abs(zp).^2+abs(zn).^2);\nom=frac(omp.*abs(zp).^2+omn.*abs(zn).^2,kappa.^2);\nombar=vmean(om,1,squared(kappa));\n\nsig=sqrt(frac((upp.^2+(omp-vrep(ombar,size(om,1),1)).^2).*abs(zp).^2+...\n (upn.^2+(omn-vrep(ombar,size(om,1),1)).^2).*abs(zn).^2,kappa.^2));\nsigbar=sqrt(vmean(sig.^2,1,squared(kappa)));\n\n[x,y]=vectmult(sqrt(2)*tmat',zp,zn);\n[kappa,lambda,theta,phi]=ellparams(x,y);\n[ba,bd,bp]=ellband(dt,kappa,lambda,theta,phi);\nbom=om-vrep(ombar,size(om,1),1);\n\n\nsig2=sqrt(ba.^2+bd.^2+bp.^2+bom.^2);\nsigbar2=sqrt(vmean(sig2.^2,1,squared(kappa)));\n\n%plot(sig,'b'),hold on,plot(sig2,'r') %Visually identical\nerr=sum(squared(sigbar-sigbar2))./sum(squared(sigbar));\nreporttest('ELLBAND rotary and elliptical bandwidths match for shifted ellipse, non-unit sample rate',err<1e-5)\n\nfunction[]=ellband_test4\n\n\nload solomon \nuse solomon\n\n%Choose central portion where polarization is elliptical\nvindex(x,y,z,420:580,1);\nvfilt(x,y,z,10,'zeros');\n[x,y,z]=anatrans(x,y,z,'mirror');\n\n[kappa,lambda,theta,phi,alpha,beta]=ellparams(x,y,z);\n[a,ombar,upbar]=instmom([x,y,z],1,2);\n[a,b,c,d,e]=ellband(kappa,lambda,theta,phi,alpha,beta); \nupbar1=sqrt(a.^2+b.^2+d.^2+abs(e).^2);\n\nerr=abs(upbar-upbar1).^2./abs(upbar).^2;\nerr=sort(err,'descend');\nerr=err(20:end);\n%figure, plot([upbar upbar1])\nreporttest('ELLBAND trivariate case, sum of bandwith terms for Solomon Islands (removing worst outliers)',allall(err<0.05))\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/jEllipse/ellband.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7747654673887996}} {"text": "function [ seed, xd, td ] = triangulation_order3_sample ( node_num, node_xy, ...\n triangle_num, triangle_node, num_ran, seed )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_SAMPLE returns random points in a triangulation.\n%\n% Discussion:\n%\n% It is assumed that the triangulation consists of a set of non-overlapping\n% triangles.\n%\n% The point is chosen uniformly in the area covered by the triangulation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the node coordinates.\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 triangles.\n%\n% Input, integer NUM_RAN, the number of points to sample.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n% Output, real XD(2,NUM_RAN), the sample points.\n%\n% Output, integer TD(NUM_RAN), the triangle to which each sample point\n% belongs.\n%\n dim_num = 2;\n%\n% Compute the areas of the triangles.\n% Build a cumulative area vector.\n% Convert it to a relative cumulative area vector.\n%\n area_cum(0+1) = 0.0;\n\n for i = 1 : triangle_num\n\n i1 = triangle_node(1,i);\n i2 = triangle_node(2,i);\n i3 = triangle_node(3,i);\n\n t(1:dim_num,1) = node_xy(1:dim_num,i1);\n t(1:dim_num,2) = node_xy(1:dim_num,i2);\n t(1:dim_num,3) = node_xy(1:dim_num,i3);\n\n area = triangle_area_2d ( t );\n\n area_cum(i+1) = area_cum(i-1+1) + area;\n\n end\n\n area_total = area_cum(triangle_num+1);\n\n area_cum(0+1:triangle_num+1) = area_cum(0+1:triangle_num+1) / area_total;\n%\n% Pick random values. A random value R indicates the corresponding triangle\n% whose cumulative relative area contains R.\n%\n% Bracket the random value in the cumulative relative areas,\n% indicating a triangle.\n%\n% Pick a random point in the triangle.\n%\n for i = 1 : num_ran\n\n [ r, seed ] = r8_uniform_01 ( seed );\n\n [ left, right ] = r8vec_bracket ( triangle_num+1, area_cum, r );\n\n td(i) = right - 1;\n\n i1 = triangle_node(1,td(i));\n i2 = triangle_node(2,td(i));\n i3 = triangle_node(3,td(i));\n\n t(1:dim_num,1) = node_xy(1:dim_num,i1);\n t(1:dim_num,2) = node_xy(1:dim_num,i2);\n t(1:dim_num,3) = node_xy(1:dim_num,i3);\n\n [ xd(1:dim_num,i), seed ] = triangle_sample ( t, 1, seed );\n\n end\n\n return\nend\n", "meta": {"author": "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_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.774627429288507}} {"text": "function val=intPowSinPow(u,n,m)\n%%INTPOWSINPOW Evaluate the integral of u^n*sin(u)^m du. A definite\n% integral can be evaluated, or an indefinite integral (with a\n% particular additive constant).\n%\n%INPUTS: u A 2XN (for definite integral) or a 1XN (for indefinite\n% integrals) set of N points. For definite integrals, u(1,:) are\n% the real lower bounds and u(2,:) are the real upper bounds. For\n% indefinite integrals, the integral is evaluated at the points in\n% u. The values in u should be real.\n% n The positive integer exponent of u.\n% m The positive integer exponent of the sine term.\n%\n%OUTPUTS: val The 1XN set of values of the integral of u^n*sin(u)^m.\n%\n%This function implements formulas 4 and 5 of Section 2.631 of [1].\n%\n%REFERENCES:\n%[1] I. S. Gradshteyn and I. M. Ryzhik, Tables of Integrals, Series, and\n% Products, Corrected and Enlarged Edition. New York: Academic Press,\n% 1980, translated from Russian.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(u,1);\n\nif(isempty(u))\n val=[];\n return;\nend\n\nif(numDim==1)%An indefinite integral\n val=indefIntPowSinPow(u,n,m);\nelse%A definite integral\n val=indefIntPowSinPow(u(2,:),n,m)-indefIntPowSinPow(u(1,:),n,m);\nend\n\nend\n\nfunction val=indefIntPowSinPow(u,n,m)\n\nif(mod(m,2)==0)%Use formula 4.\n m=m/2;\n \n val=0;\n for k=0:(m-1)\n a=2*(m-k);\n x=a*u;\n val=val+(-1)^k*binomial(2*m,k)*(1/a)^(n+1)*intPowCos(x,n);\n end\n\n val=(-1)^m/(2^(2*m-1))*val;\n val=val+binomial(2*m,m)*u.^(n+1)/(2^(2*m)*(n+1));\nelse%Use formula 5.\n m=(m-1)/2;\n \n val=0;\n for k=0:m\n a=2*(m-k)+1;\n x=a*u;\n val=val+(-1)^k*binomial(2*m+1,k)*(1/a)^(n+1)*intPowSin(x,n);\n end\n \n val=val*(-1)^m/(2^(2*m));\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Specific_Integrals/intPowSinPow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7746274144477538}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n% problem 6 - Computation of linear convolution\n\n\n% a)\nx1=[1 2 3 4];\nx2=[ 5 4 3 2 1];\ny=conv(x1,x2)\n\n% b)\nN1=length(x1);\nN2=length(x2);\nM=N1+N2-1;\nx1(M)=0;\nx2(M)=0;\ny=circonv(x1,x2)\n\n% c)\nX1=fft(x1,M);\nX2=fft(x2,M);\ny=ifft(X1.*X2)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/7/c713f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7745564155667635}} {"text": "function R = rand_rotation(n)\n % Uniformly sample SO(n) \n %\n % R = rand_rotation(n)\n %\n % Inputs:\n % n dimension\n % Output:\n % R n by n rotation matrix\n %\n\n % \"How to generate a random unitary matrix\" [Maris Ozols 2006]\n % http://home.lu.lv/~sd20008/papers/essays/Random%20unitary%20[paper].pdf\n [Q,~] = qr(randn(n));\n s = (2*(rand>0.5)-1);\n Q(:,1) = Q(:,1)*s;\n %b = det(Q);\n b = s*(2*mod(n,2)-1);\n Q(:,2) = b*Q(:,2);\n assert(abs(det(Q)-1)<1e-10)\n % rename as R\n R = Q;\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/matrix/rand_rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7745564060204386}} {"text": "function angles = tetrahedron_face_angles_3d ( tetra )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_FACE_ANGLES_3D returns the 12 face angles of a tetrahedron 3D.\n%\n% Discussion:\n%\n% The tetrahedron has 4 triangular faces. This routine computes the\n% 3 planar angles associated with each face.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real TETRA(3,4) the tetrahedron vertices.\n%\n% Output, real ANGLES(3,4), the face angles.\n%\n\n%\n% Face 123\n%\n tri(1:3,1:3) = tetra(1:3,1:3);\n angles(1:3,1) = triangle_angles_3d ( tri );\n%\n% Face 124\n%\n tri(1:3,1:2) = tetra(1:3,1:2);\n tri(1:3,3) = tetra(1:3,4);\n angles(1:3,2) = triangle_angles_3d ( tri );\n%\n% Face 134\n%\n tri(1:3,1) = tetra(1:3,1);\n tri(1:3,2:3) = tetra(1:3,3:4);\n angles(1:3,3) = triangle_angles_3d ( tri );\n%\n% Face 234\n%\n tri(1:3,1:3) = tetra(1:3,2:4);\n angles(1:3,4) = triangle_angles_3d ( tri );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/tetrahedron_face_angles_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7745564045060439}} {"text": "% Author: Jai Juneja (adapted from video lecture series by Joan Sola)\n% Date: 12/02/2013\n%\n% Given a range-bearing measurement y, obtain position p of observed\n% landmark in the robot's frame.\n%\n% Inputs:\n% y = [d a] : Laser range and bearing measurement\n%\n% Outputs:\n% p_r = [p_x p_y]': Cartesian position of observation in robot's frame\n% Optional:\n% P_y : Jacobian of p wrt. y\n\nfunction [p_r, P_y] = getInvMeasurement(y)\n d = y(1, :); % Range measurement\n a = y(2, :); % Bearing measurement\n\n p_x = d .* cos(a); % x-position of observation in robot's frame\n p_y = d .* sin(a); % y-position of observation in robot's frame\n \n p_r = [p_x; p_y];\n \n if nargout > 1 % Compute Jacobian (only works for single measurement)\n P_y = [...\n cos(a) -d*sin(a)\n sin(a) d*cos(a)];\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/getInvMeasurement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7745545587615046}} {"text": "%% Example 2.5: Viscous Conservation Law\n% In this example, we consider the viscous conservation law\n%\n% $$ u_t + f(u)_x = \\mu u_{xx}, \\qquad u(x,0)=u_0(x).$$\n%\n% A common method to derive efficient methods for this equation is to split\n% the evolution into two different operators\n%\n% $$ S(t): \\quad v_t + f(v)_x = 0, \\qquad v(x,0)=v_0(x)$$\n%\n% $$ H(t): \\quad w_t = \\mu w_{xx}, \\qquad w(y,0)=w_0(y)$$\n%\n% The approximate solution is constructed from the formula\n%\n% $$u(x,t)\\approx [H(\\Delta t)\\circ S(\\Delta t) ]^n u_0(x)$$\n%\n% This way, one can utilize highly efficient solvers for each of the two\n% subequations. Here, we use a spectral difference method for the heat\n% equation. Moreover, because the purpose here is simply to demonstrate the\n% operator splitting, we use the simple first-order Lax-Friedrichs scheme\n% for the hyperbolic conservation law ($r=\\Delta t/\\Delta x$)\n%\n% $$u_i^{n+1} = \\frac12\\bigl(u_{i-1}^n + u_{i+1}^n\\bigr) \n% - \\frac12 r \\bigl[ f(u_{i+1}^n) - f(u_{i-1}^n)\\bigr]$$\n\n%% Initial setup\nN = 512; h = 2*pi/N;\nT = 6;\nx = -pi+(0:N)*h; x = 0.5*(x(1:end-1)+x(2:end));\nu0 = exp(-4*sin((x+2)/2).^2);\n\n%% Burgers' equation\n% A classical example of a viscous conservation law is the so-called\n% Burgers' equation\n%\n% $$ u_t + ( 0.5 u^2)_x = \\mu u_{xx}\n%\n% which can be considered a simplified model of the momentum equation from\n% the Navier-Stokes equations. Here, we will consider the evolution of a\n% smooth profile for \\mu=0.01 using periodic boundary conditions.\nnsplit = 50;\nu = consheat('flux', u0, x, T, nsplit, 0.01);\nsubplot(2,1,1), plot(x,u(:,1:10:nsplit+1))\nsubplot(2,1,2), surf(x,linspace(0,T,nsplit+1),u')\nshading interp; view(-10,50), axis tight\n\n%%\n% As we see from the figure, the nonlinear convective forces sharpen the\n% smooth profile into a shock layer whose width is determined by the\n% balance of the diffusion term and the self-sharpening mechanisms in the\n% nonlinear flux function.\n\n%% Compare different time steps\n% Next, we increase \\mu to 0.1 and consider the effect of different number\n% of splitting steps.\nfor n=1:4,\n\tnsplit = 4*3.^(n-1);\n\tu = consheat('flux', u0, x, T, nsplit);\n subplot(2,2,n); contourf(x, linspace(0,T,nsplit+1), u');\n xlabel('x'), ylabel('t'), colorbar, title([num2str(nsplit) ' steps']);\nend;\n%%\n% The approximations computed with four and twelve splitting steps clearly\n% capture the dominant evolutionary behavior of the solution, but also\n% contain nonphysical wiggles caused by splitting errors. As we increase\n% the number of splitting steps, the splitting errors decrease and the\n% approximate solutions are able to capture the whole evolution without\n% significant artifacts created by our splitting strategy.\n\n%% Comparing different shock widths\n% As a last example, we will look at the evolution of the smooth profile\n% for different balances between the convective and diffusive forces.\nmu = 4; nsplit = 50;\nt = linspace(0,T,nsplit+1);\nfor n=1:4,\n mu = 0.25*mu;\n\tu = consheat('flux',u0,x,T,nsplit,mu);\n\tsubplot(2,2,n); contourf(x,t,u');\n xlabel('x'), ylabel('t'), colorbar, title(['mu = ', num2str(mu)]);\nend;\n%%\n% For large values of \\mu, the diffusive forces dominate and the solution\n% profile evolves toward a flat surface. As \\mu decreases, the convective\n% forces take over and the solution develops into a viscous shock that\n% travels to the right.", "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_5/Example2_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.7745312026951591}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1 \n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the \n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\n\nm = size(X,1)\n\nfor i = 1:m\n distance_array = zeros(1,K);\n for j = 1:K\n distance_array(1,j) = sqrt(sum(power((X(i,:)-centroids(j,:)),2)));\n end\n [d, d_idx] = min(distance_array);\n idx(i,1) = d_idx;\nend\n\n\n\n\n\n% =============================================================\n\nend\n\n", "meta": {"author": "Borye", "repo": "machine-learning-coursera-1", "sha": "033fdc2e6da393eeb1179a09aafe92362021effb", "save_path": "github-repos/MATLAB/Borye-machine-learning-coursera-1", "path": "github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 8 Assignments/K-Means Clustering and PCA/mlclass-ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.7745312008296981}} {"text": "function [R,W] = rodrigues(N,phi)\n % RODRIGUES Construct the rotation matrix for rotating vectors around each\n % given vector.\n %\n % Inputs:\n % N #N by 3 list of 3D vectors\n % phi angle to rotate by.\n % Outputs:\n % R 3#N by 3#N \"rotation\" matrix\n % W 3#N by 3#N cross product matrix\n % \n % Example:\n % % Given a scalar function Z on a mesh (V,F)\n % G = grad(V,F);\n % N = normalizerow(normals(V,F));\n % X = reshape(G*Z,[],3);\n % Y = reshape(rodrigues(N,pi/2)*G*Z,[],3);\n % BC = barycenter(V,F);\n % tsurf(F,V,'CData',Z,fphong,'EdgeColor','none');\n % hold on;\n % quiver3(BC(:,1),BC(:,2),BC(:,3),X(:,1),X(:,2),X(:,3))\n % quiver3(BC(:,1),BC(:,2),BC(:,3),Y(:,1),Y(:,2),Y(:,3))\n % hold off;\n % \n\n m = size(N,1);\n % Either uniform angle or per-vector\n if numel(phi)>1\n assert(numel(phi) == m);\n phi = diag(sparse(phi));\n end\n % https://math.stackexchange.com/a/142831\n %\n W = sparse( ...\n [1 2 0 2 0 1]*m+(1:m)', ...\n [0 0 1 1 2 2]*m+(1:m)', ...\n [N(:,3) -N(:,2) -N(:,3) N(:,1) N(:,2) -N(:,1)], ...\n 3*m,3*m);\n if isempty(phi)\n R = [];\n else\n R = speye(3*m,3*m) + sin(phi)*W + (2*sin(phi/2)^2)*W*W;\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/rodrigues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7745255535549297}} {"text": "function result = ball_unit_07_3d ( func )\n\n%*****************************************************************************80\n%\n%% BALL_UNIT_07_3D approximates an integral inside the unit ball in 3D.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that:\n%\n% X**2 + Y**2 + Z**2 <= 1.\n%\n% Discussion:\n%\n% A 64 point 7-th degree formula is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 May 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Arthur H Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function which evaluates F(X,Y,Z), of the form\n% function value = func ( x, y, z )\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n norder = 4;\n%\n% This is the 5 point Gauss-Legendre rule,\n% but with the midpoint deleted, and with different weights.\n%\n xtab1(1:4) = [...\n -0.906179845938663992797626878299E+00, ...\n -0.538469310105683091036314420700E+00, ...\n 0.538469310105683091036314420700E+00, ...\n 0.906179845938663992797626878299E+00 ];\n\n weight1(1:4) = [ ...\n 0.19455533421780251826E+00, ...\n 0.13877799911553081506E+00, ...\n 0.13877799911553081506E+00, ...\n 0.19455533421780251826E+00 ];\n%\n% Set XTAB2 and WEIGHT2.\n%\n for j = 1 : norder\n angle = pi * ( 2 * j - 1 ) / ( 2 * norder );\n xtab2(j) = cos ( angle );\n end\n\n weight2(1:norder) = 1.0E+00;\n%\n% Set XTAB3 and WEIGHT3 for the interval [-1,1].\n%\n [ xtab3, weight3 ] = legendre_set ( norder );\n\n w = 3.0E+00 / 16.0E+00;\n\n quad = 0.0E+00;\n\n for i = 1 : norder\n for j = 1 : norder\n for k = 1 : norder\n\n x = xtab1(i) * sqrt ( 1.0E+00 - xtab2(j)^2 ) ...\n * sqrt ( 1.0E+00 - xtab3(k)^2 );\n y = xtab1(i) * xtab2(j) * sqrt ( 1.0E+00 - xtab3(k)^2 );\n z = xtab1(i) * xtab3(k);\n\n quad = quad + w * weight1(i) * weight2(j) * weight3(k) ...\n * feval ( func, x, y, z );\n\n end\n end\n end\n\n volume = ball_unit_volume_3d ( );\n result = quad * volume;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/ball_unit_07_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.774525549707618}} {"text": "function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)\n %% GRADIENTDESCENT Performs gradient descent to learn theta\n % theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by \n % taking num_iters gradient steps with learning rate alpha\n\n % Initialize some useful values\n n = length(y); % number of training examples\n J_history = zeros(num_iters, 1);\n\n for iter = 1 : num_iters\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCost) and gradient here.\n %\n \n % compute the gradient\n grad = zeros(size(theta));\n error = X * theta - y;\n for j = 1 : length(grad)\n grad(j) = alpha * sum(error .* X(:, j)) / n;\n end\n \n % simultaneously update all theta entries\n theta = theta - grad;\n \n % Save the cost J in every iteration \n J_history(iter) = computeCost(X, y, theta);\n end\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/linear-regression/code/gradientDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7744764842979494}} {"text": "function value = r4_acosh ( x )\n\n%*****************************************************************************80\n%\n%% R4_ACOSH evaluates the arc-hyperbolic cosine of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the arc-hyperbolic cosine of X.\n%\n persistent dln2;\n persistent xmax;\n\n if ( isempty ( xmax ) )\n dln2 = 0.69314718055994530941723212145818;\n xmax = 1.0 / sqrt ( r4_tiny ( ) );\n end\n\n if ( x < 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_ACOSH - Fatal error!\\n' );\n fprintf ( 1, ' X < 1.0\\n' );\n error ( 'R4_ACOSH - Fatal error!' )\n elseif ( x < xmax )\n value = log ( x + sqrt ( x * x - 1.0 ) );\n else\n value = dln2 + log ( 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/r4lib/r4_acosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7744764811537608}} {"text": "function value = stirling2_value ( n, m )\n\n%*****************************************************************************80\n%\n%% STIRLING2_VALUE computes a Stirling number of the second kind.\n%\n% Discussion:\n%\n% S2(N,M) represents the number of distinct partitions of N elements\n% into M nonempty sets. For a fixed N, the sum of the Stirling\n% numbers S2(N,M) is represented by B(N), called \"Bell's number\",\n% and represents the number of distinct partitions of N elements.\n%\n% For example, with 4 objects, there are:\n%\n% 1 partition into 1 set:\n%\n% (A,B,C,D)\n%\n% 7 partitions into 2 sets:\n%\n% (A,B,C) (D)\n% (A,B,D) (C)\n% (A,C,D) (B)\n% (A) (B,C,D)\n% (A,B) (C,D)\n% (A,C) (B,D)\n% (A,D) (B,C)\n%\n% 6 partitions into 3 sets:\n%\n% (A,B) (C) (D)\n% (A) (B,C) (D)\n% (A) (B) (C,D)\n% (A,C) (B) (D)\n% (A,D) (B) (C)\n% (A) (B,D) (C)\n%\n% 1 partition into 4 sets:\n%\n% (A) (B) (C) (D)\n%\n% So S2(4,1) = 1, S2(4,2) = 7, S2(4,3) = 6, S2(4,4) = 1, and B(4) = 15.\n%\n%\n% First terms:\n%\n% N/M: 1 2 3 4 5 6 7 8\n%\n% 1 1 0 0 0 0 0 0 0\n% 2 1 1 0 0 0 0 0 0\n% 3 1 3 1 0 0 0 0 0\n% 4 1 7 6 1 0 0 0 0\n% 5 1 15 25 10 1 0 0 0\n% 6 1 31 90 65 15 1 0 0\n% 7 1 63 301 350 140 21 1 0\n% 8 1 127 966 1701 1050 266 28 1\n%\n% Recursion:\n%\n% S2(N,1) = 1 for all N.\n% S2(I,I) = 1 for all I.\n% S2(I,J) = 0 if I < J.\n%\n% S2(N,M) = M * S2(N-1,M) + S2(N-1,M-1)\n%\n% Properties:\n%\n% sum ( 1 <= K <= M ) S2(I,K) * S1(K,J) = Delta(I,J)\n%\n% X**N = sum ( 0 <= K <= N ) S2(N,K) X_K\n% where X_K is the falling factorial function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of rows of the table.\n%\n% Input, integer M, the number of columns of the table.\n%\n% Output, integer VALUE, the value of S2(N,M).\n%\n if ( n <= 0 )\n value = 0;\n return\n end\n\n if ( m <= 0 )\n value = 0;\n return\n end\n\n s2(1,1) = 1;\n s2(1,2:m) = 0;\n\n for i = 2 : n\n\n s2(i,1) = 1;\n\n for j = 2 : m\n s2(i,j) = j * s2(i-1,j) + s2(i-1,j-1);\n end\n\n end\n\n value = s2(n,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/prob/stirling2_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7744764794223383}} {"text": "function trans = createScaling3d(varargin)\n%CREATESCALING3D Create the 4x4 matrix of a 3D scaling\n%\n% TRANS = createScaling3d(S);\n% returns the scaling transform corresponding to a scaling factor S in\n% each direction. S can be a scalar, or a 1x3 vector containing the\n% scaling factor in each direction.\n%\n% TRANS = createScaling3d(SX, SY, SZ);\n% returns the scaling transform corresponding to a different scaling\n% factor in each direction.\n%\n% The returned matrix has the form :\n% [SX 0 0 0]\n% [ 0 SY 0 0]\n% [ 0 0 SZ 0]\n% [ 0 0 0 0]\n%\n% See also:\n% transforms3d, transformPoint3d, transformVector3d, createTranslation3d,\n% createRotationOx, createRotationOy, createRotationOz\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 20/04/2006.\n%\n\n% HISTORY\n% 25/11/2008 rename from scale3d to scaling3d\n% 30/04/2009 rename to createScaling3d\n\n\n% process input parameters\nif isempty(varargin)\n % assert uniform scaling in each direction\n sx = 1;\n sy = 1;\n sz = 1;\nelseif length(varargin)==1\n % only one argument\n var = varargin{1};\n if length(var)==1\n % same scaling factor in each direction\n sx = var;\n sy = var;\n sz = var;\n elseif length(var)==3\n % scaling is a vector, giving different scaling in each direction\n sx = var(1);\n sy = var(2);\n sz = var(3);\n else\n error('wrong size for first parameter of \"createScaling3d\"');\n end\nelseif length(varargin)==3\n % 3 arguments, giving scaling in each direction\n sx = varargin{1};\n sy = varargin{2};\n sz = varargin{3};\nelse\n error('wrong number of arguments for \"createScaling3d\"');\nend\n\n% create the scaling matrix\ntrans = [sx 0 0 0;0 sy 0 0;0 0 sz 0;0 0 0 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/geom3d/createScaling3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7743498997145368}} {"text": "function dy_dx = parabolderiv( x, y, k, graphics_flag )\n\n% function dy_dx = parabolderiv( x, y, k, graphics_flag )\n%\n% default: example from Ref. [1], p. 322\n%\n% or try: parabolderiv( ( -2 : 0.01 : 2 )', exp( -2 : 0.01 : 2 )', 2 )\n% parabolderiv( ( -2 : 0.01 : 2 )', ( exp( -2 : 0.01 : 2 ) + 0.01 * rand( 1, 401 ) )', 25 )\n% parabolderiv( ( ( 0 : 200 * pi ) / 100 )', ( sin( 0 : 0.01 : 2 * pi ) + 0.01 * rand( 1, 629 ) )', 40 )\n% for demonstration of noisy input and edge deviations\n%\n% graphics_flag = 1: show result in graph (default) \n% (includes comparison to 2 other methods)\n% 0: show no graph\n%\n% This program differentiates an empirical function (an array of evenly\n% spaced values), for instance periodically sampled data from an\n% experiment.\n%\n% Method used: basically, a parabola is fit from k points to the left to k\n% points to the right of the point where the derivative is required, this\n% is then analytically differentiated. These calculations are not actually\n% performed, but the method as given by Lanczos in Ref. [1] is used: only\n% 1 fit parameter of the parabola is needed, which is calculated directly\n% from the data; at the edges a parabola is fit through the first (last)\n% 2k points, from which the derivative is calculated directly. Additional\n% information (on accuracy, &c.) in Ref. [2]. Noise is handled well. An \n% example from Ref. [1] is included.\n%\n% The datapoints need to be equidistant. If the graphics_flag is set, the\n% result of this method is compared to applying the standard Matlab diff()\n% function on the raw data as well as on adjacent averaged filtered data\n% (zero phase delay). The example commands given above illustrate this.\n%\n% References:\n%\n% [1] Title : Applied analysis / by Cornelius Lanczos\n% Author : Cornelius Lanczos\n% Edition : 3rd print.\n% Publisher : London : Pitman, 1964\n% Pages : 539 p.\n% Bibliographic annotation : 1st print: 1957\n% see pp. 321 - 324\n%\n% [2] Title : Digital filters / by Richard W. Hamming\n% Author : Richard W. Hamming\n% Edition : 3rd ed.\n% Publisher : Englewoood Cliffs : Prentice-Hall, 1989\n% Pages : XIV, 284 p.\n% Bibliographic annotation : 1st print: 1977\n% ISBN : 0-13-212812-8\n% see p. 137\n%\n% Last update 24-03-2004 by Robert Klein-Douwel\n% \n% mail: robertkdkd@yahoo.co.uk, R.J.H.Klein-Douwel@tue.nl\n% web: http://www.sci.kun.nl/mlf/robertkd/\n\nlinewidth = 1; % can be changed for plotting purposes\n\n% fill in some default values\n\nif nargin < 4\n graphics_flag = 1;\nend\n\nif nargin < 3 % take example from Ref. [1], p. 322\n y = [ 0\n 4\n 25\n 50\n 67.4\n 124.9\n 172.0\n 201.4\n 288.1\n 321.3\n 387.1 ];\n\n x = ( 0 : 1 : length( y ) - 1 )';\n\n k = 2;\nend\n\n% initialise stuff\n\nif length( x ) ~= length( y )\n error( 'x and y vectors have different lengths (RKD)' );\nend\n\nn = length( y ); %number of points\n\nif 2 * k + 1 > n\n error( 'k too large or too few datapoints (RKD)' );\nend\n\ndy = zeros( n, 1 );\n\n% check equidistancy of x\ndx = diff( x );\nd2x = diff( dx );\n\nrel_error_d2x = max( abs( d2x ) ) / min( dx );\nif rel_error_d2x > 401 * eps\n % vectors like ( -2 : 0.01 : 2 ) are not equidistant, but have a small variation \n % in dx and d2x; if this is not more than 401 * eps, then it is neglected\n disp( [ 'relative error in d2x = ' num2str( rel_error_d2x ) ] );\n disp( [ 'relative error / eps = ' num2str( rel_error_d2x / eps ) ] );\n disp( [ 'min( d2x ) = ' num2str( min( d2x ) ) ] );\n disp( [ 'max( d2x ) = ' num2str( max( d2x ) ) ] );\n error( 'non-equidistant data points (RKD)' );\nend\nh = dx( 1 ); % stepsize\n\n% start calculations\ndy_denominator = 2 * h * sum( ( 1 : k ).^2 );\n\na = - k : + k;\nfor i = k + 1 : n - k\n dy( i ) = sum( a .* y( i + a )' );\nend\n\ndy = dy / dy_denominator;\n\n% first and last k points:\n% fit parabola over first and last 2k points\nkk = 2 * k;\n\n% first kk points\np1 = polyfit( x( 1 : kk ), y( 1 : kk ), 2 );\nq1 = polyder( p1 ); % take derivative\ndy( 1 : k ) = polyval( q1, x( 1 : k ) );\n\n% last kk points\np2 = polyfit( x( n - kk + 1 : n ), y( n - kk + 1 : n ), 2 );\nq2 = polyder( p2 ); % take derivative\ndy( n - k + 1 : n ) = polyval( q2, x( n - k + 1 : n ) );\n\nif nargout ~= 0 % output\n dy_dx = dy;\nend\n\n% end of calculations (everything below is just for making comparisons and nice output)\n\nif graphics_flag == 1 % make some comparisons\n xdiff_range = x( 1 : n - 1 ) + h / 2; % x coordinates for results of diff() function\n\n % compare with diff()\n dydx_matlab = diff( y ) / h;\n\n if nargin >=3 % not enough data points in example to apply this filter\n\n % another test: try first adjacent averaging and then diff()\n % use k points to left and to right\n kkk = 2 * k + 1;\n b = ones( 1, kkk ) / kkk; % k point averaging filter\n y_filt = filtfilt( b, 1, y ); % noncausal filtering, zero phase distortion\n\n % calculate dy_filt/dx\n dy_filtdx = diff( y_filt ) / h;\n end\n\n if nargin < 3 % show results of example\n disp( ' x y dy' );\n disp( [ x, y, dy ] );\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% show results\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif graphics_flag == 1\n if nargout == 0\n close all;\n end\n\n dx_idx_range = k + 1 : n - k;\n\n % parabolic fits to first (last) kk points\n x1_fit = min( x( 1 : kk ) ) : h / 100 : max( x( 1 : kk ) );\n y1_fit = polyval( p1, x1_fit );\n\n x2_fit = min( x( n - kk + 1 : n ) ) : h / 100 : max( x( n - kk + 1 : n ) );\n y2_fit = polyval( p2, x2_fit );\n\n figure;\n hold on;\n plot( x, y, '-ob', 'LineWidth', linewidth );\n plot( x( dx_idx_range ), dy( dx_idx_range ), '-or', 'LineWidth', linewidth );\n plot( x( 1 : k ), dy( 1 : k ), '-sr', 'LineWidth', linewidth );\n plot( x1_fit, y1_fit, '--r', 'LineWidth', linewidth );\n plot( xdiff_range, dydx_matlab, ':sg', 'LineWidth', linewidth );\n\n if nargin >= 3\n plot( xdiff_range, dy_filtdx, ':dm', 'LineWidth', linewidth );\n end\n\n legend( 'y', [ 'dy/dx_{Lanczos: {\\pm}' num2str( k ) '}' ], ...\n [ 'first/last ' num2str( k ) ' pts' ], ...\n [ 'y_{fit, parabola, ' num2str( kk ) ' pts}' ], 'diff( y )/ dx', ...\n [ 'diff( y_{adj avg ({\\pm}' num2str( k ) ')} )/ dx' ], 0 );\n\n plot( x( n - k + 1 : n ), dy( n - k + 1 : n ), '-sr', 'LineWidth', linewidth );\n plot( x2_fit, y2_fit, '--r', 'LineWidth', linewidth );\n\n plot( x, dy, '-r', 'LineWidth', linewidth );\n\n % replot to put these on top again\n plot( x( dx_idx_range ), dy( dx_idx_range ), '-or', 'LineWidth', linewidth );\n plot( x( 1 : k ), dy( 1 : k ), '-sr', 'LineWidth', linewidth );\n hold off;\n\n xlabel( 'x' );\n ylabel( 'y' );\n\n title( 'parabolic derivative (Lanczos)' );\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/4675-parabolderiv/parabolderiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7743099527051989}} {"text": "classdef VonMisesD\n%%VONMISESD Functions to handle the von Mises distribution, which is a\n% common circular distribution. The distribution is given in Chapter\n% 3.5.4 of [1].\n%Implemented methods are: circVar, PDF, CDF,trigMoment, normProdDist,\n% convDistApprox, params4TrigMoment, rand, entropy\n%\n%REFERENCES:\n%[1] K. V. Mardia and P. E. Jupp, Directional Statistics. Chichester: John\n% Wiley and Sons, 2000.\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n \nfunction val=circVar(kappa)\n%%CIRCVAR Obtain the circular variance of a particular von Mises\n% distribution.\n%\n%INPUTS: kappa The concentration of the distribution 0<=kappa=1.\n% mu The mean direction of the distribution. This is normally between\n% -pi and pi.\n% kappa The concentration of the distribution 0<=kappa500, the results might be inaccurate.\n%\n%OUTPUTS: rho The (complex) mean resultant value for the nth moment. Note\n% that rho=R*exp(1j*theta).\n% theta The (real) trigonometric mean angle in radians for the nth\n% moment. This is between -pi and pi.\n% R The (real) mean resultant length for the nth moment.\n%\n%The moments of a von Mises distribution are given in Chapter 2.2.4 of [1]\n%and Chapter 3.5.4 of [2].\n%\n%EXAMPLE:\n%Here, we verify the first trigonometric moment based on samples.\n% numRuns=1e5;\n% kappa=100;\n% mu=0.25;\n% x=VonMisesD.rand([numRuns,1],mu,kappa);\n% [rhoS,thetaS,RS]=findTrigMomentFromSamp(1,x);\n% [rho,theta,R]=VonMisesD.trigMoment(1,mu,kappa);\n% abs(rhoS-rho)\n% abs(thetaS-theta)\n% abs(RS-R)\n%Here, we will see that the errors tend to be on the order of 1e-4,\n%dominated by the angular error.\n%\n%REFERENCES:\n%[1] S. R. Jammalamadaka and A. SenGupta, Topics in Circular Statistics.\n% Singapore: World Scientific, 2001.\n%[2] K. V. Mardia and P. E. Jupp, Directional Statistics. Chichester: John\n% Wiley and Sons, 2000.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n%For n=1 or 2, there should be no need to use anything but the default\n%maximum number of iterations in BesseliRatio.\nif(n==1)\n rho=BesseliRatio(1,kappa)*exp(1j*n*mu);\nelseif(n==2)\n rho=BesseliRatio(2,kappa)*BesseliRatio(1,kappa)*exp(1j*n*mu);\nelse\n rho=besseli(n,kappa,1)/besseli(0,kappa,1)*exp(1j*n*mu);\nend\n\nif(nargout>1)\n theta=angle(rho);\n R=abs(rho);\nend\nend\n\nfunction [mu,kappa]=normProdDist(mu1,kappa1,mu2,kappa2)\n%%NORMPRODDIST The product of two von Mises distributions is an\n% unnormalized von Mises distribution. This finds the\n% parameters of the product distribution.\n%\n%INPUTS: mu1, kappa1 The mean direction and concentration of the first\n% distribution. Note that 0<=kappa0)\n break;\n end\n\n %Step 3\n if(log(c/u2)+1-c>=0)\n break;\n end\n end\n %Step 4\n u3=2*rand(1)-1;%In range [-1,1]\n vals(curSamp)=wrapRange(sign(u3)*acos(f)+mu,-pi,pi);\n end\nend\n \nfunction entropyVal=entropy(kappa)\n%%ENTROPY Obtain the differential entropy of the von Mises distribution\n% given in nats. The differential entropy of a continuous\n% distribution is entropy=-int_x p(x)*log(p(x)) dx where the\n% integral is over all values of x. Units of nats mean that the\n% natural logarithm is used in the definition. Unlike the Shannon\n% entropy for discrete variables, the differential entropy of\n% continuous variables can be both positive and negative.\n%\n%INPUTS: kappa The concentration of the distribution 0<=kappa1\n for a=2:n\n q=zeros(a*m,a);\n r=2:a+1;\n ix=1:m;\n for b=1:a\n q(ix,1)=b;\n q(ix,2:a)=r(p);\n r(b)=b;\n ix=ix+m;\n end\n m=m*a;\n p=q;\n end\nend\nif nargout>1 s=1-2*rem(fix((1:m)'/2),2); end\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/permutes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.774230112899813}} {"text": "function [tri, x] = delaunay_sphere(N, xi)\n% DELAUNAY_SPHERE Triangulation of a sphere or a surface topologically\n% equivalent to a sphere so that it can be used as a mesh\n%\n% [TRI, X] = delaunay_sphere(N)\n%\n% Number of samples of the sphere (in latitude and longitude).\n%\n% TRI is a 3-column matrix with a triangulation of the sphere. Each\n% element in TRI is an index to a row in X. Each row represents the three\n% vertices of a triangle on the sphere.\n%\n% X is a 3-column matrix with the Euclidean coordinates of the\n% triangulation vertices.\n%\n% The surface can be plotted running\n%\n% trisurf(tri, x(:, 1), x(:, 2), x(:, 3));\n%\n% ... = delaunay_sphere(N, XI)\n%\n% XI is an (N+1,N+1,3)-array with the coordinates of the vertices of a\n% surface topologically equivalent to a sphere. By default, XI is the\n% concatenation of the output of sphere(N), and the surface is a unit\n% sphere.\n%\n% The surface can be plotted running\n%\n% surf(xi(:, :, 1), xi(:, :, 2), xi(:, :, 3))\n%\n% See also: scimat_tri_to_raster.\n\n% Author: Ramon Casero \n% Copyright © 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\n% check arguments\nnarginchk(1, 2);\nnargoutchk(0, 2);\n\nif (nargin > 1 ...\n && (size(xi, 1) ~= N+1 || size(xi, 2) ~= N+1 || size(xi, 3) ~= 3))\n error('XI must be a (N+1, N+1, 3) array')\nend\n\n% sphere surface\n[x, y, z] = sphere(N);\n\n% remove repeated points\n[x, idx] = unique([x(:) y(:) z(:)], 'rows');\n\n% triangulate the sphere and extract the surface\ntri = DelaunayTri(x);\ntri = freeBoundary(tri);\n\n% if an input point configuration was provided, we use it to replace the\n% unit sphere points coordinates\nif (nargin > 1)\n xi = reshape(xi, (N+1)*(N+1), 3);\n x = xi(idx, :);\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ManifoldToolbox/delaunay_sphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.7742301123285761}} {"text": "function [CL, u_U, v_U, w_U, l_t, l_s] = LiftCoeff(gamma, panel, geo, Fu_bar, Fv_bar, Fw_bar)\n%Determine the lift coefficient given the vortex strengths\n%and the influence coefficients from the vortex lattice method\n\nu_U.c = 1/(4*pi)*Fu_bar*[gamma.c]'; %Eqn 25 in NASA paper\nv_U.c = 1/(4*pi)*Fv_bar*[gamma.c]'; %Eqn 23 in NASA paper\nw_U.c = 1/(4*pi)*Fw_bar*[gamma.c]';\n\nu_U.alpha = 1/(4*pi)*Fu_bar*[gamma.alpha]';\nv_U.alpha = 1/(4*pi)*Fv_bar*[gamma.alpha]';\nw_U.alpha = 1/(4*pi)*Fw_bar*[gamma.alpha]';\n\nfor i = 1:geo.ns\n for j = 1:geo.nc\n if i == geo.ns %wingtip\n DeltaGamma(i,j).c = gamma(i,j).c;\n DeltaGamma(i,j).alpha = gamma(i,j).alpha;\n elseif j == 1 %Leading edge\n DeltaGamma(i,j).c = gamma(i,j).c-gamma(i+1,j).c;\n DeltaGamma(i,j).alpha = gamma(i,j).alpha-gamma(i+1,j).alpha;\n else\n DeltaGamma(i,j).c = DeltaGamma(i,j-1).c + gamma(i,j).c - gamma(i+1,j).c;\n DeltaGamma(i,j).alpha = DeltaGamma(i,j-1).alpha + gamma(i,j).alpha - gamma(i+1,j).alpha;\n end\n end\nend\n\nl_t.c = 2/geo.S*[DeltaGamma.c]'.*[panel.cc]'.*[v_U.c]; %Eqn 24 in NASA paper\nl_t.alpha = 2/geo.S*[DeltaGamma.alpha]'.*[panel.cc]'.*[v_U.alpha]; %Eqn 24 in NASA paper\n\nl_s.c = 2/geo.S*[gamma.c]'*2.*[panel.s]'.*((ones(size(u_U))-[u_U.c])+[v_U.c].*tan([panel.sweep]'))*cos(geo.dih); %Eqn 28 in NASA paper\nl_s.alpha = 2/geo.S*[gamma.alpha]'*2.*[panel.s]'.*((ones(size(u_U))-[u_U.alpha])+[v_U.alpha].*tan([panel.sweep]'))*cos(geo.dih); %Eqn 28 in NASA paper\n\n% reshape([l_t.c],geo.ns,geo.nc)\n% reshape([l_t.alpha],geo.ns,geo.nc)\n% reshape([l_s.c],geo.ns,geo.nc)\n% reshape(((ones(size(u_U))-[u_U.alpha])+[v_U.alpha].*tan([panel.sweep]')),geo.ns,geo.nc)\n% reshape([panel.s],geo.ns,geo.nc)\n% reshape([l_s.alpha],geo.ns,geo.nc)\n% reshape([u_U.alpha],geo.ns,geo.nc)\n% reshape([v_U.alpha],geo.ns,geo.nc)\n% reshape([gamma.alpha],geo.ns,geo.nc)\n% sum([gamma.c])\n% geo.S\n\nCL.c = 2*(sum([l_t.c])+sum([l_s.c]));\nCL.alpha = 2*(sum([l_t.alpha])+sum([l_s.alpha]));\n\n", "meta": {"author": "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/LiftCoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654164300481, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7742178185985863}} {"text": "classdef grassmannian < handle\n % Ways to generate Grassmannian frames.\n properties\n end\n\n methods(Static)\n\n function result = minimum_coherence(m, n)\n % Returns the minimum coherence of an m times n matrix\n num = n - m;\n den = m * (n - 1);\n result = sqrt(num / den);\n end\n\n function n = n_upper_bound(m)\n % for a given value of m, returns the upper bound on n.\n a = m * (m + 1) / 2;\n n = m * (m + 1) / 2 - 1;\n lower_limit = m;\n while true\n b = (n - m) * (n - m + 1) / 2;\n upper_limit = min (a, b);\n if n < upper_limit\n break;\n end\n n = n- 1;\n end\n end\n function [ns, coherences] = min_coherence_max_n(ms)\n if ~isvector(ms)\n error('ms must be a vector');\n end\n mm = length(ms);\n ns = zeros(1, mm);\n coherences = zeros(1, mm);\n for i=1:mm\n m = ms(i);\n n = spx.dict.grassmannian.n_upper_bound(m);\n ns(i) = n;\n coherences(i) = spx.dict.grassmannian.minimum_coherence(m, n);\n end\n end\n\n function n = max_n_for_coherence(m, mu)\n % estimates a value of n for m x n matrix which achieves a \n % given coherence\n num = (mu^2 -1) * m;\n den = mu^2 * m - 1;\n n = floor(num / den);\n if n < 0\n error('A Grassmannian frame for this dimension will never have so high coherence.');\n end\n end\n\n function result = alternate_projections(dict, options)\n % Converts a given dictionary to Grassmannian frame via\n % alternate projections\n [n, d] = size(dict);\n % We assume that the dictionary contains unit norm atoms\n target_mu = spx.dict.grassmannian.minimum_coherence(n, d);\n % Compute the Gram matrix\n gram_matrix = dict' * dict;\n iterations = 1000;\n entry_shrinkage_factor = 0.9;\n coherence_shrinkage_factor = 0.9;\n verbose = false;\n if nargin > 1 && isstruct(options)\n if isfield(options, 'iterations')\n iterations = options.iterations;\n end\n if isfield(options, 'entry_shrinkage_factor')\n entry_shrinkage_factor = options.entry_shrinkage_factor;\n end\n if isfield(options, 'coherence_shrinkage_factor')\n coherence_shrinkage_factor = options.coherence_shrinkage_factor;\n end\n if isfield(options, 'verbose')\n verbose = options.verbose;\n end\n end\n total_entries = d^2 - d; % excluding the main diagonal.\n % Identify the indices in the gram matrix which are off diagonal\n off_diagonal_indices = abs(gram_matrix(:) - 1)> 1e-6;\n coherence_array = zeros(iterations, 1);\n mean_coherence_array = zeros(iterations, 1);\n for k=1:iterations\n % Convert gram matrix to an array\n gram_array = gram_matrix(:);\n % Absolute Gram matrix\n abs_gram_array = abs(gram_array);\n % sort the inner products by their absolute values\n sorted_gram_array = sort(abs_gram_array);\n upper_threhold_index = round(entry_shrinkage_factor * total_entries);\n upper_threshold = sorted_gram_array(upper_threhold_index);\n % identify coherence values above the threshold\n above_indices = off_diagonal_indices & (abs_gram_array > upper_threshold);\n % map the boolean flags to positions.\n above_indices = find(above_indices);\n above_values = abs_gram_array(above_indices);\n current_mu = max(above_values);\n mean_mu = mean(above_values);\n coherence_array(k) = current_mu;\n mean_coherence_array(k) = mean_mu;\n if verbose\n fprintf('%6d:, Coherence:: target: %12.8f, ', k, target_mu);\n fprintf('current: %12.8f, threshold: %12.8f, above: %d, mean: %12.8f\\n', ...\n current_mu, upper_threshold, length(above_values), mean_mu);\n else\n fprintf('.');\n if mod(k, 100) == 0\n fprintf('\\n');\n end\n end\n % Update off diagonal entries\n gram_matrix(above_indices)=gram_matrix(above_indices)*coherence_shrinkage_factor;\n \n % reduce the rank back to n\n [U,S,V]=svd(gram_matrix);\n % Ensure that all higher singular values are set to 0. \n S(n+1:end,n+1:end)=0;\n % Reconstruct the Gram matrix.\n gram_matrix=U*S*V';\n % Ensure that the diagonal elements of G continue to be 1.\n % Compute d = diag(G) d^{-1/2}.\n gram_diag_sqrt_inv = diag(1./sqrt(diag(gram_matrix)));\n % Compute G = d^{-1/2} G d^{-1/2}.\n gram_matrix = gram_diag_sqrt_inv*gram_matrix*gram_diag_sqrt_inv;\n end\n % final dictionary\n % perform SVD of the gram matrix.\n [U,S,V]=svd(gram_matrix);\n % Construct the dictionary \n dict=S(1:n,1:n).^0.5*U(:,1:n)';\n result.dictionary = dict;\n result.coherence_array = coherence_array;\n result.mean_coherence_array = mean_coherence_array;\n result.target_coherence = target_mu;\n result.iterations = iterations;\n end\n end\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/grassmannian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7742178112262499}} {"text": "%% KEOLLOGG Problem\n%\n% KELLOGG solves a diffusion equation with jump coefficients with AFEM.\n%\n% KELLOGG solves the problem within maxN number of vertices. The\n% input argument theta is a parameter used in the marking step. \n%\n% The KELLOGG command, if no input arguments, use maxN = 5e3 and theta = 0.5. \n%\n% EXAMPLE\n%\n% Kellogg \n%\n% See also crack, Lshape\n%\n% TODO: rewrite M-lint\n%\n% Created by Chen-Song Zhang. Modified by Long Chen.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all\n%% Problem setting\n% $$-\\nabla\\cdot(d\\nabla u) = 0 \\quad \\Omega = (-1,1)\\times (-1,1)$$ \n%\n% $$u = g_D \\quad \\partial \\Omega$$\n%\n% The diffusion constant is discontinous; see the figure below. We set a2 = \n% 1; a1 = 161.4476387975881 and choose boundary condition g_D such that the\n% exact solution is $z = r^{0.1}\\mu(\\theta)$ in the poloar coordinate, where\n% the formula of mu can be found in exactu function.\n\n[x,y] = meshgrid(-1:1:1,-1:1:1); \nz = 0*x;\nsurf(x,y,z,'linewidth',2); view(2);\naxis equal; axis tight;\ntext(0.5,0.5,'a1','FontSize',12,'FontWeight','bold');\ntext(-0.5,-0.5,'a1','FontSize',12,'FontWeight','bold');\ntext(-0.5,0.5,'a2','FontSize',12,'FontWeight','bold');\ntext(0.5,-0.5,'a2','FontSize',12,'FontWeight','bold');\n\n%% Parameters\nmaxN = 3e3; theta = 0.2; maxIt = 1000; \nN = zeros(maxIt,1); uIuhErr = zeros(maxIt,1);\nerrH1 = zeros(maxIt,1);\n\n%% Generate an initial mesh\n[node,elem] = squaremesh([-1 1 -1 1], 0.25);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% Set up PDE data\npde = Kelloggdata;\n\n%% Adaptive Finite Element Method\n% *SOLVE* -> *ESTIMATE* -> *MARK* -> *REFINE*\n\nfor k = 1:maxIt\n % Step 1: SOLVE\n [u,Du,eqn] = Poisson(node,elem,pde);\n % Plot mesh and solution\n figure(1); showresult(node,elem,u,[27,26]); \n % Step 2: ESTIMATE\n eta = estimaterecovery(node,elem,u); % recovery type\n% eta = estimateresidual(node,elem,u,pde); % residual type\n % Record error and number of vertices\n uI = pde.exactu(node);\n uIuhErr(k) = sqrt((uI-u)'*eqn.A*(uI-u));\n errH1(k) = getH1error(node,elem,@pde.Du,u);\n N(k) = size(node,1);\n if (N(k)>maxN), break; end \n % Step 3: MARK\n markedElem = mark(elem,eta,theta);\n % Step 4: REFINE\n [node,elem,bdFlag] = bisect(node,elem,markedElem,bdFlag);\nend\n\n%% Plot convergent rates in energy norm\nN = N(1:k); \nuIuhErr = uIuhErr(1:k);\nerrH1 = errH1(1:k);\nfigure(2)\nshowrate2(N,uIuhErr,10,'-*','||Du_I-Du_h||',...\n N,errH1,10,'k-.','||Du-Du_h||');", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/example/2D/Kellogg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.8652240843146881, "lm_q1q2_score": 0.7741934013179959}} {"text": "function [L] = lap2DDir(N, h);\n%\n% [L] = lap2DDir(N, h)\n%\n% Constructs the 2D Laplacian for a square mesh with zero Dirichlet \n% boundary conditions using the standard 5-point stencil.\n%\n% Returns:\n% L = discrete Laplacian\n%\n% Input:\n% N = number of mesh points in each direction\n% h = mesh width\n%\n%\n%\n% License: This code is free to use for any purposes, provided\n% any publications resulting from the use of this code\n% reference the original code/author.\n%\n% Author: Samuel Isaacson (isaacson@math.utah.edu)\n% Date: 11/2007\n%\n% Please notify the author of any bugs, and contribute any\n% modifications or bug fixes back to the original author.\n%\n% Disclaimer:\n% This code is provided as is. The author takes no responsibility \n% for its results or effects.\n\nM = N * N;\n\n\n% 2D Laplace Operator on Square:\ne = ones(M,1);\ned = -4*e;\neu1 = ones(M,1);\neu1((N+1):N:M) = 0;\ned1 = ones(M,1);\ned1(N:N:M) = 0;\n \nL = spdiags([e ed1 ed eu1 e], [-N -1:1 N], M, M);\n\n\nL = L ./ (h*h);\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/IBM/lap2DDir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7741902084857618}} {"text": "function diff = getDiffuseness_SV(i_vecs)\n%GETDIFFUSENESS_SV Compute the DoA spherical variance diffuseness \n% \n% This routine estimates diffuseness based on the assumption that DoA \n% estimates should have a small variance around the source DoA, if the\n% direct-to-diffuse ratio is high, and be completely uniformly\n% distributed if the sound is fully diffuse. This variation can be\n% captured on the spherical variance of the DoA estimates. The method can\n% utilize intensity vectors, or any other vectors that indicate DoAs. The\n% statistics can be computed from multiple temporal observations or\n% across different frequency bands. This estimator has been used e.g. in\n%\n% Politis, A., Delikaris-Manias, S. and Pulkki, V., 2015. \n% Direction-of-arrival and diffuseness estimation above spatial aliasing for symmetrical directional microphone arrays. \n% In 2015 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP).\n%\n% Inputs:\n% i_vecs: Kx3 matrix of DoA vectors, for K temporal or frequency\n% observations\n%\n% Outputs:\n% diff: diffuseness value\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GETDIFFUSENESS_SV.M - 5/10/2016\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% unit DoA vectors\ndoa_vecs = i_vecs ./ (sqrt(sum(i_vecs.^2,2))*ones(1,3));\n% mean DoA vector\nmean_doa_vec = mean(doa_vecs,1);\n% spherical variance\ndiff = 1 - sqrt(sum(mean_doa_vec.^2, 2));\n\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Array-Processing", "sha": "f08bed9b80ce580f9056fd6573ab0c08588ebc11", "save_path": "github-repos/MATLAB/polarch-Spherical-Array-Processing", "path": "github-repos/MATLAB/polarch-Spherical-Array-Processing/Spherical-Array-Processing-f08bed9b80ce580f9056fd6573ab0c08588ebc11/getDiffuseness_SV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.774178588955101}} {"text": "% Author : FUAT COGUN\n% Date : 16.07.2009\n%\n%\n% Find the Covariance Matrix of given region.\n% \n%\n% Inputs : -I (uint8 Matrix)\n% ====== -x position (Integer)\n% -y position (Integer)\n% -size (Integer)\n%\n% Outputs : -Covariance Matrix (7x7 Matrix)\n% ======= \n\nfunction CR = findCovarianceMatrix(I, positionX, positionY, size) \n\n % First and second derivatives\n d = [-1 0 1];\n dd = [-1 2 -1];\n dI = double(I);\n\n % Ix, Iy, Ixx, Iyy\n Ix = conv2(d, dI);\n Iy = conv2(d,1,dI);\n Ixx = conv2(dd, dI);\n Iyy = conv2(dd,1,dI);\n\n for j = 1:size\n for i = 1:size\n\n f(i+(j-1)*size,:) = [positionX+i-1 positionY+j-1 dI(positionY+j-1, positionX+i-1) ...\n Ix(positionY+j-1, positionX+i-1) Iy(positionY+j-1, positionX+i-1) ...\n Ixx(positionY+j-1, positionX+i-1) Iyy(positionY+j-1,positionX+i-1)];\n\n end\n end\n\n % vector of means of features in region R\n uR = mean(f);\n\n T = zeros(7);\n for k = 1:size^2\n temp = (f(k,:)-uR)'*(f(k,:)-uR);\n T = T + temp;\n end\n\n CR = (1/size^2)*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/25435-a-ball-tracking-application/findCovarianceMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7741690783228501}} {"text": "% DEMO -- Chebyshev Polynomial Integral\n% UPDATED -- October 28, 2013\n% Written by Matthew Kelly, Cornell University\n%\n% This demo is designed to show how to compute integrals of chebyshev\n% polynomials.\n%\n% Results - Note that there are relative large errors between the chebyshev\n% approximation of the integral and the analytic integral, BUT the last\n% value (which is the value of the definite integral) is very accurate.\n% \n% The last point is so accurate because it is the solution to the definite\n% integral over the domain using Clenshaw-Curtis quadrature for an order\n% \"order\" accurate polynomial.\n%\n\n%% General Settings\nclear; clc;\n\n%What order should the approximation be?\norder = 50;\n\n%What domain should we be looking at?\nd = [0,1];\n\n%Get chebyshev values at the nodes:\n[x,w] = chebyshevPoints(order+1,d);\n[~,f] = testFunction(x);\nIf= chebyshevIntegral(f,d);\n\n%Set the time vector\ntime = linspace(d(1),d(2),10000);\n[Ig, g] = testFunction(time);\n\n%Adjust the constants of integration S.T. they all start at zero:\nIg = Ig-Ig(1);\n\n%Interpolate the chebyshev approximations:\ny = chebyshevInterpolate(f,time,d);\nIy = chebyshevInterpolate(If,time,d);\n\n%Show results\nfigure(407); clf; \nsubplot(2,2,1); hold on;\n plot(time,g,'b-','LineWidth',2) \n plot(x,f,'ko','MarkerSize',5);\n title(['function approximation - order ' num2str(order)]);\n legend('Analytic','Cheb. nodes','Location','NorthWest')\nsubplot(2,2,3); hold on;\n plot(time,Ig,'b-','LineWidth',2) \n plot(x,If,'ko','MarkerSize',5);\n title(['integral approximation - order ' num2str(order)]);\n legend('Analytic','Cheb. nodes','Location','NorthWest')\nsubplot(2,2,2);\n semilogy(time,abs(g-y)) \n title('error in function');\nsubplot(2,2,4); hold on;\n semilogy(time,abs(Ig-Iy)) \n semilogy(time(end),abs(Ig(end)-Iy(end)),...\n 'bo','MarkerSize',10,'LineWidth',2) \n title(['error in definite integral: ' num2str(Ig(end)-Iy(end))]);\n set(gca,'yscale','log')\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/chebyshevPolynomials/DEMO_8_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7741528149988885}} {"text": "function [ pn, dist ] = circle_arc_point_near_2d ( r, center, theta1, ...\n theta2, p )\n\n%*****************************************************************************80\n%\n%% CIRCLE_ARC_POINT_NEAR_2D : nearest point on a circular arc.\n%\n% Discussion:\n%\n% A circular arc is defined by the portion of a circle (R,C)\n% between two angles (THETA1,THETA2).\n%\n% Thus, a point (X,Y) on a circular arc satisfies\n%\n% ( X - C(1) ) * ( X - C(1) ) + ( Y - C(2) ) * ( Y - C(2) ) = R * R\n%\n% and\n%\n% Theta1 <= Theta <= Theta2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Input, real CENTER(2,1), the center of the circle.\n%\n% Input, real THETA1, THETA2, the angles defining the arc,\n% in radians. Normally, THETA1 < THETA2.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, real PN(2,1), a point on the circular arc which is\n% nearest to the point.\n%\n% Output, real DIST, the distance to the nearest point.\n%\n dim_num = 2;\n%\n% Special case, the zero circle.\n%\n if ( r == 0.0 )\n pn(1:dim_num,1) = center(1:dim_num,1);\n dist = sqrt ( sum ( ( p(1:dim_num,1) - pn(1:dim_num,1) ).^2 ) );\n return\n end\n%\n% Determine the angle made by the point.\n%\n theta = atan4 ( p(2,1) - center(2,1), p(1,1) - center(1,1) );\n%\n% If the angle is between THETA1 and THETA2, then you can\n% simply project the point onto the arc.\n%\n if ( r8_modp ( theta - theta1, 2.0 * pi ) <= ...\n r8_modp ( theta2 - theta1, 2.0 * pi ) )\n\n r2 = sqrt ( sum ( ( p(1:dim_num,1) - center(1:dim_num,1) ).^2 ) );\n\n pn(1:dim_num,1) = center(1:dim_num,1) ...\n + ( p(1:dim_num,1) - center(1:dim_num,1) ) * r / r2;\n%\n% Otherwise, if the angle is less than the negative of the\n% average of THETA1 and THETA2, it's on the side of the arc\n% where the endpoint associated with THETA2 is closest.\n%\n elseif ( r8_modp ( theta - 0.5 * ( theta1 + theta2 ), 2.0 * pi ) <= pi )\n\n pn(1:dim_num,1) = center(1:dim_num,1) + r * [ cos ( theta2 ), sin ( theta2 ) ];\n%\n% Otherwise, the endpoint associated with THETA1 is closest.\n else\n\n pn(1:dim_num,1) = center(1:dim_num,1) + r * [ cos ( theta1 ), sin ( theta1 ) ];\n\n end\n\n dist = sqrt ( sum ( ( p(1:dim_num,1) - pn(1:dim_num,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/circle_arc_point_near_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7741072330030734}} {"text": "function [xi,w]=fifthOrderTriangleCubPoints()\n%%FIFTHORDERTRIANGLECUBPOINTS Obtain fifth-order cubature points for\n% integration over a triangle in 2D. The points and weights are for the\n% triangle with vertices (1,0), (0,1), (0,0), but can be transformed to\n% any triangle using transformSimplexTriPoints.\n%\n%INPUTS: None\n%\n%OUTPUTS: xi A 2XnumCubPoints set of points for the standard triangle.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the triangle (1/2).\n%\n%This function implements the points given in [1] (7 points).\n%\n%EXAMPLE:\n%Given the vertices of the simplex, we compare a fifth-order moment\n%computed using these cubature points to one computed using\n%monomialIntSimplex. The results are the same within typical finite\n%precision limits.\n% [xi,w]=fifthOrderTriangleCubPoints();\n% alpha=[3;2];\n% theMoment=findMomentFromSamp(alpha,xi,w)\n% intVal=monomialIntSimplex(alpha)\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=[-0.33333333333333333333333333333333333333, -0.33333333333333333333333333333333333333, 0.45;\n -0.79742698535308732239802527616975234389, 0.59485397070617464479605055233950468778, 0.25187836108965430519136789100036266732;\n 0.59485397070617464479605055233950468778, -0.79742698535308732239802527616975234389, 0.25187836108965430519136789100036266732;\n -0.79742698535308732239802527616975234389, -0.79742698535308732239802527616975234389, 0.25187836108965430519136789100036266732;\n -0.059715871789769820459117580973104798968, -0.88056825642046035908176483805379040206, 0.26478830557701236147529877566630399935;\n -0.88056825642046035908176483805379040206, -0.059715871789769820459117580973104798968, 0.26478830557701236147529877566630399935;\n -0.059715871789769820459117580973104798968, -0.059715871789769820459117580973104798968, 0.26478830557701236147529877566630399935];\nw=M(:,3);\nxi=M(:,1:2)';\n%Transform the points to the standard triangle.\nv1=[-1,-1, 1;\n -1, 1,-1];\nv2=[1,0,0;\n 0,1,0];\n[A,d]=affineTransBetweenTriangles(v1,v2);\nxi=bsxfun(@plus,A*xi,d);\nw=w/4;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Simplex/Triangles/fifthOrderTriangleCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7741072205054363}} {"text": "function point = intersectLines(line1, line2, varargin)\n%INTERSECTLINES Return all intersection points of N lines in 2D.\n%\n% PT = intersectLines(L1, L2);\n% returns the intersection point of lines L1 and L2. L1 and L2 are 1-by-4\n% row arrays, containing parametric representation of each line (in the\n% form [x0 y0 dx dy], see 'createLine' for details).\n% \n% In case of colinear lines, returns [Inf Inf].\n% In case of parallel but not colinear lines, returns [NaN NaN].\n%\n% If each input is [N*4] array, the result is a [N*2] array containing\n% intersections of each couple of lines.\n% If one of the input has N rows and the other 1 row, the result is a\n% [N*2] array.\n%\n% PT = intersectLines(L1, L2, EPS);\n% Specifies the tolerance for detecting parallel lines. Default is 1e-14.\n%\n% Example\n% line1 = createLine([0 0], [10 10]);\n% line2 = createLine([0 10], [10 0]);\n% point = intersectLines(line1, line2)\n% point = \n% 5 5\n%\n% See also \n% lines2d, edges2d, intersectEdges, intersectLineEdge\n% intersectLineCircle\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2003-10-31\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n%% Process input arguments\n\n% extract tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% check size of each input\nN1 = size(line1, 1);\nN2 = size(line2, 1);\nN = max(N1, N2);\nif N1 ~= N2 && N1*N2 ~= N\n error('matGeom:IntersectLines:IllegalArgument', ...\n 'The two input arguments must have same number of lines');\nend\n\n\n%% Check parallel and colinear lines\n\n% coordinate differences of origin points\ndx = bsxfun(@minus, line2(:,1), line1(:,1));\ndy = bsxfun(@minus, line2(:,2), line1(:,2));\n\n% indices of parallel lines\ndenom = line1(:,3) .* line2(:,4) - line2(:,3) .* line1(:,4);\npar = abs(denom) < tol;\n\n% indices of colinear lines\ncol = abs(dx .* line1(:,4) - dy .* line1(:,3)) < tol & par ;\n\n% initialize result array\nx0 = zeros(N, 1);\ny0 = zeros(N, 1);\n\n% initialize result for parallel lines\nx0(col) = Inf;\ny0(col) = Inf;\nx0(par & ~col) = NaN;\ny0(par & ~col) = NaN;\n\n% in case all line couples are parallel, return\nif all(par)\n point = [x0 y0];\n return;\nend\n\n\n%% Extract coordinates of itnersecting lines\n\n% indices of intersecting lines\ninds = ~par;\n\n% extract base coordinates of first lines\nif N1 > 1\n line1 = line1(inds,:);\nend\nx1 = line1(:,1);\ny1 = line1(:,2);\ndx1 = line1(:,3);\ndy1 = line1(:,4);\n\n% extract base coordinates of second lines\nif N2 > 1\n line2 = line2(inds,:);\nend\nx2 = line2(:,1);\ny2 = line2(:,2);\ndx2 = line2(:,3);\ndy2 = line2(:,4);\n\n% re-compute coordinate differences of origin points\ndx = bsxfun(@minus, line2(:,1), line1(:,1));\ndy = bsxfun(@minus, line2(:,2), line1(:,2));\n\n\n%% Compute intersection points\n\ndenom = denom(inds);\nx0(inds) = (x2 .* dy2 .* dx1 - dy .* dx1 .* dx2 - x1 .* dy1 .* dx2) ./ denom ;\ny0(inds) = (dx .* dy1 .* dy2 + y1 .* dx1 .* dy2 - y2 .* dx2 .* dy1) ./ denom ;\n\n% concatenate result\npoint = [x0 y0];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/intersectLines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7740995750586478}} {"text": "function [m,v]=v_chimv(n,l,s)\n%V_CHIMV approximate mean and variance of non-central chi distribution [m,v]=(n,l,s)\n%\n% Inputs:\tn = degrees of freedom\n% l = non-centrality parameter = sqrt(sum(mean^2)) [default 0]\n% (can be a vector or matrix to calculate many different values at once)\n% s = standard deviation of Gaussian [default 1]\n%\n% Outputs: m = mean of chi distribution\n% v = variance of chi distribution\n%\n% If x=c+randn(n,1) is a column vector of Gaussian random numbers with mean vector c, then\n% z=sqrt(x'*x) has a chi distributon with n degrees of freedom and non-centrality parameter\n% l=sqrt(c'*c). The mean and variance of a chi distribution are given precisely by\n%\n% m = sqrt(2)*exp(gammaln(0.5*n+0.5)-gammaln(0.5*n))*hypergeom(-0.5,0.5*n,-0.5*(l/s)^2)*s\n% = sqrt(pi/2) L(0.5,0.5*n-1,-0.5*(l/s)^2)*s\n% v = n*s^2+l^2-m^2\n%\n% where L(n,a,x) is the generalized Laguerre polynomial L_n^{(a)}(x) but this is very slow\n% to calculate so this routine approximates these expressions.\n% The expressions are from [1] together with the following identities taken\n% from [2] or [3]: 13.2.39, 13.6.19, 5.2.5, 5.4.1, 5.5.1, 5.4.6.\n%\n% For n=1, the accuracy is high; for n>1, accuracy improves with increasing n.\n% Accuracy is worst when the non-centrality parameter, l, is close to s*sqrt(n).\n% Worst case errors as a function of n are:\n% n: 1 2 3 5 10\n% worst case error in m: 1e-15 0.007 0.004 0.0015 0.0005\n%\n% References:\n% [1]\tJ. H. Park. Moments of the generalized Rayleigh distribution. Quarterly of Applied Mathematics, 19: 45–49, 1961.\n% [2]\tF. W. J. Olver, D. W. Lozier, R. F. Boisvert, and C. W. Clark, editors. NIST Handbook of Mathematical Functions. CUP, 2010. ISBN 978-0-521-14063-8.\n% [3]\tF. W. J. Olver, D. W. Lozier, R. F. Boisvert, and C. W. Clark, editors. NIST Digital Library of Mathematical Functions. 2010-2014. URL http://dlmf.nist.gov/.\n\n% Copyright (C) Mike Brookes 2014-2020\n% Version: $Id: v_chimv.m 11260 2020-07-18 20:07:58Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npersistent ab pp qq nab\nif isempty(ab)\n nab=200; % cache a few low values of n\n pp=[ 0.595336298258636 -1.213013700592756 -0.018016200037799 1.999986150447582 0];\n qq=[ -0.161514114798972 0.368983655790737 -0.136992134476950 -0.499681107630725 2];\n ni=1./(1:nab);\n ab=[polyval(qq,ni);polyval(pp,ni)];\nend\nif nargin<3\n s=1;\n if nargin<2\n l=0;\n end\nend\nls=l/s;\nl2=(ls).^2;\ns2=s^2;\nif n<=nab\n if n==1\n m=l.*(1-2*normcdf(-ls))+2*s*normpdf(-ls);\n else\n m=sqrt(l2+n-1+(ab(1,n)+ab(2,n)*l2).^(-1))*s;\n end\nelse\n m=sqrt(l2+n-1+(polyval(qq,1/n)+polyval(pp,1/n)*l2).^(-1))*s;\nend\nv=(n+l2)*s2-m.^2;\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_chimv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7740995603013745}} {"text": "function [vol] = volume_intrinsic(l)\n % VOLUME Compute volumes of tets defined intrinsically by edge lengths l\n %\n % v = volume(l)\n % \n % Inputs:\n % l #T by 6 list of tetrahedra side lengths of edges opposite *face* pairs\n % [23 31 12 41 42 43]\n % Ouputs:\n % vol #T list of tet volumes (always positive)\n %\n\n % http://en.wikipedia.org/wiki/Heron%27s_formula#Heron-type_formula_for_the_volume_of_a_tetrahedron\n\n % U, V, W, u, v, w are lengths of edges of the tetrahedron (first three form\n % a triangle; u opposite to U and so on)\n u = l(:,1); v = l(:,2); w = l(:,3); \n U = l(:,4); V = l(:,5); W = l(:,6); \n X = (w - U + v).*(U + v + w);\n x = (U - v + w).*(v - w + U);\n Y = (u - V + w).*(V + w + u);\n y = (V - w + u).*(w - u + V);\n Z = (v - W + u).*(W + u + v);\n z = (W - u + v).*(u - v + W);\n a = sqrt(x.*Y.*Z); \n b = sqrt(y.*Z.*X); \n c = sqrt(z.*X.*Y); \n d = sqrt(x.*y.*z); \n vol = sqrt( ...\n (-a + b + c + d).* ...\n ( a - b + c + d).* ...\n ( a + b - c + d).* ...\n ( a + b + c - d))./ ...\n (192.*u.*v.*w);\n\nend\n\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/volume_intrinsic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7740827968199647}} {"text": "%%\nX = rand(100,400);\nk = 100;\n\ntic; [U,S,V] = svdsecon(X,k); toc; norm(U*S*V' - X,'fro')\ntic; [U,S,V] = svds(X,k); toc; norm(U*S*V' - X,'fro')\n\ntic; [U,S,V] = svdecon(X); toc; norm(U*S*V' - X,'fro')\ntic; [U,S,V] = svd(X,'econ'); toc; norm(U*S*V' - X,'fro')\n\n%%\n%X = rand(400,100);\nX = X';\nk = 100;\n\ntic; [U,S,V] = svdsecon(X,k); toc; norm(U*S*V' - X,'fro')\ntic; [U,S,V] = svds(X,k); toc; norm(U*S*V' - X,'fro')\n\ntic; [U,S,V] = svdecon(X); toc; norm(U*S*V' - X,'fro')\ntic; [U,S,V] = svd(X,'econ'); toc; norm(U*S*V' - X,'fro')\n\n%%\n%X = rand(400,100);\nX = X';\nk = 9;\n\nXm = bsxfun(@minus,X,mean(X,2));\ntic; [U,T] = pcaecon(X,k); toc\nnorm(Xm-U*T,'fro')\n\ntic; [U,T] = pcasecon(X,k); toc\nnorm(Xm-U*T,'fro')\n\ntic; [U,S,V] = svdsecon(Xm,k); toc\nnorm(Xm-U*S*V','fro')\n\ntic; [U,S,V] = svdecon(Xm); toc\nnorm(Xm-U(:,1:k)*S(1:k,1:k)*V(:,1:k)','fro')\n\ntic; [U,S,V] = svds(Xm,k); toc\nnorm(Xm-U*S*V','fro')\n\ntic; [U,S,V] = svd(Xm); toc\nnorm(Xm-U(:,1:k)*S(1:k,1:k)*V(:,1:k)','fro')\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/SVD/testsvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7740796428613708}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n% sinusoidal sequence \n\n n=0:20;\n x=2*cos(1/2*n+pi/4);\n stem(n,x)\n legend('x[n]')\n grid\n\n figure\n y=2*cos(pi/6*n+pi/4);\n stem(n,y)\n legend('y[n]')\n grid\n\n \n \n%sampling\nfigure\nt=0:0.01:10;\nx=cos(7*t);\n\nTs1=pi/7;\nts1=0:Ts1:10;\nxs1=cos(7*ts1);\n\nTs2=pi/4;\nts2=0:Ts2:10;\nxs2=cos(7*ts2);\n\nplot(t,x,ts1,xs1,':o',ts2, xs2,':+')\nlegend('x(t)','x[n],T_s=\\pi/7','x[n],T_s=\\pi/4')\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c235.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8376199633332893, "lm_q1q2_score": 0.7740796408653662}} {"text": "function r = i4int_to_r8int ( imin, imax, i, rmin, rmax )\n\n%*****************************************************************************80\n%\n%% I4INT_TO_R8INT maps an integer interval to an R8 interval.\n%\n% Formula:\n%\n% R := RMIN + ( RMAX - RMIN ) * ( I - IMIN ) / ( IMAX - IMIN )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer IMIN, IMAX, the range.\n%\n% Input, integer I, the integer to be converted.\n%\n% Input, real RMIN, RMAX, the range.\n%\n% Output, real R, the corresponding value in [RMIN,RMAX].\n%\n if ( imax == imin )\n\n r = 0.5 * ( rmin + rmax );\n\n else\n\n r = ( ( imax - i ) * rmin ...\n + ( i - imin ) * rmax ) ...\n / ( imax - imin );\n\n end\n\n return\nend\n", "meta": {"author": "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/i4int_to_r8int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7740796407423636}} {"text": "function dist = line_par_point_dist_2d ( f, g, x0, y0, p )\n\n%*****************************************************************************80\n%\n%% LINE_PAR_POINT_DIST_2D: distance ( parametric line, point ) in 2D.\n%\n% Discussion:\n%\n% The parametric form of a line in 2D is:\n%\n% X = X0 + F * T\n% Y = Y0 + G * T\n%\n% We normalize by choosing F*F+G*G=1 and 0 <= F.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983.\n%\n% Parameters:\n%\n% Input, real F, G, X0, Y0, the parametric line parameters.\n%\n% Input, real P(2,1), the point whose distance from the line is\n% to be measured.\n%\n% Output, real DIST, the distance from the point to the line.\n%\n dx = g * g * ( p(1,1) - x0 ) - f * g * ( p(2,1) - y0 );\n dy = - f * g * ( p(1,1) - x0 ) + f * f * ( p(2,1) - y0 );\n\n dist = sqrt ( dx * dx + dy * dy ) / ( f * f + g * g );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/line_par_point_dist_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7740796376113692}} {"text": "function grid_index = sparse_grid_cc_index ( dim_num, level_max, point_num )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_CC_INDEX indexes the points forming a sparse grid.\n%\n% Discussion:\n%\n% The points forming the sparse grid are guaranteed to be a subset\n% of a certain product grid. The product grid is formed by DIM_NUM\n% copies of a 1D rule of fixed order. The orders of the 1D rule,\n% (called ORDER_1D) and the order of the product grid, (called ORDER)\n% are determined from the value LEVEL_MAX.\n%\n% Thus, any point in the product grid can be identified by its grid index,\n% a set of DIM_NUM indices, each between 1 and ORDER_1D.\n%\n% This routine creates the GRID_INDEX array, listing (uniquely) the\n% points of the sparse grid. \n%\n% An assumption has been made that the 1D rule is closed (includes\n% the interval endpoints) and nested (points that are part of a rule\n% of a given level will be part of every rule of higher level).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer POINT_NUM, the total number of points in the grids.\n%\n% Output, integer GRID_INDEX(DIM_NUM,POINT_NUM), a list of point indices,\n% representing a subset of the product grid of level LEVEL_MAX,\n% representing (exactly once) each point that will show up in a\n% sparse grid of level LEVEL_MAX.\n%\n\n%\n% The outer loop generates LEVELs from 0 to LEVEL_MAX.\n%\n point_num2 = 0;\n\n for level = 0 : level_max\n%\n% The middle loop generates the next partition LEVEL_1D(1:DIM_NUM)\n% that adds up to LEVEL.\n%\n level_1d = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n%\n% Transform each 1D level to a corresponding 1D order.\n%\n order_1d = level_to_order_closed ( dim_num, level_1d );\n%\n% The product of the 1D orders gives us the number of points in this grid.\n%\n order_nd = prod ( order_1d(1:dim_num) );\n%\n% The inner (hidden) loop generates all points corresponding to given grid.\n%\n grid_index2 = multigrid_index0 ( dim_num, order_1d, order_nd );\n%\n% Adjust these grid indices to reflect LEVEL_MAX.\n%\n grid_index2 = multigrid_scale_closed ( dim_num, order_nd, level_max, level_1d, ...\n grid_index2 );\n%\n% Determine the first level of appearance of each of the points.\n%\n grid_level = abscissa_level_closed_nd ( level_max, dim_num, order_nd, ....\n grid_index2 );\n%\n% Only keep those points which first appear on this level.\n%\n for point = 1 : order_nd\n\n if ( grid_level(point) == level )\n\n point_num2 = point_num2 + 1;\n\n grid_index(1:dim_num,point_num2) = grid_index2(1:dim_num,point);\n\n end\n\n end\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_cc/sparse_grid_cc_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7740796336193596}} {"text": "clear all;\nwarning('off','all');\n\n% parameters & settings\nk = 250; % spring stiffness\ndt = 0.01; % time step\nframe_num = 5000; % number of total frames to run\nmass_num = 10; % number of masses in the mass-spring system\n\n\n% construct a 2-dimensional mass-spring system\nV = [linspace(1,1+mass_num,mass_num)',zeros(mass_num,1)];\nE = [linspace(1,mass_num-1,mass_num-1)',linspace(2,mass_num,mass_num-1)']; % edges\nV = V-(max(V)+min(V))/2; V = V/max(V(:)); % normalize the mesh s.t. it has the right size\n\n\nvec = @(X) X(:); % vectorization: [x1x2 y1y2] order\n\n\n% boundary condition (feel free to play with it!)\nci = [1 mass_num]; % fixed vertex indices\nci = [ci ci+mass_num]'; % match the [x1x2 y1y2] order --> Q: why is this important?\n\nM = eye(2*size(V,1)); % mass matrix\ng = 1*vec(repmat([0 -9.8],size(V,1),1)); % gravity\n\n\n% set up the viewer\nclf;\nhold on;\nts = line('XData',V(:,1),'YData',V(:,2),'LineWidth',2); % draw springs as lines\ntp = scatter(V(:,1),V(:,2),'.b','SizeData',400); % draw masses as dots\nhold off;\naxis equal;\naxis([-1.5 1.5 -2 0.2]);\naxis manual;\ndrawnow;\n\n\n% initialization\nP = vec(V); % mass positions for the next time step\nPt = vec(V); % mass positions for the current time step\nPtt = vec(V); % mass positions for the previous time step\n\n\nfor iter = 1:frame_num\n\n % save the states of previous time steps\n Ptt = Pt; Pt = P;\n \n % implicit euler time stepper\n max_iter = 50;\n for i = 1 : max_iter\n \n % gradient and hessian for the elastic potential energy\n [G,K] = mass_spring_gradient_hessian(V,E,k,reshape(P,size(V)));\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% solution %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % TASK: Use newton's method to solve the following nonlinear optimization problem\n % min total_energy(P)\n % s.t. P(ci,:) = 0\n %\n % White list:\n % - \"min_quad_with_fixed\" to solve the constrained optimization problem\n %\n % Hint:\n % - total energy = incremental kinetic energy + gravitational\n % potential energy + elastic potential energy\n \n dP = zeros(size(P));\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n if norm(dP) < 1e-6\n break;\n end\n\n alpha = 1; % fixed step size for newton\n P = P + alpha * dP; % update P\n\n end\n\n Vnew = reshape(P,size(V));\n ts.XData = Vnew(:,1); ts.YData = Vnew(:,2); % update springs\n tp.XData = Vnew(:,1); tp.YData = Vnew(:,2); % update masses\n title(sprintf('%d : %d',iter, i),'Fontsize',20);\n drawnow;\n% figgif('./mass-spring.gif'); % uncomment this line to save a .gif\n \nend", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/105_mass_spring/exercise/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.77407962849236}} {"text": "function UNew = elasticPeriodic2D(varargin);\n% elasticPeriodic2D: solve elastic registraion in 2D with periodic\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[U,F,mu,lambda,gamma,PixSize,NumPix] = parse_inputs(varargin{:});\n\n% construct filters that implement discretized Navier-Lame equations\nd1 = [1;-2;1]/(PixSize(1)^2);\nd2 = [1 -2 1]/(PixSize(2)^2);\nd12 = [1 0 -1;0 0 0;-1 0 1]/(4*PixSize(1)*PixSize(2));\n\n[A11,A22] = deal(zeros(3,3));\nA11(2,2) = gamma;\nA11(:,2) = A11(:,2) + (lambda+2*mu)*d1;\nA11(2,:) = A11(2,:) + mu*d2;\nA22(2,2) = gamma;\nA22(:,2) = A22(:,2) + mu*d1;\nA22(2,:) = A22(2,:) + (lambda+2*mu)*d2;\n\nA12 = d12*(lambda+mu)/4;\nA21 = A12;\n\n% add displacement vectors to multiple of force field\nF = gamma*U + F;\n\n% multiply force field by adjoint of Navier-Lame equations\nFnew = zeros(NumPix(1),NumPix(2),2);\nFnew(:,:,1) = imfilter(F(:,:,1),A22,'replicate') - imfilter(F(:,:,2),A12,'replicate');\nFnew(:,:,2) = imfilter(F(:,:,2),A11,'replicate') - imfilter(F(:,:,1),A21,'replicate');\n\n% compute Fourier transform of new force field\nFnewF1 = fft2(Fnew(:,:,1));\nFnewF2 = fft2(Fnew(:,:,2));\n\n% construct images of coordinates scaled by pi/(N or M)\n[alpha,beta] = ndgrid(2*pi*(0:(NumPix(1)-1))/NumPix(1),2*pi*(0:(NumPix(2)-1))/NumPix(2));\n\n% construct LHS factor\nT = 2*cos(alpha) + 2*cos(beta) - 4;\nLHSfactor = (gamma + (lambda+2*mu).*T).*(gamma + mu.*T);\n\n% if gamma is zero, set origin term to 1, as DC term does not matter\nif isequal(gamma,0),\n LHSfactor(1,1) = 1;\nend\n\n% solve for FFT of U\nUF1 = FnewF1./LHSfactor;\nUF2 = FnewF2./LHSfactor;\n\n% perform inverse fft and concatenate\nUNew = cat(3,ifft2(UF1,'symmetric'),ifft2(UF2,'symmetric'));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [U,F,mu,lambda,gamma,PixSize,NumPix] = parse_inputs(varargin);\n\n% get displacement field and check size\nU = varargin{1};\nF = varargin{2};\ngamma = varargin{3};\nPixSize = varargin{4}(1:2);\nNumPix = [varargin{5} varargin{6}];\nmu = varargin{8};\nlambda = varargin{9};\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/elasticPeriodic2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7740378598029996}} {"text": "function K = kernel(X1, X2, param)\n\nn1 = size(X1,1);\nn2 = size(X2,1);\nd = size(X1,2);\nswitch param.type\n case 'linear'\n K = X1*X2';\n \n case 'rbf'\n norm1 = sum(X1.^2,2);\n norm2 = sum(X2.^2,2);\n dist = (repmat(norm1 ,1,size(X2,1)) + ...\n repmat(norm2',size(X1,1),1) - ...\n 2*X1*X2'); \n K = exp(-0.5/param.sig^2 * dist);\n\n case 'dist'\n norm1 = sum(X1.^2,2);\n norm2 = sum(X2.^2,2);\n dist = (repmat(norm1 ,1,size(X2,1)) + ...\n repmat(norm2',size(X1,1),1) - ...\n 2*X1*X2');\n K = param.maxdist - dist;\n \n case 'Lp'\n K = zeros(n1,n2);\n for n = 1:n1\n K(n,:) = real(sum(bsxfun(@minus, X2, X1(n,:)).^param.p,2));\n end\n K = exp(-0.5/param.sig^2 * K);\n\n case 'L1'\n K = zeros(n1,n2);\n for n = 1:n1\n K(n,:) = real(sum(abs(bsxfun(@minus, X2, X1(n,:))),2));\n end\n K = exp(-0.5/param.sig * K);\n \n case 'histintersection'\n\t\tK = zeros(n1,n2);\n for n = 1:n1\n K(n,:) = sum(bsxfun(@min, X2, X1(n,:)),2);\n end\n\t\t\n case 'L1_james'\n K = zeros(n1,n2);\n for n = 1:n1\n K(n,:) = real(sum(abs(bsxfun(@minus, X2, X1(n,:))),2));\n end\n K = max(max(K)) - K;\n \n otherwise\n error('Unknown kernel');\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/primalSVM/kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7740378579212914}} {"text": "function [yPred, PInvPred]=infoFilterDiscPred(yPrev,PInvPrev,F,Q,u)\n%%INFOFILTERDISCPRED Perform the discrete-time prediction step that comes \n% with the standard linear information filter with\n% additive process noise.\n%\n%INPUTS: yPrev The xDimX1 information state at the previous time-step. The\n% information state is the inverse covariance matrix times the\n% target state.\n% PInvPrev The xDimXxDim inverse of the state covariance matrix at the\n% previous time-step.\n% F An xDim X xDim state transition matrix.\n% Q The xDimX xDim process noise covariance matrix. This can be\n% singular.\n% u An optional xDimX1 vector that is the control input. If\n% omitted, no control input is used.\n%\n%OUTPUTS: yPred The xDim X 1 predicted information state vector.\n% PInvPred The predicted xDim X xDim inverse state covariance matrix.\n%\n%The implementation of the prediction step given here is from the flow\n%chart given in [1]. The matrix G in the paper is omitted, since any\n%control input can be pre-multipled by the matrix. The implied discrete-\n%time dynamic model is\n%x(k)=F(k-1)*x(k-1)+u(k-1)+noise\n%where x(k) is the state at time k. However, an information filter\n%propagates\n%y=inv(P)*x\n%and \n%PInv=inv(P)\n%instead of propagating P and x, where P is the covariance matrix\n%associated with the Gaussian state x. This allows the filter to be used\n%even when PInv is singular.\n%\n%More information on information filtering is given in Chapter 7.2 of [2].\n%\n%REFERENCES:\n%[1] D. F. Crouse, P. Willett, and Y. Bar-Shalom, \"A low-complexity\n% sliding-window Kalman FIR smoother for discrete-time models,\" IEEE\n% Signal Processing Letters, vol. 17, no. 2, pp. 177-180, Feb. 2009.\n%[2] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n% Applications to Tracking and Navigation. New York: John Wiley and\n% Sons, Inc, 2001.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n DInv=F'+PInvPrev/(F)*Q;\n PInvPred=DInv\\PInvPrev/(F);\n \n %Handle possible loss of symmetry due to order of operations and finite\n %precision limitations.\n PInvPred=(PInvPred+PInvPred')/2;\n\n if(nargin<5||isempty(u))\n yPred=DInv\\yPrev;\n else\n yPred=DInv\\yPrev+PInvPred*u;\n end\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/State_Propagation/Discrete_Time/infoFilterDiscPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7740378499264233}} {"text": "function [ po, pc, pe ] = lagrange_complete ( d, n, r, nd, xd )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_COMPLETE: Complete Lagrange polynomial basis from data.\n%\n% Discussion:\n%\n% This function represents algorithm 4.1 in the reference.\n%\n% This function is given XD, a set of ND distinct data points in a \n% D dimensional space, and returns information defining a set of \n% ND Lagrange polynomials L(i)(X) with the property that:\n%\n% L(i)(XD(j)) = delta(i,j)\n%\n% This function does a very weak form of pivoting, by selecting\n% the very next polynomial that is \"nonzero\" at the current point.\n% An improved version of this function chooses instead the polynomial\n% with maximum function value at the current point.\n%\n% In order for this computation to be carried out, it is necessary that\n% ND, the number of data points, is equal to R, the dimension of the \n% space of polynomials in D dimensions and total degree N or less, that is:\n%\n% ND = R = Choose ( N + D, N )\n%\n% There will be ND polynomials returned. Each polynomial can have\n% as many as R coefficients.\n%\n% Each polynomial is given as a vector, with each entry corresponding\n% to a nonzero coefficient. In particular, for polynomial L(i)(X):\n%\n% PO(i) is the order, that is, the number of nonzero coefficients;\n% PC(i,j), for 1 <= j <= PO(i), is the coefficient of the J-th term.\n% PE(i,j), for 1 <= j <= PO(i), encodes the exponents of the J-th term.\n%\n% The exponent codes are a compact way of recording the exponent vector\n% associated with each monomial. If PE(i,j) = k, then the corresponding\n% vector of D exponents can be determined by:\n%\n% E = mono_unrank_grlex ( D, k );\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Tomas Sauer, Yuan Xu,\n% On multivariate Lagrange interpolation,\n% Mathematics of Computation,\n% Volume 64, Number 211, July 1995, pages 1147-1170.\n%\n% Parameters:\n%\n% Input, integer D, the spatial dimension.\n%\n% Input, integer N, the maximum total degree.\n%\n% Input, integer R, the number of monomials in D dimensions \n% of total degree N or less.\n%\n% Input, integer ND, the number of data points.\n% This function requires that the ND is equal to R.\n%\n% Input, real XD(D,ND), the data points, which must be distinct.\n%\n% Output, integer PO(ND), the order (number of nonzero coefficients) for the \n% Lagrange basis polynomials.\n%\n% Output, real PC(ND,R), the coefficients for the \n% Lagrange basis polynomials.\n%\n% Output, integer PE(ND,R), the exponent indices for the \n% Lagrange basis polynomials.\n%\n\n%\n% Verify that R is correct.\n%\n if ( r ~= mono_upto_enum ( d, n ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_COMPLETE - Fatal error!\\n' );\n fprintf ( 1, ' The value R is not correct.\\n' );\n error ( 'LAGRANGE_COMPLETE - Fatal error!' );\n end\n\n if ( r ~= nd )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_COMPLETE - Fatal error!\\n' );\n fprintf ( 1, ' The value R = %d does not equal ND = %d.\\n', r, nd );\n error ( 'LAGRANGE_COMPLETE - Fatal error!' );\n end\n%\n% Verify that the points are sufficiently distinct.\n%\n [ d_min, d_max ] = r8col_separation ( d, nd, xd );\n d_tol = sqrt ( eps );\n\n if ( d_min < d_tol )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_COMPLETE - Fatal error!\\n' );\n fprintf ( 1, ' Some points are too close!\\n' );\n fprintf ( 1, ' Minimum data point separation is = %g.\\n', d_min );\n error ( 'LAGRANGE_COMPLETE - Fatal error!' );\n end\n%\n% Initialize the polynomials Q to be all monomials of degree N or less.\n%\n qo = zeros ( r, 1 );\n qc = zeros ( r, r );\n qe = zeros ( r, r );\n\n for k = 1 : r\n qo(k,1) = 1;\n qc(k,1) = 1.0;\n qe(k,1) = k;\n end\n%\n% Now set up the P polynomials.\n%\n po = zeros ( r, 1 );\n pc = zeros ( r, r );\n pe = zeros ( r, r );\n\n for k = 1 : nd\n%\n% Find the first polynomial Q(K:R)(X) which is nonzero at X(K).\n%\n i = r + 1;\n\n for j = k : r\n o = qo(j);\n value = polynomial_value ( d, o, qc(j,1:o), qe(j,1:o), 1, xd(1:d,k) );\n if ( value ~= 0.0 )\n i = j;\n break\n end\n end\n\n if ( i == r + 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_COMPLETE - Fatal error!\\n' );\n fprintf ( 1, ' I = R+1.\\n' );\n error ( 'LAGRANGE_COMPLETE - Fatal error!' );\n end\n%\n% Define P(K)(X) = Q(I)(X) / Q(I)(X(k)\n%\n o = qo(i);\n po(k) = qo(i);\n pc(k,1:o) = qc(i,1:o) / value;\n pe(k,1:o) = qe(i,1:o);\n%\n% Modify P(1:k-1)(X).\n%\n for j = 1 : k - 1\n\n oj = po(j);\n ok = po(k);\n\n value = polynomial_value ( d, oj, pc(j,1:oj), pe(j,1:oj), 1, xd(1:d,k) );\n\n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, pc(j,1:oj), pe(j,1:oj) );\n\n po(j) = o;\n pc(j,1:o) = c(1:o)';\n pe(j,1:o) = e(1:o)';\n\n end\n%\n% Modify Q(I:downto:K+1)\n%\n for j = i : -1 : k + 1\n\n oj = qo(j-1);\n ok = po(k);\n\n value = polynomial_value ( d, oj, qc(j-1,1:oj), qe(j-1,1:oj), ...\n 1, xd(1:d,k) );\n \n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, qc(j-1,1:oj), qe(j-1,1:oj) );\n\n qo(j) = o;\n qc(j,1:o) = c(1:o)';\n qe(j,1:o) = e(1:o)';\n\n end\n%\n% Modify Q(I+1:R)\n%\n for j = i + 1 : r\n\n oj = qo(j);\n ok = po(k);\n\n value = polynomial_value ( d, oj, qc(j,1:oj), qe(j,1:oj), ...\n 1, xd(1:d,k) );\n\n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, qc(j,1:oj), qe(j,1:oj) );\n\n qo(j) = o;\n qc(j,1:o) = c(1:o)';\n qe(j,1:o) = e(1:o)';\n\n end\n\n end\n%\n% Get rid of tiny coefficients.\n%\n for i = 1 : nd\n oi = po(i);\n [ o, c, e ] = polynomial_compress ( ...\n po(i), pc(i,1:oi), pe(i,1:oi) );\n po(i) = o;\n pc(i,1:o) = c(1:o)';\n pe(i,1:o) = e(1:o)';\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/lagrange_nd/lagrange_complete.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7739535384325006}} {"text": "function value = q_measure ( n, z, triangle_order, triangle_num, triangle_node )\n\n%*****************************************************************************80\n%\n%% Q_MEASURE determines the triangulated pointset quality measure Q.\n%\n% Discussion:\n%\n% The Q measure evaluates the uniformity of the shapes of the triangles\n% defined by a triangulated pointset.\n%\n% For a single triangle T, the value of Q(T) is defined as follows:\n%\n% TAU_IN = radius of the inscribed circle,\n% TAU_OUT = radius of the circumscribed circle,\n%\n% Q(T) = 2 * TAU_IN / TAU_OUT\n% = ( B + C - A ) * ( C + A - B ) * ( A + B - C ) / ( A * B * C )\n%\n% where A, B and C are the lengths of the sides of the triangle T.\n%\n% The Q measure computes the value of Q(T) for every triangle T in the\n% triangulation, and then computes the standard deviation of this\n% set of values:\n%\n% Q_MEASURE = min ( all T in triangulation ) Q(T)\n%\n% In an ideally regular mesh, all triangles would have the same\n% equilateral shape, for which Q = 1. In a good mesh, 0.5 < Q.\n%\n% Given the 2D coordinates of a set of N nodes, stored as Z(1:2,1:N),\n% a triangulation is a list of NT triples of node indices that form\n% triangles. Generally, a maximal triangulation is expected, namely,\n% a triangulation whose image is a planar graph, but for which the\n% addition of any new triangle would mean the graph was no longer planar.\n% A Delaunay triangulation is a maximal triangulation which maximizes\n% the minimum angle that occurs in any triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Max Gunzburger and John Burkardt,\n% Uniformity Measures for Point Samples in Hypercubes.\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, pages 329-345, June 2004.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real Z(DIM_NUM,N), the points.\n%\n% Input, integer TRIANGLE_ORDER, the order of the triangles.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(TRIANGLE_ORDER,TRIANGLE_NUM), the triangulation.\n%\n% Output, real VALUE, the Q quality measure.\n%\n if ( triangle_num < 1 )\n value = -1.0;\n return\n end\n%\n% Compute the mean value of Q.\n%\n q_min = r8_huge ( );\n\n for triangle = 1 : triangle_num\n\n a_index = triangle_node(1,triangle);\n b_index = triangle_node(2,triangle);\n c_index = triangle_node(3,triangle);\n\n ab_length = sqrt ( ...\n ( z(1,a_index) - z(1,b_index) )^2 ...\n + ( z(2,a_index) - z(2,b_index) )^2 );\n\n bc_length = sqrt ( ...\n ( z(1,b_index) - z(1,c_index) )^2 ...\n + ( z(2,b_index) - z(2,c_index) )^2 );\n\n ca_length = sqrt ( ...\n ( z(1,c_index) - z(1,a_index) )^2 ...\n + ( z(2,c_index) - z(2,a_index) )^2 );\n\n q = ( bc_length + ca_length - ab_length ) ...\n * ( ca_length + ab_length - bc_length ) ...\n * ( ab_length + bc_length - ca_length ) ...\n / ( ab_length * bc_length * ca_length );\n\n q_min = min ( q_min, q );\n\n end\n\n value = q_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/quality/q_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7739535382463552}} {"text": "function [fm,am,iflaw]=doppler(N,Fs,f0,d,v,t0,c);\n%DOPPLER Generate complex Doppler signal.\n% \t [FM,AM,IFLAW]=DOPPLER(N,FS,F0,D,V,T0,C) \n%\t Returns the frequency modulation (FM), the amplitude \n%\t modulation (AM) and the instantaneous frequency law (IFLAW) \n%\t of the signal received by a fixed observer from a moving target \n%\t emitting a pure frequency f0.\n%\n%\t N : number of points. \n%\t FS : sampling frequency (in Hertz). \n%\t F0 : target frequency (in Hertz). \n%\t D : distance from the line to the observer (in meters). \n%\t V : target velocity (in m/s)\n%\t T0 : time center (default : N/2). \n%\t C : wave velocity (in m/s) (default : 340). \n%\t FM : Output frequency modulation. \n%\t AM : Output amplitude modulation. \n%\t IFLAW : Output instantaneous frequency law.\n% \n%\tExample: \n%\t N=512; [fm,am,iflaw]=doppler(N,200,65,10,50); \n%\t subplot(211); plot(real(am.*fm)); \n%\t subplot(212); plot(iflaw);\n% [ifhat,t]=instfreq(sigmerge(am.*fm,noisecg(N),15),11:502,10);\n% hold on; plot(t,ifhat,'g'); hold off;\n%\n%\tSee also DOPNOISE \n\n%\tF. Auger, July 94, August 95 - O. Lemoine, October 95.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin <= 4),\n error ( 'At least 5 parameters are required' ); \nelseif (nargin == 5),\n t0=N/2; c=340.0;\nelseif (nargin == 6),\n c=340.0;\nend;\n\nif (N <= 0),\n error ('The signal length N must be strictly positive' );\nelseif (d <= 0.0),\n error ('The distance D must be positive' );\nelseif (Fs < 0.0),\n error ('The sampling frequency FS must be positive' );\nelseif (t0<1) | (t0>N),\n error ('T0 must be between 1 and N');\nelseif (f0<0)|(f0>Fs/2),\n error ('F0 must be between 0 and FS/2');\nelseif (v<0),\n error ('V must be positive');\nelse\n tmt0=((1:N)'-t0)/Fs;\n dist=sqrt(d^2+(v*tmt0).^2);\n fm = exp(j*2.0*pi*f0*(tmt0-dist/c));\n if (nargout>=2), \n if abs(f0) old_err\n disp('Failed to find descending step length.');\n break;\n else\n alpha = new_alpha;\n rel_err = abs(old_err - err)/old_err;\n if rel_err <= TOLERANCE\n break;\n end\n end\n % End convergence testing.\n\nend %End of main loop.\n\n% Compute the coefficients of the numerator.\nc = (diag(D)*N)\\y;\n\n% Generate an error message if the algorithm failed to converge.\nif rel_err > TOLERANCE\n disp('Algorithm did not converge.');\nend\n\n%XXXXXXXXXXXXXXXXX Subroutines XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n function update(alpha)\n % Updates the model matrix and computes ancillary quantities.\n D = 1./(1+M*alpha); % Compute the denominator.\n [Q R] = qr(diag(D)*N,0); % Compute the QR factorization of A = D*N\n Py = Q*(Q'*y); % Compute the projection of y onto the range of A.\n r = y - Py; % Compute the residual. \n err = r'*r; % Compute the current squared error.\n end\n\n function step_control\n % This function implements stepsize control using a simple\n % backtracking scheme from Dennis & Schnabel.\n \n % Try taking a full step.\n new_alpha = alpha + delta;\n\n % Update the model.\n update(new_alpha);\n \n % If a full step does not sufficiently reduce the error then we \n % use a backtracking line-search method for step-size control.\n % This involves minimizing a function f(lambda) that interpolates the \n % computed error (and its derivatives) at different values of lambda.\n f0 = old_err;\n fprime = gradient'*delta;\n steptol = f0 + .0001*fprime;\n if err > steptol\n\n errs(1) = err; lams(1) = 1; % We'll need this if further refinement is necessary.\n\n % We start with a quadratic model at f(0), f'(0), and f(1)\n % and will take the larger of the computed step or 1/10.\n lambda = max([-fprime/(2*(err - f0 - fprime)) .1]);\n\n new_alpha = alpha + lambda*delta;\n\n % Update the model matrix and compute ancillary quantities.\n update(new_alpha); \n\n % If this doesn't work then we loop with a cubic model at f(0),\n % f'(0), f(lambda), and f(lam2) where the last two are errors at\n % the last two lambda that were tried.\n steptol = f0 + .0001*fprime*lambda;\n while err > steptol\n\n % Push the current lambda and error to the top of the lams and errs\n % stacks.\n lams = [lambda; lams(1)]; errs = [err; errs(1)];\n rhs = (errs - fprime*lams - [f0 ; f0])./(lams.*lams);\n ab = [lams [1 ; 1]]\\rhs;\n\n lambda = (-ab(2)+sqrt(ab(2)*ab(2) - 3*ab(1)*fprime))/(3*ab(1));\n\n % It is still important to make certain that the new lambda\n % progresses quickly but not too quickly. So if lambda is less\n % than lam2/10 we just use lam2/10, and if it is larger than\n % lam2/2 then we use lam2/2.\n if lambda < lams(1)/10\n lambda = lams(1)/10;\n end\n if lambda > lams(1)/2\n lambda = lams(1)/2;\n end\n\n new_alpha = alpha + lambda*delta;\n\n % Update the model matrix and compute ancillary quantities.\n update(new_alpha); \n\n steptol = f0 + .0001*fprime*lambda;\n\n end\n end\n end \n\n%XXXXXXXXXXXXXXXXX Subroutines End XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\nend\n% End of function.\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24117-discrete-least-squares-rational-approximation/dlsqrat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7739132822448099}} {"text": "% Reed-Solomon Errors and Erasures Decoding\n% Decoding is based on the Massey-Berlekamp decoder. Based on the notes of Adina Matache: http://www.ee.ucla.edu/~matache/rsc/slide.html\n% This program was written by Jaco Versfeld. For any questions or remarks email Jaco at jaco.versfeld@gmail.com. \n% This code is provided as is and Jaco Versfeld accepts no liability what so ever.\n% Feel free to use and modify this code for whatever purpose.\n\nclear\nclc\n\n\n%**************************\n%*** RS code Parameters ***\n%**************************\n\n% Here we specify the parameters of the (n,k) Reed-Solomon code\n\n\nm = 4 %Determine the Galois Field, GF(2^m)\nn = 2^m - 1 %This is fixed for a Reed-Solomon, the length of the codeword\nk = 3 %The number of data symbols, can be anything between 1 to n - 1\nh = n-k\nt = h/2\n\n%**************************\n\n\n\n\n%*** Generate the Galois Field and Generator polynomial ***\n\n% This step is neccessary for Matlab. Here we create the Galois Field which is used for\n% computations of the Reed-Solomon code\n\n\nfield = gftuple([-1:2^m-2]', m, 2);\n\n\n%Generator Polynomial:\n%Lin + Costello, p.171\n%The Generator polynomial is one way of encoding Reed-Solomon codes\n\n%Construct the generator polynomial\nc = [1 0]; \np(1) = c(1);\n\nfor i = 1:h-1\n p(1) = gfmul(p(1),1,field);\n p(2) = 0;\n c = gfconv(c,p,field);\nend\ng = c;\n\n%**************************\n\n\n\n%*** RS Encode ***\n\n%Generate Random Data\nDATA_IN = randint(1,k,[-1 n-1]);\n\n%RS encoding\nparity = RS_ENC4(DATA_IN,n,k,g,field);\nRS_CODE = [parity DATA_IN];\n\n%********************************\n\n\n\n\n%*** Channel ***\nRECEIVED = RS_CODE\n\n\n%I introduce the errors manually here, but any channel can be used here, like an AWGN.\n% A maximum of 2*t + e <= (n-k) errors and erasures can be corrected, where t is the number of \n% errors and e the number of erasures\n\n%Introduce some errors\nRECEIVED(3) = gfadd(RECEIVED(3),randint(1,1,[-1 n-1]),field);\nRECEIVED(5) = gfadd(RECEIVED(3),randint(1,1,[-1 n-1]),field);\n\n\n%Introduce some erasures\nerasures = [ 2 3 4 5 6 7 8 9 11 14 15]; %This polynomial contains the positions of the erasures\n\n%RECEIVED(1) = -2\nRECEIVED(2) = -2\nRECEIVED(3) = -2\nRECEIVED(4) = -2\nRECEIVED(5) = -2\nRECEIVED(6) = -2\nRECEIVED(7) = -2\nRECEIVED(8) = -2\nRECEIVED(9) = -2\nRECEIVED(11) = -2\nRECEIVED(14) = -2\nRECEIVED(15) = -2\n\n\n\n\n%****************\n\n\n\n%*** Decoding ***\n\nDECODED = RS_E_E_DEC(RECEIVED, erasures,n,k,t,h,g,field);\n\n%****************\n\nDECODED\nRS_CODE\n\nif all(DECODED == RS_CODE)\n disp('Decoding Success')\nelse\n disp('Decoding Failure')\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/27116-mfsk-modulation-in-awgn-noise-with-reed-solomon-decoding/MFSK/Errors_and_Erasures/Errors_And_Erasures_Test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.77391327716522}} {"text": "%% Edge Element Discretization of Maxwell Equations\n% We test Maxwell solvers in iFEM.\n\nclear all; close all\nrowNames ={'h=1/2';'h=1/4';'h=1/8'};\ncolHeaders = {'H^curl Error','L^2 Error'};\n\n%% The data of the pde\n%\n% * pde = Maxwelldata1; % zero Neumann boundary condition and curl u = 0\n% * pde = Maxwelldata2; % non-homogenous Neumann boundary condition\n% * pde = Maxwelldata3; % polynomial data and curl u = 0\n% * pde = Maxwelldata4; % zero Dirichlet boundary condition\n% * pde = Maxwelldata5; % linear polynomial data\n% * pde = planewavedataC; % plane wave with complex coefficients\n% * pde = planewavedata1; % plane wave with real coefficients\n\n\n%% Positive Definite Case\n% curl curl E + E = f.\n\nhelp Maxwelldata2\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = Maxwelldata2;\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'cg';\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = Maxwelldata2;\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'cg';\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned CG\n% converges around 20 steps. \n\n%% Indefinite with real coefficients\n% curl curl E - E = f.\n\nhelp planewavedata1\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = planewavedata1;\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'cg';\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = planewavedata1;\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'cg';\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned CG\n% converges around 40 steps although the system is indefinite.\n\n%% Indefinite: complex coefficients, real solution\n% curl curl E - (1-i)E = f.\noption.solver = 'gmres';\n\nhelp planewavedataC\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = planewavedataC;\nbdFlag = setboundary3(node,elem,'Dirichlet');\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\npde = planewavedataC;\nbdFlag = setboundary3(node,elem,'Neumann');\ncubeMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned GMRES\n% converges around 90 steps although the system is indefinite.\n%\n% Bug: For Neumann boundary condition, the rate of L2 error is not quite right.\n\n%% Indefinite: real coefficents, complex solution\noption.solver = 'cg';\n\nhelp planewavedata\n%%\n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\nbdFlag = setboundary3(node,elem,'Dirichlet');\nplanewaveMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\nbdFlag = setboundary3(node,elem,'Neumann');\nplanewaveMaxwell;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% The computation of error can't handle complex functions. So in\n% planewaveMaxwell the error between uI and uh is computed. Therefore\n% slightly better rate of convergence is observed. The rate of L2 error is\n% almost second order.", "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/Maxwelltestdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.773911511523874}} {"text": "% IM = mkGaussian(SIZE, COVARIANCE, MEAN, AMPLITUDE)\n% \n% Compute a matrix with dimensions SIZE (a [Y X] 2-vector, or a\n% scalar) containing a Gaussian function, centered at pixel position\n% specified by MEAN (default = (size+1)/2), with given COVARIANCE (can\n% be a scalar, 2-vector, or 2x2 matrix. Default = (min(size)/6)^2),\n% and AMPLITUDE. AMPLITUDE='norm' (default) will produce a\n% probability-normalized function. All but the first argument are\n% optional.\n\n% Eero Simoncelli, 6/96.\n\nfunction [res] = mkGaussian(sz, cov, mn, ampl)\n\nsz = sz(:);\nif (size(sz,1) == 1)\n sz = [sz,sz];\nend\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('cov') ~= 1)\n cov = (min(sz(1),sz(2))/6)^2;\nend\n\nif (exist('mn') ~= 1)\n mn = (sz+1)/2;\nend\n\nif (exist('ampl') ~= 1)\n ampl = 'norm';\nend\n\n%------------------------------------------------------------\n\n[xramp,yramp] = meshgrid([1:sz(2)]-mn(2),[1:sz(1)]-mn(1));\n\nif (sum(size(cov)) == 2) % scalar\n if (strcmp(ampl,'norm')) \n ampl = 1/(2*pi*cov(1));\n end\n e = (xramp.^2 + yramp.^2)/(-2 * cov);\nelseif (sum(size(cov)) == 3) % a 2-vector\n if (strcmp(ampl,'norm')) \n ampl = 1/(2*pi*sqrt(cov(1)*cov(2)));\n end\n e = xramp.^2/(-2 * cov(2)) + yramp.^2/(-2 * cov(1));\nelse\n if (strcmp(ampl,'norm')) \n ampl = 1/(2*pi*sqrt(det(cov)));\n end\n cov = -inv(cov)/2;\n e = cov(2,2)*xramp.^2 + (cov(1,2)+cov(2,1))*(xramp.*yramp) ...\n + cov(1,1)*yramp.^2;\nend\n \nres = ampl .* exp(e);\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/mkGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7737570302855616}} {"text": "function [ x, seed ] = r8vec_normal_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_NORMAL_01 returns a unit pseudonormal R8VEC.\n%\n% Discussion:\n%\n% The standard normal probability distribution function (PDF) has\n% mean 0 and standard deviation 1.\n%\n% This routine can generate a vector of values on one call. It\n% has the feature that it should provide the same results\n% in the same order no matter how we break up the task.\n%\n% Before calling this routine, the user may call RANDOM_SEED\n% in order to set the seed of the random number generator.\n%\n% The Box-Muller method is used, which is efficient, but\n% generates an even number of values each time. On any call\n% to this routine, an even number of new values are generated.\n% Depending on the situation, one value may be left over.\n% In that case, it is saved for the next call.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 July 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of values desired. If N is negative,\n% then the code will flush its internal memory; in particular,\n% if there is a saved value to be used on the next call, it is\n% instead discarded. This is useful if the user has reset the\n% random number seed, for instance.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N), a sample of the standard normal PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n% Local parameters:\n%\n% Local, integer MADE, records the number of values that have\n% been computed. On input with negative N, this value overwrites\n% the return value of N, so the user can get an accounting of\n% how much work has been done.\n%\n% Local, real R(N+1), is used to store some uniform random values.\n% Its dimension is N+1, but really it is only needed to be the\n% smallest even number greater than or equal to N.\n%\n% Local, integer SAVED, is 0 or 1 depending on whether there is a\n% single saved value left over from the previous call.\n%\n% Local, integer X_LO_INDEX, X_HI_INDEX, records the range of entries of\n% X that we need to compute. This starts off as 1:N, but is adjusted\n% if we have a saved value that can be immediately stored in X(1),\n% and so on.\n%\n% Local, real Y, the value saved from the previous call, if\n% SAVED is 1.\n%\n persistent made;\n persistent saved;\n persistent y;\n%\n% I'd like to allow the user to reset the internal data.\n% But this won't work properly if we have a saved value Y.\n% I'm making a crock option that allows the user to signal\n% explicitly that any internal memory should be flushed,\n% by passing in a negative value for N.\n%\n if ( n < 0 )\n made = 0;\n saved = 0;\n y = 0.0;\n x = [];\n return\n elseif ( n == 0 )\n x = [];\n return\n end\n%\n% Record the range of X we need to fill in.\n%\n x_lo_index = 1;\n x_hi_index = n;\n%\n% Use up the old value, if we have it.\n%\n if ( saved == 1 )\n x(1) = y;\n saved = 0;\n x_lo_index = 2;\n end\n%\n% Maybe we don't need any more values.\n%\n if ( x_hi_index - x_lo_index + 1 == 0 )\n%\n% If we need just one new value, do that here to avoid null arrays.\n%\n elseif ( x_hi_index - x_lo_index + 1 == 1 )\n\n [ r(1), seed ] = r8_uniform_01 ( seed );\n\n if ( r(1) == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_NORMAL_01 - Fatal error!\\n' );\n fprintf ( 1, ' R8_UNIFORM_01 returned a value of 0.\\n' );\n error ( 'R8VEC_NORMAL_01 - Fatal error!' );\n end\n\n [ r(2), seed ] = r8_uniform_01 ( seed );\n\n x(x_hi_index) = ...\n sqrt ( - 2.0 * log ( r(1) ) ) * cos ( 2.0 * pi * r(2) );\n y = sqrt ( - 2.0 * log ( r(1) ) ) * sin ( 2.0 * pi * r(2) );\n\n saved = 1;\n\n made = made + 2;\n%\n% If we require an even number of values, that's easy.\n%\n elseif ( mod ( x_hi_index - x_lo_index + 1, 2 ) == 0 )\n\n m = floor ( ( x_hi_index - x_lo_index + 1 ) / 2 );\n\n [ r, seed ] = r8vec_uniform_01 ( 2*m, seed );\n\n x(x_lo_index:2:x_hi_index-1) = ...\n sqrt ( -2.0 * log ( r(1:2:2*m-1) ) ) ...\n .* cos ( 2.0 * pi * r(2:2:2*m) );\n\n x(x_lo_index+1:2:x_hi_index) = ...\n sqrt ( -2.0 * log ( r(1:2:2*m-1) ) ) ...\n .* sin ( 2.0 * pi * r(2:2:2*m) );\n\n made = made + x_hi_index - x_lo_index + 1;\n%\n% If we require an odd number of values, we generate an even number,\n% and handle the last pair specially, storing one in X(N), and\n% saving the other for later.\n%\n else\n\n x_hi_index = x_hi_index - 1;\n\n m = floor ( ( x_hi_index - x_lo_index + 1 ) / 2 ) + 1;\n\n [ r, seed ] = r8vec_uniform_01 ( 2*m, seed );\n\n x(x_lo_index:2:x_hi_index-1) = ...\n sqrt ( -2.0 * log ( r(1:2:2*m-3) ) ) ...\n .* cos ( 2.0 * pi * r(2:2:2*m-2) );\n\n x(x_lo_index+1:2:x_hi_index) = ...\n sqrt ( -2.0 * log ( r(1:2:2*m-3) ) ) ...\n .* sin ( 2.0 * pi * r(2:2:2*m-2) );\n\n x(n) = sqrt ( -2.0 * log ( r(2*m-1) ) ) ...\n * cos ( 2.0 * pi * r(2*m) );\n\n y = sqrt ( -2.0 * log ( r(2*m-1) ) ) ...\n * sin ( 2.0 * pi * r(2*m) );\n\n saved = 1;\n\n made = made + x_hi_index - x_lo_index + 2;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ellipse_monte_carlo/r8vec_normal_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7737509806892127}} {"text": "function C = spm_dctmtx(N,K,n,f)\n% Creates basis functions for Discrete Cosine Transform.\n% FORMAT C = spm_dctmtx(N,K,n)\n% OR C = spm_dctmtx(N,K)\n% OR D = spm_dctmtx(N,K,n,'diff')\n% OR D = spm_dctmtx(N,K,'diff')\n% N - dimension\n% K - order\n% n - optional points to sample\n%____________________________________________________________________________\n% spm_dctmtx creates a matrix for the first few basis functions of a one\n% dimensional discrete cosine transform.\n% With the 'diff' argument, spm_dctmtx produces the derivatives of the\n% DCT.\n%\n% See: Fundamentals of Digital Image Processing (p 150-154).\n% Anil K. Jain 1989.\n%____________________________________________________________________________\n% @(#)spm_dctmtx.m\t2.1 John Ashburner MRCCU/FIL 01/08/28\n\nd = 0;\n\nif nargin == 1, K = N; end;\n\nif any(nargin == [1 2]),\n\tn = (0:(N-1))';\nelseif nargin == 3,\n\tif strcmp(n,'diff'),\n\t\td = 1;\n\t\tn = (0:(N-1))';\n\telseif strcmp(n,'diff2'),\n\t\td = 2;\n\t\tn = (0:(N-1))';\n\telse\n\t\tn = n(:);\n\tend\nelseif nargin == 4,\n\tn = n(:);\n\tif strcmp(f,'diff'),\n\t\td = 1;\n\telseif strcmp(n,'diff2'),\n\t\td = 2;\n\telse\n\t\terror('Incorrect Usage');\n\tend\nelse\n\terror('Incorrect Usage');\nend\n\nC = zeros(size(n,1),K);\n\nif d == 0,\n\tC(:,1)=ones(size(n,1),1)/sqrt(N);\n\tfor k=2:K\n\t\tC(:,k) = sqrt(2/N)*cos(pi*(2*n+1)*(k-1)/(2*N));\n\tend\nelseif d == 1,\n\tfor k=2:K\n\t\tC(:,k) = -2^(1/2)*(1/N)^(1/2)*sin(1/2*pi*(2*n*k-2*n+k-1)/N)*pi*(k-1)/N;\n\tend\nelseif d == 2,\n\tfor k=2:K,\n\t\tC(:,k) = -2^(1/2)*(1/N)^(1/2)*cos(1/2*pi*(2*n+1)*(k-1)/N)*pi^2*(k-1)^2/N^2;\n\tend;\nelse,\n\terror('Can''t do this');\nend\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/spm2/spm_dctmtx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.77371645198606}} {"text": "function c = correlation_cubic ( n, rho, rho0 )\n\n%*****************************************************************************80\n%\n%% CORRELATION_CUBIC evaluates the cubic correlation function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 March 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, integer N, the number of arguments.\n%\n% Input, real RHO(N,1), the arguments.\n%\n% Input, real RHO0, the correlation length.\n%\n% Output, real C(N,1), the correlations.\n%\n rho = rho ( : );\n\n rhohat = min ( abs ( rho ) / rho0, 1.0 );\n\n c = 1.0 - 7.0 * rhohat.^2 + 8.75 * rhohat.^3 - 3.5 * rhohat.^5 + 0.75 * rhohat.^7;\n\n return\nend\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/correlation/correlation_cubic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7737164486355971}} {"text": "function X = MvnRndMatchCrossCov(S, varargin)\n% X = MvnRndMatchCrossCov(S, J) simulates a panel of J scenarios of a\n% multivariate normal random vector with zero sample mean and sample\n% covariance exactly equal to S. Each row of X is a scenario and each\n% column is a variable. \n%\n% X = MvnRndMatchCrossCov(S, P, F, CovF) generates a multivariate normal\n% panel X with zero sample mean, sample covariance S and sample cross\n% covariance P with another zero-mean panel F. CovF, the sample covariance\n% of F, is computed if not provided as input.\n\n% IMPORTANT: The order of computations in the following expressions is\n% important for efficiency. Please use the same order, or have a good reason\n% to change it! \n\n% Code by S. Gollamudi. This version December 2009. \n\n\n\n% check input \nN = size(S,1);\nif nargin==2,\n J = varargin{1};\n K = 0;\nelse\n P = varargin{1};\n F = varargin{2};\n [J,K] = size(F);\n assert(all(size(P)==[K,N]), 'Incorrect dimensions of cross-covariance P.');\n if length(varargin)<=2,\n CovF = cov(F,1);\n else\n CovF = varargin{3};\n end\n sqrtJ = sqrt(J);\nend\n\n% tolerance level\neps = 1e-9;\n\n% Algorithm: X = F*B + V*R\n% where F'*V=0, V'V=J*I and R is upper triangular\n\nif K>0,\n \n % Compute B\n B = CovF \\ P;\n\n % Compute R\n Sigma_orth = S - P'*B;\n var_orth = diag(Sigma_orth);\n var_x = diag(S);\n if any(var_orth < -eps*var_x),\n error('MvnRndMatchCrossCov: S and P are incompatible.')\n end\n i_positive = (var_orth > eps*var_x);\n num_positive = sum(i_positive);\n R = zeros(num_positive,N);\n R(:,i_positive) = chol(S(i_positive,i_positive) - P(:,i_positive)'*B(:,i_positive));\n\n % Generate V \n Z = randn(J/2,N);\n Z=[Z\n -Z];\n \n % using QR decomposition\n %[V,dummy] = qr([F Z],0);\n %V = V(:,K+1:K+num_positive)*sqrtJ;\n \n % using modified Gram-Schmidt\n Z = Z - (F/CovF)*((F'*Z)/J);\n V = zeros(J,0);\n for n = 1:num_positive,\n u = Z(:,n) - V*((V'*Z(:,n))/J);\n V = [V u*(sqrtJ/norm(u))];\n end\n\n % generate panel X\n X = F*B + V*R;\n\nelse\n\n % generate X to have zero sample mean and sample covariance S\n Z = randn(J/2,N);\n Z = [Z\n -Z];\n X = Z * (chol(cov(Z,1)) \\ chol(S));\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/26853-factors-on-demand/FactorsOnDemand/StatisticalVsCrossSectional/MvnRndMatchCrossCov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7737164461950491}} {"text": "% Steady state transport solutions for one fixed value of Pe and various values of Da1\nx = [0:0.01:1];\nPe = 1; Da1 = 16;\ns = sqrt(0.25*Pe*Pe+Pe/Da1);\nmu1 = 0.5*Pe+s; mu2 = 0.5*Pe-s;\ns = mu2*exp(mu2)-mu1*exp(mu1);\nc = (mu2*exp(mu2)*exp(mu1*x)-mu1*exp(mu1)*exp(mu2*x))./s;\nfor Da1 = [8 4 2 1 0.5 0.25 0.125];\n s = sqrt(0.25*Pe*Pe+Pe/Da1);\n mu1 = 0.5*Pe+s; mu2 = 0.5*Pe-s;\n s = mu2*exp(mu2)-mu1*exp(mu1);\n c = [c;(mu2*exp(mu2)*exp(mu1*x)-mu1*exp(mu1)*exp(mu2*x))./s];\nend\nplot (x,c);\nlegend('Da_1=16','Da_1=8','Da_1=4','Da_1=2','Da_1=1','Da_1=0.5','Da_1=0.25','Da_1=0.125');\nxlabel ('x/L [-]'); ylabel ('c/c_{in} [-]');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15646-environmental-modeling/analtrans_s3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308278, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7737017539689051}} {"text": "function pdf = f_pdf ( x, m, n )\n\n%*****************************************************************************80\n%\n%% F_PDF evaluates the F central PDF.\n%\n% Discussion:\n%\n% PDF(X)(M,N) = M**(M/2) * X**((M-2)/2)\n% / ( Beta(M/2,N/2) * N**(M/2) * ( 1 + (M/N) * X )**((M+N)/2)\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 X, the argument of the PDF.\n% 0.0 <= X\n%\n% Input, integer M, N, the parameters of the PDF.\n% 1 <= M,\n% 1 <= N.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x < 0.0 )\n\n pdf = 0.0;\n\n else\n\n a = m;\n b = n;\n\n top = sqrt ( m^m * n^n * x^( m - 2 ) );\n bot1 = beta ( m / 2.0, n / 2.0 );\n bot2 = sqrt ( ( n + m * x )^( m + n ) );\n\n pdf = top / ( bot1 * bot2 );\n\n end\n\n return\nend\n", "meta": {"author": "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/f_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7736658965312344}} {"text": "function X = newtonraphson(Eqn_Str,Start_Point,Max_Iter)\n\n% Function :\n% X = newtonraphson(fun_str,Start_Point)\n% Finds the root of an equation by NEWTON-RAPHSON METHOD.\n% \n% x(n+1) = x(n) - (F(x(n))/diff(F(x(n)));\n%\n% INPUTS :\n% Eqn_Str : The equation whose root has to be find.\n% Eqn_Str Should be an string format.\n% Example : \n% if F(x) = x^4 - x - 10\n% the Eqn_Str = 'x^4 - x - 10';\n% \n% Start_Point : Initial value of root X ==> x0\n%\n% Max_Iter : Maximum number of iterations\n% \n% OUTPUT : \n% X : Estimeted root of Equation.\n%--------------------------------------------------------------------------\n% By :-\n% SANDEEP SOLANKI\n% rtm_sandeep@rediffmail.com\n%--------------------------------------------------------------------------\nif nargin < 2\n error('Not Enough Input Arguments');\nend\n\nif nargin < 3\n Max_Iter = 1000;\nend\n\nif ~ischar(Eqn_Str)\n error('Funtion Should Be an String');\nend\n\nfx = inline(Eqn_Str);\nfxd = inline(diff(Eqn_Str));\n\nx0 = Start_Point;\ndisp(['F(X) = ' Eqn_Str]);\ndisp(['X0 = ' num2str(x0)]);\n% Iterating\nfor i = 1 : Max_Iter\n s1=sprintf(' Iteration : %1.0f',i);\n disp(s1);\n x1 = x0 - (fx(x0)/fxd(x0));\n \n s2=sprintf(' X(%0.0f) = %0.15f',i,x1);\n disp(s2);\n if x1 == x0\n disp('Terminating Process : Value of Root Repeated');\n break;\n else\n x0 = x1; \n end\nend\n\nif x1 == NaN\n error('Start Point is Not Correct');\nend\nX = x1;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37090-newton-raphson/newtonraphson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7736658885486685}} {"text": "function membership=paretoset(X)\n\n% PARETOSET To get the Pareto set from a given set of points.\n% synopsis: membership =paretoset (objectiveMatrix)\n% where:\n% objectiveMatrix: [number of points X number of objectives] array\n% membership: [number of points X 1] logical vector to indicate if ith\n% point belongs to the Pareto set (true) or not (false).\n%\n% by Yi Cao, Cranfield University, 02 June 2007\n% Revised by Yi Cao on 17 October 2007\n% Version 3, 21 October 2007, new sorting scheme to improve speed.\n% Bugfix, 25 July 2008, devided by zero error is fixed.\n%\n% Examples: see paretoset_examples\n%\n\nm=size(X,1);\nXmin=min(X);\nX1=X-Xmin(ones(m,1),:); %make sure X1>=0;\nXmean=mean(X1); \n%sort X1 so that dominated points can be removed quickly\n[x,checklist]=sort(max(X1./(Xmean(ones(m,1),:)+1)));\nY=X(checklist,:); \nmembership=false(m,1);\nwhile numel(checklist)>1\n k=checklist(1);\n [membership(k),checklist,Y]=paretosub(Y,checklist);\nend\nmembership(checklist)=true;\n\nfunction [ispareto,nondominated,X]=paretosub(X,checklist)\n\nZ=X-X(ones(size(X,1),1),:);\nnondominated=any(Z<0,2); %retain nondominated points from the check list \nispareto=all(any(Z(nondominated,:)>0,2)); %check if current point belongs to pareto set \nX=X(nondominated,:);\nnondominated=checklist(nondominated);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15181-pareto-set/paretoset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7736362599857276}} {"text": "%%%%%%%VERSION 2\n%%ANOTHER DESCRIBTION OF GABOR FILTER\n\n%The Gabor filter is basically a Gaussian (with variances sx and sy along x and y-axes respectively)\n%modulated by a complex sinusoid (with centre frequencies U and V along x and y-axes respectively) \n%described by the following equation\n%%\n% -1 x' ^ y' ^ \n%%% G(x,y,theta,f) = exp ([----{(----) 2+(----) 2}])*cos(2*pi*f*x');\n% 2 sx' sy'\n%%% x' = x*cos(theta)+y*sin(theta);\n%%% y' = y*cos(theta)-x*sin(theta);\n\n%% Describtion :\n\n%% I : Input image\n%% Sx & Sy : Variances along x and y-axes respectively\n%% f : The frequency of the sinusoidal function\n%% theta : The orientation of Gabor filter\n\n%% G : The output filter as described above\n%% gabout : The output filtered image\n\n\n\n%% Author : Ahmad poursaberi e-mail : a.poursaberi@ece.ut.ac.ir\n%% Faulty of Engineering, Electrical&Computer Department,Tehran\n%% University,Iran,June 2004\n\nfunction [G,gabout] = gaborfilter(I,Sx,Sy,f,theta);\n\nif isa(I,'double')~=1 \n I = double(I);\nend\n\nfor x = -fix(Sx):fix(Sx)\n for y = -fix(Sy):fix(Sy)\n xPrime = x * cos(theta) + y * sin(theta);\n yPrime = y * cos(theta) - x * sin(theta);\n G(fix(Sx)+x+1,fix(Sy)+y+1) = exp(-.5*((xPrime/Sx)^2+(yPrime/Sy)^2))*cos(2*pi*f*xPrime);\n end\nend\n\nImgabout = conv2(I,double(imag(G)),'same');\nRegabout = conv2(I,double(real(G)),'same');\n\ngabout = sqrt(Imgabout.*Imgabout + Regabout.*Regabout);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/5237-2d-gabor-filterver123/gaborfilter1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948917260153714, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7735881801841916}} {"text": "function [var, U, lambda] = ppca(x, ppca_dim)\n%PPCA\tProbabilistic Principal Components Analysis\n%\n%\tDescription\n%\t [VAR, U, LAMBDA] = PPCA(X, PPCA_DIM) computes the principal\n%\tcomponent subspace U of dimension PPCA_DIM using a centred covariance\n%\tmatrix X. The variable VAR contains the off-subspace variance (which\n%\tis assumed to be spherical), while the vector LAMBDA contains the\n%\tvariances of each of the principal components. This is computed\n%\tusing the eigenvalue and eigenvector decomposition of X.\n%\n%\tSee also\n%\tEIGDEC, PCA\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n\nif ppca_dim ~= round(ppca_dim) | ppca_dim < 1 | ppca_dim > size(x, 2)\n error('Number of PCs must be integer, >0, < dim');\nend\n\n[ndata, data_dim] = size(x);\n% Assumes that x is centred and responsibility weighted\n% covariance matrix\n[l Utemp] = eigdec(x, data_dim);\n% Zero any negative eigenvalues (caused by rounding)\nl(l<0) = 0;\n% Now compute the sigma squared values for all possible values\n% of q\ns2_temp = cumsum(l(end:-1:1))./[1:data_dim]';\n% If necessary, reduce the value of q so that var is at least\n% eps * largest eigenvalue\nq_temp = min([ppca_dim; data_dim-min(find(s2_temp/l(1) > eps))]);\nif q_temp ~= ppca_dim\n wstringpart = 'Covariance matrix ill-conditioned: extracted';\n wstring = sprintf('%s %d/%d PCs', ...\n wstringpart, q_temp, ppca_dim);\n warning(wstring);\nend\nif q_temp == 0\n % All the latent dimensions have disappeared, so we are\n % just left with the noise model\n var = l(1)/data_dim;\n lambda = var*ones(1, ppca_dim);\nelse\n var = mean(l(q_temp+1:end));\nend \nU = Utemp(:, 1:q_temp);\nlambda(1:q_temp) = l(1:q_temp);\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/netlab3.3/ppca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.773447528308432}} {"text": "%==============================================================================\n% Copyright (C) 2005, Jan Modersitzki and Nils Papenberg, see copyright.m,\n% this file is part of the FLIRT Package, all rights reserved;\n% http://www.math.uni-luebeck.de/SAFIR/FLIRT-MATLAB.html\n%==============================================================================\n% function [B,Bstr] = getElasticMatrixStg(Omega,m,mu,lambda);\n% generates the elastic matrix B for the domain Omega with resolution m,\n% by default, mu = 1, lambda = 0;\n%==============================================================================\nfunction [B,Bstr] = getElasticMatrixStg(Omega,m,mu,lambda)\n\nBstr = 'elastic-stg';\nif ~exist('mu','var'), mu = 1; end;\nif ~exist('lambda','var'), lambda = 0; end;\nh = Omega./m;\n\ndim = length(Omega);\n\nswitch dim\n case 2\n d11 = spdiags(ones(m(1),1)*[-1,1],[0,1],m(1),m(1)+1)/h(1);\n d12 = spdiags(ones(m(2)-1,1)*[-1,1],[0,1],m(2)-1,m(2))/h(2);\n d21 = spdiags(ones(m(1)-1,1)*[-1,1],[0,1],m(1)-1,m(1))/h(1);\n d22 = spdiags(ones(m(2),1)*[-1,1],[0,1],m(2),m(2)+1)/h(2);\n\n D11 = sparse(kron(speye(m(2)),d11));\n D12 = sparse(kron(d12,speye(m(1)+1)));\n D21 = sparse(kron(speye(m(2)+1),d21));\n D22 = sparse(kron(d22,speye(m(1))));\n\n % build the elastic operator\n %\n % | \\nabla 0 |\n % B = | |\n % | 0 \\nabla |\n % | |\n % | Div1 Div2 |\n % B[U] = [\\partial_1 U1,\\partial_2 U1, \\partial_1 U2,\\partial_2 U2,div(U)]\n\n a = sqrt(mu);\n b = sqrt(mu+lambda);\n n1 = (m(1)+1)*m(2);\n n2 = m(1)*(m(2)+1);\n j1 = size(D11,1);\n j2 = size(D12,1);\n j3 = size(D21,1);\n j4 = size(D22,1);\n\n B = [ a*D11,sparse(j1,n2);\n a*D12,sparse(j2,n2);\n sparse(j3,n1),a*D21;\n sparse(j4,n1),a*D22;\n b*D11,b*D22];\n return;\n \n otherwise\n error('nyi');\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/getElasticMatrixStg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.773444398243264}} {"text": "function eigg_segmentation\n% This code was written by Muhammet Balcilar , France,\n% muhammetbalcilar@gmail.com, inspired from following reference\n%\n% This Matlab code implements an edge-based active contour model as an\n% application of the Distance Regularized Level Set Evolution (DRLSE) formulation in Li et al's paper:\n%\n% C. Li, C. Xu, C. Gui, M. D. Fox, \"Distance Regularized Level Set Evolution and Its Application to Image Segmentation\", \n% IEEE Trans. Image Processing, vol. 19 (12), pp.3243-3254, 2010.\n\nclose all\n\n%% step1, read grayscale image\nImg=imread('Inputs/eigg_scotland.jpg');\nImg=rgb2gray(Img);\nfrm=0;\n%% step2, set params\ntimestep=5; % time step\nmu=0.2; % coefficient of the distance regularization term R(phi)\nlambda=5; %coefficient of the weighted length term L(phi)\nalfa= -3; % coefficient of the weighted area term A(phi)\nepsilon=1.5; % papramater that specifies the width of the DiracDelta function\nc0=2;\nmaxiter=602;\nsigma=2.0; % scale parameter in Gaussian kernel\n\n%% step3 smooth image with gaussian filter\nG=fspecial('gaussian',30,sigma); % 15 Caussian kernel\nImg_smooth=conv2(Img,G,'same'); % smooth image by Gaussiin convolution\nfigure(1);\nimagesc(Img_smooth,[0, 255]); axis off; axis equal; colormap(gray);\ntitle('Smoothed image');\n\n%% step4 calculate edge indicator according to Eq23\n[Ix,Iy]=gradient(Img_smooth);\nf=Ix.^2+Iy.^2;\ng=1./(1+f); % edge indicator function.\ng=exp(-f);\nfigure(2);\nimagesc(g); axis off; axis equal; \ntitle('g, edge indicator');\n\n%% step5, set initial phi\nphi = -c0*ones(size(Img));\nphi(50:650,50:500)=c0;\n%phi(350:370,200:220)=-c0;\nfigure(3);\nimagesc(phi);\naxis off; axis equal;colormap(jet);\ntitle('initial phi matrix');\n\n[vx, vy]=gradient(g);\nfigure(4);\nsubplot(1,2,1);imagesc(vx); title('x directioned gradient of g');\nsubplot(1,2,2);imagesc(vy); title('y directioned gradient of g');\n\nfor k=1:maxiter\n %% step6, check boundary conditions\n phi=NeumannBoundCond(phi);\n \n %% step 7 calculate differential of regularized term in Eq.30\n distRegTerm=distReg_p2(phi);\n \n %% step8 calculate differential of area term in Eq.30\n diracPhi=Dirac(phi,epsilon);\n areaTerm=diracPhi.*g;\n \n %% step9 calculate differential of length term in Eq.30\n [phi_x,phi_y]=gradient(phi);\n s=sqrt(phi_x.^2 + phi_y.^2);\n Nx=phi_x./(s+1e-10); % add a small positive number to avoid division by zero\n Ny=phi_y./(s+1e-10);\n edgeTerm=diracPhi.*(vx.*Nx+vy.*Ny) + diracPhi.*g.*div(Nx,Ny);\n \n %% step 10 update phi according to Eq.20\n phi=phi + timestep*(mu/timestep*distRegTerm + lambda*edgeTerm + alfa*areaTerm);\n \n %% show result in every 50 iteration\n if mod(k,50)==1\n frm=frm+1;\n close all\n h=figure(5);\n set(gcf,'color','w');\n subplot(1,2,1);\n II=Img;\n II(:,:,2)=Img;II(:,:,3)=Img;\n imshow(II); axis off; axis equal; hold on; \n q=contour(phi, [0,0], 'r');\n msg=['contour result , iteration number=' num2str(k)];\n title(msg);\n subplot(1,2,2);\n mesh(-phi,[-2 2]); \n hold on; contour(phi, [0,0], 'r','LineWidth',2);\n \n view([180-30 -65-180]); \n msg=['phi result , iteration number=' num2str(k)];\n title(msg);\n pause(0.1)\n \n % gif video\n \n frame = getframe(h);\n im = frame2im(frame);\n [imind,cm] = rgb2ind(im,256);\n %Write to the GIF File\n if frm == 1 \n imwrite(imind,cm,'Outputs/eigg.gif','gif', 'Loopcount',inf);\n else \n imwrite(imind,cm,'Outputs/eigg.gif','gif','WriteMode','append');\n end\n end\n \n \n %% step 11 if maxiter done then finish, else return step6\nend\n%% Step 12. show last iteration results\nfigure(6);\nimagesc(Img,[0, 255]); axis off; axis equal; colormap(gray); hold on; contour(phi, [0,0], 'r');\nmsg=['phi result , iteration number=' num2str(k)];\ntitle(msg);\n\n\nfunction f = distReg_p2(phi)\n% compute the distance regularization term with the double-well potential p2 in eqaution (16)\n[phi_x,phi_y]=gradient(phi);\ns=sqrt(phi_x.^2 + phi_y.^2);\na=(s>=0) & (s<=1);\nb=(s>1);\nps=a.*sin(2*pi*s)/(2*pi)+b.*(s-1); % compute first order derivative of the double-well potential p2 in eqaution (16)\ndps=((ps~=0).*ps+(ps==0))./((s~=0).*s+(s==0)); % compute d_p(s)=p'(s)/s in equation (10). As s-->0, we have d_p(s)-->1 according to equation (18)\nf = div(dps.*phi_x - phi_x, dps.*phi_y - phi_y) + 4*del2(phi);\n\nfunction f = div(nx,ny)\n[nxx,junk]=gradient(nx);\n[junk,nyy]=gradient(ny);\nf=nxx+nyy;\n\nfunction f = Dirac(x, sigma)\nf=(1/2/sigma)*(1+cos(pi*x/sigma));\nb = (x<=sigma) & (x>=-sigma);\nf = f.*b;\n\nfunction g = NeumannBoundCond(f)\n% Make a function satisfy Neumann boundary condition\n[nrow,ncol] = size(f);\ng = f;\ng([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]);\ng([1 nrow],2:end-1) = g([3 nrow-2],2:end-1);\ng(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]);", "meta": {"author": "balcilar", "repo": "DRLSE-Image-Segmentation", "sha": "c775db4795c8cafd1d1cc7e4431b7af8bb2f5330", "save_path": "github-repos/MATLAB/balcilar-DRLSE-Image-Segmentation", "path": "github-repos/MATLAB/balcilar-DRLSE-Image-Segmentation/DRLSE-Image-Segmentation-c775db4795c8cafd1d1cc7e4431b7af8bb2f5330/eigg_segmentation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7734443935557687}} {"text": "function x=modcent(x,r);\n%MODCENT Centered modulo\n% Usage: y=modcent(x,r);\n%\n% `modcent(x,r)` computes the modulo of *x* in the range $[-r/2,r/2[$.\n%\n% As an example, to compute the modulo of *x* in the range $[-\\pi,\\pi[$ use\n% the call::\n%\n% y = modcent(x,2*pi);\n\nx=mod(x,r); \nidx=x>r/2;\nx(idx)=x(idx)-r;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/fourier/modcent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7733987929811258}} {"text": "function [ n_data_new, n, m, x, fx ] = legendre_associated_values ( n_data )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_ASSOCIATED_VALUES returns values of associated Legendre functions.\n%\n% Discussion:\n%\n% The function considered is the associated Legendre function P^M_N(X).\n%\n% In Mathematica, the function\n%\n% LegendreP [ n, m, x ]\n%\n% returns the value of the associated Legendre function P^M_N(X).\n%\n% Differential equation:\n%\n% (1-X*X) * Y'' - 2 * X * Y + ( N (N+1) - (M*M/(1-X*X)) * Y = 0\n%\n% First terms:\n%\n% M = 0 ( = Legendre polynomials of first kind P(N)(X) )\n%\n% P00 = 1\n% P10 = 1 X\n% P20 = ( 3 X^2 - 1)/2\n% P30 = ( 5 X^3 - 3 X)/2\n% P40 = ( 35 X^4 - 30 X^2 + 3)/8\n% P50 = ( 63 X^5 - 70 X^3 + 15 X)/8\n% P60 = (231 X^6 - 315 X^4 + 105 X^2 - 5)/16\n% P70 = (429 X^7 - 693 X^5 + 315 X^3 - 35 X)/16\n%\n% M = 1\n%\n% P01 = 0\n% P11 = 1 * SQRT(1-X*X)\n% P21 = 3 * SQRT(1-X*X) * X\n% P31 = 1.5 * SQRT(1-X*X) * (5*X*X-1)\n% P41 = 2.5 * SQRT(1-X*X) * (7*X*X*X-3*X)\n%\n% M = 2\n%\n% P02 = 0\n% P12 = 0\n% P22 = 3 * (1-X*X)\n% P32 = 15 * (1-X*X) * X\n% P42 = 7.5 * (1-X*X) * (7*X*X-1)\n%\n% M = 3\n%\n% P03 = 0\n% P13 = 0\n% P23 = 0\n% P33 = 15 * (1-X*X)^1.5\n% P43 = 105 * (1-X*X)^1.5 * X\n%\n% M = 4\n%\n% P04 = 0\n% P14 = 0\n% P24 = 0\n% P34 = 0\n% P44 = 105 * (1-X*X)^2\n%\n% Recursion:\n%\n% if N < M:\n% P(N,M) = 0\n% if N = M:\n% P(N,M) = (2*M-1)!! * (1-X*X)^(M/2) where N!! means the product of\n% all the odd integers less than or equal to N.\n% if N = M+1:\n% P(N,M) = X*(2*M+1)*P(M,M)\n% if M+1 < N:\n% P(N,M) = ( X*(2*N-1)*P(N-1,M) - (N+M-1)*P(N-2,M) )/(N-M)\n%\n% Restrictions:\n%\n% -1 <= X <= 1\n% 0 <= M <= N\n%\n% Special values:\n%\n% P(N,0)(X) = P(N)(X), that is, for M=0, the associated Legendre\n% function of the first kind equals the Legendre polynomial of the\n% first kind.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N_DATA, indicates the index of the previous test data\n% returned, or is 0 if this is the first call. For repeated calls,\n% set the input value of N_DATA to the output value of N_DATA_NEW\n% from the previous call.\n%\n% Output, integer N_DATA_NEW, the index of the test data.\n%\n% Output, integer N, integer M, real X, the arguments of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 19;\n n_vec = [ ...\n 1, 1, 1, 1, ...\n 1, 2, 2, 2, ...\n 3, 3, 3, 3, ...\n 4, 5, 6, 7, ...\n 8, 9, 10 ];\n m_vec = [ ...\n 0, 0, 0, 0, ...\n 1, 0, 1, 2, ...\n 0, 1, 2, 3, ...\n 2, 2, 3, 3, ...\n 4, 4, 5 ];\n fx_vec = [ ...\n 0.000000E+00, 0.500000E+00, 0.707107E+00, 1.000000E+00, ...\n -0.866025E+00, -0.125000E+00, -1.29904E+00, 2.25000E+00, ...\n -0.437500E+00, -0.324759E+00, 5.62500E+00, -9.74278E+00, ...\n 4.21875E+00, -4.92187E+00, 12.7874E+00, 116.685E+00, ...\n -1050.67E+00, -2078.49E+00, 30086.2E+00 ];\n x_vec = [ ...\n 0.0E+00, 0.5E+00, 0.7071067E+00, 1.0E+00, ...\n 0.5E+00, 0.5E+00, 0.5E+00, 0.5E+00, ...\n 0.5E+00, 0.5E+00, 0.5E+00, 0.5E+00, ...\n 0.5E+00, 0.5E+00, 0.5E+00, 0.5E+00, ...\n 0.5E+00, 0.5E+00, 0.5E+00 ];\n\n n_data_new = n_data;\n\n if ( n_data_new < 0 )\n n_data_new = 0;\n end\n\n n_data_new = n_data_new + 1;\n\n if ( n_max < n_data_new )\n n_data_new = 0;\n n = 0;\n m = 0;\n x = 0.0E+00;\n fx = 0.0E+00;\n else\n n = n_vec(n_data_new);\n m = m_vec(n_data_new);\n x = x_vec(n_data_new);\n fx = fx_vec(n_data_new);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/legendre_associated_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7733947158970165}} {"text": "function [xi,w]=secondOrderTriangleCubPoints()\n%%SECONDORDERTRIANGLECUBPOINTS Obtain second-order cubature points for\n% integration over a triangle in 2D. The points and weights are for the\n% triangle with vertices (1,0), (0,1), (0,0), but can be transformed to\n% any triangle using transformSimplexTriPoints.\n%\n%INPUTS: None\n%\n%OUTPUTS: xi A 2XnumCubPoints set of points for the standard triangle.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the triangle (1/2).\n%\n%This function implements the points given in [1] (3 points).\n%\n%EXAMPLE:\n%Given the vertices of the simplex, we compare a second-order moment\n%computed using these cubature points to one computed using\n%monomialIntSimplex. The results are the same within typical finite\n%precision limits.\n% [xi,w]=secondOrderTriangleCubPoints();\n% alpha=[1;1];\n% theMoment=findMomentFromSamp(alpha,xi,w)\n% intVal=monomialIntSimplex(alpha)\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=[-0.66666666666666666666666666666666666667, 0.33333333333333333333333333333333333333, 0.66666666666666666666666666666666666667;\n 0.33333333333333333333333333333333333333, -0.66666666666666666666666666666666666667, 0.66666666666666666666666666666666666667;\n -0.66666666666666666666666666666666666667, -0.66666666666666666666666666666666666667, 0.66666666666666666666666666666666666667];\n\nw=M(:,3);\nxi=M(:,1:2)';\n%Transform the points to the standard triangle.\nv1=[-1,-1, 1;\n -1, 1,-1];\nv2=[1,0,0;\n 0,1,0];\n[A,d]=affineTransBetweenTriangles(v1,v2);\nxi=bsxfun(@plus,A*xi,d);\nw=w/4;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Simplex/Triangles/secondOrderTriangleCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7733439075139406}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Inverse kinematics for the 3dof planar robot\n% T: homogeneous matrix\n% robot: structure with arm parameters\n% returns: all possible solutions or q = [q1 q2] that place the end effectors at the\n% position specified by T. Two possible solutions q1 and q2 q3 and q4 are returned,\n% generally called elbow up and elbow down, combined with \n% Author: Arturo Gil Aparicio arturo.gil@umh.es\n% Date: 08/03/2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction q = inversekinematic_3dofplanar(robot, T)\n\nfprintf('\\nComputing inverse kinematics for the %s robot', robot.name);\n\n\n%Initialize q\n% q = [q1 q2 q3 q4], atends for two possible solutions\nq=zeros(3,4);\n\na = eval(robot.DH.a);\n\n%Link lengths\nL1=abs(a(1));\nL2=abs(a(2));\nL3=abs(a(2));\n\n\n%T= [ nx ox ax Px;\n% ny oy ay Py;\n% nz oz az Pz];\nQ=T(1:3,4);\n\n%find angle Phi\nx3 = T(1:3,1);\n\ncphi = x3'*[1 0 0]';\nsphi = x3'*[0 1 0]';\nphi = atan2(sphi, cphi);\n\n\n%Find point P from P and vector (nx, ny, nz)\nP = Q - a(3)*T(1:3,1);\n\n%Distance of the point to the origin. \nR= sqrt(P(1)^2+P(2)^2);\n\nif R > (L1+L2)\n disp('\\ninversekinematic_3dofplanar: unfeasible solution. The point cannot be reached'); \nend\n\n%compute geometric solution\nbeta = atan2(P(2),P(1)); \ngamma = real(acos((L1^2+R^2-L2^2)/(2*R*L1)));\ndelta = real(acos((L1^2+L2^2-R^2)/(2*L1*L2)));\n\n%arrange possible combinations for q(1) and q(2) \n%elbow down elbow up solutions\nq =[beta+gamma beta-gamma;\n delta-pi pi-delta];\n\n%in this case, phi = q(1) + q(2) + q(3) and\n%q(3) can be computed as q(3) = phi - q(1) - q(2) \n%corresponding to each of the previous solutions, a unique q(3) can be\n%computed for each case\nfor i=1:2 %iterate through columns \n q(3,i) = phi - q(1,i) - q(2,i); \nend\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/example/3dofplanar/inversekinematic_3dofplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7732620066653856}} {"text": "% Minimize sidelobe level of an array with arbitrary 2-D geometry\n% \"Convex optimization examples\" lecture notes (EE364) by S. Boyd\n% \"Antenna array pattern synthesis via convex optimization\"\n% by H. Lebret and S. Boyd\n% (figures are generated)\n%\n% Designs an antenna array such that:\n% - it minimizes sidelobe level outside the beamwidth of the pattern\n% - it has a unit sensitivity at some target direction\n% - it has nulls (zero sensitivity) at specified direction(s) (optional)\n%\n% This is a convex problem (after sampling it can be formulated as an SOCP).\n%\n% minimize max |y(theta)| for theta outside the beam\n% s.t. y(theta_tar) = 1\n% y(theta_null) = 0 (optional)\n%\n% where y is the antenna array gain pattern (complex function) and\n% variables are w (antenna array weights or shading coefficients).\n% Gain pattern is a linear function of w: y(theta) = w'*a(theta)\n% for some a(theta) describing antenna array configuration and specs.\n%\n% Written for CVX by Almir Mutapcic 02/02/06\n\n% select array geometry\nARRAY_GEOMETRY = '2D_RANDOM';\n% ARRAY_GEOMETRY = '1D_UNIFORM_LINE';\n% ARRAY_GEOMETRY = '2D_UNIFORM_LATTICE';\n\n% select if the optimal array pattern should enforce nulls or not\nHAS_NULLS = 0; % HAS_NULLS = 1;\n\n%********************************************************************\n% problem specs\n%********************************************************************\nlambda = 1; % wavelength\ntheta_tar = 60; % target direction (should be an integer -- discretization)\nhalf_beamwidth = 10; % half beamwidth around the target direction\n\n% angles where we want nulls (optional)\nif HAS_NULLS\n theta_nulls = [95 110 120 140 225];\nend\n\n%********************************************************************\n% random array of n antenna elements\n%********************************************************************\nif strcmp( ARRAY_GEOMETRY, '2D_RANDOM' )\n % set random seed to repeat experiments\n rand('state',0);\n\n % (uniformly distributed on [0,L]-by-[0,L] square)\n n = 40;\n L = 5;\n loc = L*rand(n,2);\n angleRange = 360;\n\n%********************************************************************\n% uniform 1D array with n elements with inter-element spacing d\n%********************************************************************\nelseif strcmp( ARRAY_GEOMETRY, '1D_UNIFORM_LINE' )\n % (unifrom array on a line)\n n = 30;\n d = 0.45*lambda;\n loc = [d*[0:n-1]' zeros(n,1)];\n angleRange = 180;\n\n%********************************************************************\n% uniform 2D array with m-by-m element with d spacing\n%********************************************************************\nelseif strcmp( ARRAY_GEOMETRY, '2D_UNIFORM_LATTICE' )\n m = 6; n = m^2;\n d = 0.45*lambda;\n\n loc = zeros(n,2);\n for x = 0:m-1\n for y = 0:m-1\n loc(m*y+x+1,:) = [x y];\n end\n end\n loc = loc*d;\n angleRange = 360;\n\nelse\n error('Undefined array geometry')\nend\n\n%********************************************************************\n% construct optimization data\n%********************************************************************\n% build matrix A that relates w and y(theta), ie, y = A*w\ntheta = [1:angleRange]';\nA = kron(cos(pi*theta/180), loc(:,1)') + kron(sin(pi*theta/180), loc(:,2)');\nA = exp(2*pi*i/lambda*A);\n\n% target constraint matrix\n[diff_closest, ind_closest] = min( abs(theta - theta_tar) );\nAtar = A(ind_closest,:);\n\n% nulls constraint matrix\nif HAS_NULLS\n Anull = []; ind_nulls = [];\n for k = 1:length(theta_nulls)\n [diff_closest, ind_closest] = min( abs(theta - theta_nulls(k)) );\n Anull = [Anull; A(ind_closest,:)];\n ind_nulls = [ind_nulls ind_closest];\n end\nend\n\n% stopband constraint matrix\nind = find(theta <= (theta_tar-half_beamwidth) | ...\n theta >= (theta_tar+half_beamwidth) );\nif HAS_NULLS, ind = setdiff(ind,ind_nulls); end;\nAs = A(ind,:);\n\n%********************************************************************\n% optimization problem\n%********************************************************************\ncvx_begin\n variable w(n) complex\n minimize( max( abs(As*w) ) )\n subject to\n Atar*w == 1; % target constraint\n if HAS_NULLS % nulls constraints\n Anull*w == 0;\n end\ncvx_end\n\n% check if problem was successfully solved\ndisp(['Problem is ' cvx_status])\nif ~strfind(cvx_status,'Solved')\n return\nend\n\nmin_sidelobe_level = 20*log10( max(abs(As*w)) );\nfprintf(1,'The minimum sidelobe level is %3.2f dB.\\n\\n',...\n min_sidelobe_level );\n\n%********************************************************************\n% plots\n%********************************************************************\nfigure(1), clf\nplot(loc(:,1),loc(:,2),'o')\ntitle('Antenna locations')\n\n% plot array pattern\nif angleRange == 180,\n theta = [1:360]';\n A = [ A; -A ];\nend\ny = A*w;\nfigure(2), clf\nymin = floor(0.1*min_sidelobe_level)*10-10; ymax = 0;\nplot([1:360], 20*log10(abs(y)), ...\n [theta_tar theta_tar],[ymin ymax],'r--',...\n [theta_tar+half_beamwidth theta_tar+half_beamwidth],[ymin ymax],'g--',...\n [theta_tar-half_beamwidth theta_tar-half_beamwidth],[ymin ymax],'g--');\nif HAS_NULLS % add lines that represent null positions\n hold on;\n for k = 1:length(theta_nulls)\n plot([theta_nulls(k) theta_nulls(k)],[ymin ymax],'m--');\n end\n hold off;\nend\nxlabel('look angle'), ylabel('mag y(theta) in dB');\naxis([0 360 ymin ymax]);\n\n% polar plot\nfigure(3), clf\nzerodB = -ymin;\ndBY = 20*log10(abs(y)) + zerodB;\nind = find( dBY <= 0 ); dBY(ind) = 0;\nplot(dBY.*cos(pi*theta/180), dBY.*sin(pi*theta/180), '-');\naxis([-zerodB zerodB -zerodB zerodB]), axis('off'), axis('square')\nhold on\nplot(zerodB*cos(pi*theta/180),zerodB*sin(pi*theta/180),'k:') % 0 dB\nplot( (min_sidelobe_level + zerodB)*cos(pi*theta/180), ...\n (min_sidelobe_level + zerodB)*sin(pi*theta/180),'k:') % min level\ntext(-zerodB,0,'0 dB')\ntt = text(-(min_sidelobe_level + zerodB),0,sprintf('%0.1f dB',min_sidelobe_level));\nset(tt,'HorizontalAlignment','right');\ntheta_1 = theta_tar+half_beamwidth;\ntheta_2 = theta_tar-half_beamwidth;\nplot([0 55*cos(theta_tar*pi/180)], [0 55*sin(theta_tar*pi/180)], 'k:')\nplot([0 55*cos(theta_1*pi/180)], [0 55*sin(theta_1*pi/180)], 'k:')\nplot([0 55*cos(theta_2*pi/180)], [0 55*sin(theta_2*pi/180)], 'k:')\nif HAS_NULLS % add lines that represent null positions\n for k = 1:length(theta_nulls)\n plot([0 55*cos(theta_nulls(k)*pi/180)], ...\n [0 55*sin(theta_nulls(k)*pi/180)], 'k:')\n end\nend\nhold off\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/antenna_array_design/ant_array_min_sidelobe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7732619947154857}} {"text": "function [ px, pxp ] = least_val2 ( nterms, b, c, d, x )\n\n%*****************************************************************************80\n%\n%% LEAST_VAL2 evaluates a least squares polynomial defined by LEAST_SET.\n%\n% Discussion:\n%\n% This routine also computes the derivative of the polynomial.\n%\n% The least squares polynomial is assumed to be defined as a sum\n%\n% P(X) = SUM ( I = 1 to NTERMS ) D(I) * P(I-1,X)\n%\n% where the orthogonal basis polynomials P(I,X) satisfy the following\n% three term recurrence:\n%\n% P(-1,X) = 0\n% P(0,X) = 1\n% P(I,X) = ( X - B(I-1) ) * P(I-1,X) - C(I-1) * P(I-2,X)\n%\n% Therefore, the least squares polynomial can be evaluated as follows:\n%\n% If NTERMS is 1, then the value of P(X) is D(1) * P(0,X) = D(1).\n%\n% Otherwise, P(X) is defined as the sum of NTERMS > 1 terms. We can\n% reduce the number of terms by 1, because the polynomial P(NTERMS,X)\n% can be rewritten as a sum of polynomials; Therefore, P(NTERMS,X)\n% can be eliminated from the sum, and its coefficient merged in with\n% those of other polynomials. Repeat this process for P(NTERMS-1,X)\n% and so on until a single term remains.\n% P(NTERMS,X) of P(NTERMS-1,X)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NTERMS, the number of terms in the least squares\n% polynomial. NTERMS must be at least 1. The value of NTERMS\n% may be reduced from the value given to LEAST_SET.\n% This will cause LEAST_VAL to evaluate the least squares polynomial\n% of the lower degree specified.\n%\n% Input, real B(NTERMS), C(NTERMS), D(NTERMS), the information\n% computed by LEAST_SET.\n%\n% Input, real X, the point at which the least squares polynomial\n% is to be evaluated.\n%\n% Output, real PX, PXP, the value and derivative of the least\n% squares polynomial at X.\n%\n px = d(nterms);\n pxp = 0.0;\n pxm1 = 0.0;\n pxpm1 = 0.0;\n\n for i = nterms-1 : -1 : 1\n\n pxm2 = pxm1;\n pxpm2 = pxpm1;\n pxm1 = px;\n pxpm1 = pxp;\n\n if ( i == nterms-1 )\n px = d(i) + ( x - b(i) ) * pxm1;\n pxp = pxm1 + ( x - b(i) ) * pxpm1;\n else\n px = d(i) + ( x - b(i) ) * pxm1 - c(i+1) * pxm2;\n pxp = pxm1 + ( x - b(i) ) * pxpm1 - c(i+1) * pxpm2;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/least_val2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8670357563664173, "lm_q1q2_score": 0.7732320742896733}} {"text": "function xCommon=findLongestCommonSubsequence(x,y)\n%%FINDLONGESTCOMMONSUBSEQUENCE Given two vectors of numbers, characters,\n% etc., find the longest sequence of elements in both of them.\n% The elements must appear in order need NOT BE CONSECUTIVE.\n%\n%INPUTS: x,y Two vectors.\n%\n%OUTPUTS: xCommon The longest common subsequence shared by the vectors.\n% The elements in the subsequence need not be consecutive.\n% For example, the longest common subsequence of \"dunkin\"\n% and \"doughnuts\" is \"dun\".\n%\n%The algorithm is taken from Chapter 15.4 of [1], but modified so that the\n%sequence comes out in order and to deal with Matlab addressing things from\n%1 instead of 0.\n%\n%REFERENCES:\n%[1] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein,\n% Introduction to Algorithms, 2nd ed. Cambridge, MA: The MIT Press,\n% 2001.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nm=length(x);\nn=length(y);\n\nc=zeros(m+1,n+1);\nfor i=m:-1:1\n for j=n:-1:1\n if(x(i)==y(j))\n c(i,j)=c(i+1,j+1)+1;\n else\n c(i,j)=max(c(i,j+1),c(i+1,j));\n end\n end\nend\n\ni=1;\nj=1;\n%Setting xCommon to x rather than alocating with zeros assured that xCommon\n%will have the same type and shape as x. This is good when x is a character\n%string.\nxCommon=x;\nnumFound=0;\nwhile(i<=m&&j<=n)\n if(x(i)==y(j))\n numFound=numFound+1;\n xCommon(numFound)=x(i);\n i=i+1;\n j=j+1;\n elseif(c(i+1,j)>=c(i,j+1))\n i=i+1;\n else\n j=j+1; \n end\nend\n\n%Get rid of extra elements in xCommon.\nxCommon=xCommon(1:numFound);\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/Operations_on_Sequences/findLongestCommonSubsequence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.7732320575134803}} {"text": "function F=HessTaylor(deltaT,dadx,d2adx,method)\n%%HESSTAYLOR Simulate a nonlinear continuous-time random process specified\n% by the Langevin equation forward in time by a step-size of\n% deltaT using a Taylor scheme.\n%\n%INPUTS: deltaT The size of the single step over which to generate the\n% state transition matrix.\n% dadx A xDimXxDim matrix of the derivative of the drift function\n% with respect to the state at state xCur and time curT.\n% d2adx A xDimXxDimXxDim matrix of the second derivative of the\n% drift function with respect to the state at state xCur and\n% time curT. The value at point (m,k,l) represents\n% d2a(m)/dx(k)dx(l). If not provided, this is assumed to be\n% zero.\n% method Set to 0 for the shorter Euler-Maruyama expansion,\n% otherwise will the Taylor expansion will be used (default).\n%\n%OUTPUTS: H The Hessian matrix of a nonlinear continuous-time random\n% process specified by the Langevin equation forward in time by a\n% step-size of deltaT using a strong Taylor scheme.\n%\n%The second derivative state prediction matrix is derived from the\n%stochastic order 1.5 Taylor scheme described in 10.4 of [1].\n%\n%REFERENCES:\n%[1] P. E. Kloeden and E. Platen, Numerical Solution of Stochastic\n% Differential Equations. Berlin: Springer, 1999.\n%\n%April 2015 David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(dadx,1);\nif(nargin<4||isempty(method))\n method=1;\nend\n\nif(method==0)\n F=deltaT*d2adx;\nelse\n %Assumes 3rd derivative is zero\n term1=zeros(xDim,xDim,xDim);\n term2=zeros(xDim,xDim,xDim);\n term3=zeros(xDim,xDim,xDim);\n for m=1:xDim\n term1(:,:,m)=d2adx(:,:,m)*dadx;\n term2(:,m,:)=d2adx(:,:,m)*dadx;\n term3(:,:,m)=dadx*d2adx(:,:,m);\n end\n \n F=deltaT*d2adx+(deltaT^2/2)*(term1+term2+term3);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Models/Discrete_Time/Jacobians/HessTaylor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7732183770965846}} {"text": "function mind = dijkstra_distance ( nv, ohd )\n\n%*****************************************************************************80\n%\n%% DIJKSTRA_DISTANCE uses Dijkstra's minimum distance algorithm.\n%\n% Discussion:\n%\n% We essentially build a tree. We start with only node 0 connected\n% to the tree, and this is indicated by setting CONNECTED(0) = 1.\n%\n% We initialize MIND(I) to the one step distance from node 0 to node I.\n% \n% Now we search among the unconnected nodes for the node MV whose minimum\n% distance is smallest, and connect it to the tree. For each remaining\n% unconnected node I, we check to see whether the distance from 0 to MV\n% to I is less than that recorded in MIND(I), and if so, we can reduce\n% the distance.\n%\n% After NV-1 steps, we have connected all the nodes to 0, and computed\n% the correct minimum distances.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 01 July 2010\n%\n% Author:\n%\n% Original C version by Norm Matloff, CS Dept, UC Davis.\n% This MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, integer OHD(NV,NV), the distance of the direct link between\n% nodes I and J.\n%\n% Output, integer MIND(NV), the minimum distance from node 1 to each node.\n%\n\n%\n% Start out with only node 1 connected to the tree.\n%\n connected(1) = 1;\n connected(2:nv) = 0;\n%\n% Initialize the minimum distance to the one-step distance.\n%\n mind(1:nv) = ohd(1,1:nv);\n%\n% Attach one more node on each iteration.\n%\n for step = 2 : nv\n%\n% Find the nearest unconnected node.\n%\n [ md, mv ] = find_nearest ( nv, mind, connected );\n\n if ( mv == - 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIJKSTRA_DISTANCE - Warning!\\n' );\n fprintf ( 1, ' Search terminated early.\\n' );\n fprintf ( 1, ' Graph might not be connected.\\n' );\n return\n end\n%\n% Mark this node as connected.\n%\n connected(mv) = 1;\n%\n% Having determined the minimum distance to node MV, see if\n% that reduces the minimum distance to other nodes.\n%\n mind = update_mind ( nv, mv, connected, ohd, mind );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/dijkstra/dijkstra_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.773218375250023}} {"text": "function vol = hist_vol(ticker, N)\n% HIST_VOL Calculate historical volatility\n% vol = hist_vol(ticker, N) is used to calculate the historical\n% volatility for the underlying asset specified in TICKER over N trading\n% days. If N is not specified, a default of 20 trading days will be\n% used.\n%\n% INPUTS\n% ticker --> A string or cell array of strings specifying the ticker\n% symbols for the underlying assets to use.\n% \n% N --> An integer specifying the number of days to use in the\n% volatility calculationg\n%\n% OUTPUT\n% The function will return the historical volatility for each of the\n% tickers passed to the function\n%\n% NOTES\n% This program uses the function 'hist_stock_data.m', which downloads\n% historical stock data to use for the volatility calculations.\n% Therefore, you must also download this function from my File\n% Exchange and place it in the same directory as this function.\n%\n% The historical volatility is calculated by using the closing prices\n% of each trading day. Additionally, one year of historical stock\n% data will be downloaded, limiting N to a maximum of roughly 252 (as\n% there are about 252 trading days in a year). If the user wishes to\n% allow larger N, changes must be made to the code when creating the\n% variable 'start_date'.\n\n% Created by Josiah Renfree\n% July 20, 2009\n\n% Error checking\nif nargin == 0 % If no inputs provided\n error('Please provide at least one ticker symbol')\nelseif nargin > 2 % If too many inputs provided\n error('Function accepts no more than 2 inputs')\nelseif ~ischar(ticker) && ~iscell(ticker) % If ticker input is wrong type\n error('Ticker input must be either a string or cell array of strings')\nelseif nargin == 1 % If N not supplied, use default\n N = 20;\nelseif ~isnumeric(N) || length(N) > 1 % If N is supplied, but is wrong type\n error('N must be a single integer value')\nend\n\n% If only one ticker given, convert to cell array\nif ~iscell(ticker)\n ticker = {ticker};\nend\n\n% Cycle through each ticker and calculate historical volatility\nvol = zeros(length(ticker), 1);\nfor i = 1:length(ticker)\n % Clear for loop variables for next iteration\n clear curr_date start_date data closing log_change stdev\n \n % Create date strings to pass to hist_stock_data function\n curr_date = datestr(now, 'ddmmyyyy'); % get current date string\n start_date = datestr(now-365, 'ddmmyyyy'); % go back 1 year\n \n % First step is to download historical stock data for the ticker\n data = hist_stock_data(start_date, curr_date, ticker{i});\n closing = data.Close; % Use only closing data\n \n % Calculate the percentage change over the past N trading days\n log_change = log(closing(2:N+1)./closing(1:N));\n \n % Get standard deviation of that change\n stdev = std(log_change);\n \n % Now normalize to annual volatility\n vol(i) = stdev*sqrt(252);\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/24811-historical-volatility/hist_vol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7732183697316011}} {"text": "% Simple 1st order RC transient response:\n% File: rctime.m\n% 9/19/02\n%\nclear;clc\n%\nK=1e3;uF=1e-6;us=1e-6;ms=1e-3;\n%\nR1=20*K;R2=40*K;C1=0.5*uF;Ein=1;E1=1;\n%\nU=1;N=1;M=1;Y=1;\n%\nA1=[1/R1+1/R2 1;1 0];\n%\nB2=[0 Ein/R1;E1 0];\n%\nP=C1;\n%\n% Template matrix equations:\n%\nV=A1\\B2;H=V(U+1:U+N,1:N+M);AB=inv(P)*H;I=eye(N);\n\nA=AB(1:N,1:N);B=AB(1:N,N+1:N+M);\nD=V(Y:Y,1:N);E=V(Y:Y,N+1:N+M);\n%\n% Display A, B, D, & E\nA\nB\nD\nE\n%\nRp=R1*R2/(R1+R2);\ndt=500*us;kmax=100;Ein=4.5; % Ein can be changed after A, B, D, E have been computed.\n%dt=100*us;kmax=500;Ein=4.5; % Try this dt after using the dt above.\nVc=zeros(1,kmax);Vo=zeros(1,kmax); % Vo(k) = Vc(k);\n%\nfor k=2:kmax\n Vc(k)=(A*Vc(k-1)+B*Ein)*dt+Vc(k-1);\n Vo(k)=D*Vc(k)+E*Ein;\n T(k)=k*dt;\n F(k)=(Ein*Rp/R1)*(1-exp(-T(k)/(Rp*C1))); % F(k) = inverse LaPlace tranform \nend\n%\nh=plot(T/ms,Vo,'k',T/ms,F,'r');\nset(h,'LineWidth',2);\ngrid on\nxlabel('Time (ms)');\nylabel('Volts');\ntitle('RC Time Response');\nlegend('Vo(k)','F(k)');\nfigure(1);\n%\n% Note that difference between F(k) and the time iteration Vo(k). This can be reduced by \n% decreasing dt with a corresponding increase in kmax to retain the same sweep time.\n% For example, if dt = 250us, kmax should be set to 200.\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/rctime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7732183679700885}} {"text": "function out = jaccoeffs(f, n, a, b)\n%JACCOEFFS Jacobi polynomial coefficients of a CHEBFUN.\n% A = JACCOEFFS(F, N, ALPHA, BETA) returns the first N+1 coefficients in the\n% Jacobi series expansion of the CHEBFUN F, so that such that F approximately\n% equals A(1) J_0(x) + ... + A(N+1) J_N(x) where J_N(x) denotes the N-th\n% Jacobi polynomial with parameters ALPHA and BETA. A is a column vector.\n%\n% If F is smooth (i.e., numel(f.funs) == 1), then A = JACCOEFFS(F, ALPHA,\n% BETA) will assume that N = length(F).\n%\n% JACCOEFFS does not support quasimatrices.\n%\n% See also CHEBCOEFFS, LEGCOEFFS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n\nif ( (numel(f(1).funs) == 1) && (nargin < 4) )\n b = a;\n a = n;\n n = length(f);\nelseif ( isempty(n) )\n n = length(f);\nend\n\nif ( numel(f) > 1 )\n out = zeros(n, numel(f));\n f = cheb2cell(f);\n for k = 1:numel(f)\n out(:,k) = jaccoeffs(f{k}, n, a, b);\n end\n return\nend\n\n%%\n% Special cases:\nif ( a == 0 && b == 0 )\n out = legcoeffs(f, n);\n return\nelseif ( a == -.5 && b == -.5 )\n out = chebcoeffs(f, n, 'kind', 1);\n nn = 0:(n-2);\n scl = repmat([1 ; cumprod((nn'+.5)./(nn'+1))], 1, size(out, 2));\n out = out./scl;\n return\nelseif ( a == .5 && b == .5 )\n out = chebcoeffs(f, n, 'kind', 2);\n nn = 0:(n-2);\n scl = repmat([1 ; cumprod((nn'+1.5)./(nn'+1))], 1, size(out, 2));\n out = (1:n)'.*out./scl;\n return\nend\n \n%% \nif ( numel(f.funs) == 1 )\n \n % Compute Jacobi coefficients of the single fun.\n out = jaccoeffs(f.funs{1}, n, a, b);\n \nelse\n\n % Jacobi-Vandermonde matrix:\n Enorm = jacpoly(0:n-1, a, b, f.domain);\n\n % Compute the projection (with correct scaling):\n out = Enorm \\ f;\n \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/@chebfun/jaccoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7732002370170353}} {"text": "function error = vennX( data, resolution )\n%\n% function error = vennX( data, resolution )\n%\n% vennX - draws an area proportional venn diagram\n%\n% Draws a venn diagram (either two or three set) using\n% circles, where the area of each region is proportional\n% to the input values.\n%\n% INPUT:\n% data - a vector of counts for each set partition\n% \n% For a two circle diagram:\n% data is a three element vector of:\n% |A| \n% |A and B| \n% |B| \n% \n% For a three circle diagram:\n% data is a seven element vector of:\n% |A|\n% |A and B|\n% |B|\n% |B and C|\n% |C|\n% |C and A|\n% |A and B and C|\n%\n% resolution - A measure of accuracy on the image,\n% typical values are within 1/100 to 1/1000 of\n% the maximum partition count. Note that smaller\n% resolutions take longer compute time.\n%\n% OUTPUT:\n% error - the difference in area of each partition \n% between the actual area and the input vector\n%\n% EXAMPLES:\n%\n% vennX( [ 106 26 257 ], .05 )\n%\n% vennX( [ 75 143 210 ], .1 )\n%\n% vennX( [ 16 3 10 6 19 8 3 ], .05 )\n%\n%\n% COMMENTS: \n% \n% The implementation is trivial, for the two circle case, two circles\n% are drawn to scale and moved closer and closer together until the \n% overlap is 'near' to the desired intersection. For the three\n% circle case, it is repeated three times, once for each pair of\n% circles. Hence the two circle case is almost exact, whereas the\n% three circle case has much more error since the area |A and B and C| \n% is derived. This means that large variations from random, especially \n% close to zero, will have larger errors, for example\n%\n% vennX( [ 20 10 20 10 20 10 0], .1 )\n%\n% as opposed to \n%\n% vennX( [ 20 10 20 10 20 10 10], .1 )\n%\n% ENHANCEMENTS\n%\n% The implementation could be sped up tremendously using a MRA\n% (multi-resolutional analysis) type algorithm. e.g. start with a\n% resolution of .5 and find the distance between the circles, then use\n% that as a seed for a resolution of .1, then .05, .01, etc.\n%\n% The error vector could be used as a measure to 'perturb' the position\n% of the third circle as to minimize the error. This could be done\n% with a simple gradient descent method. This would help the\n% exceptions described above where the distribution deviates from\n% random.\n%\n% When small mishapen areas are drawn, the text does not match up, e.g.\n% vennX( [ 15 143 210 ], .1 )\n%\n%\n% Original implementation and method by Jeremy Heil, for the Order of \n% the Red Monkey, and the Tengu\n%\n% Oct. 2004\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\n figure;\n \n if length( data ) == 3\n dist = venn2( data(1), data(2), data(3), resolution );\n error = plot_venn2( data(1), data(2), data(3), resolution, dist );\n error = data - error';\n elseif length( data ) == 7 \n %get the pairwise distance of each circle center from each other\n dist_A_B = venn2( data(1)+data(6), data(2)+data(7), data(3)+data(4), resolution );\n dist_B_C = venn2( data(3)+data(2), data(4)+data(7), data(5)+data(6), resolution );\n dist_A_C = venn2( data(1)+data(2), data(6)+data(7), data(4)+data(5), resolution );\n\n error = plot_venn3( data(1), data(2), data(3), data(4), data(5), data(6), data(7), ...\n resolution, dist_A_B, dist_B_C, dist_A_C );\n error = data - error';\n else\n 'vennX error, data vector must be of length 3 or 7'\n end\n \n %change the colormap so that the background is white \n k = colormap;\n k = [ 1 1 1; k ];\n colormap(k)\n axis off \n \nfunction error = plot_venn3( a, b, c, d, e, f, g, resolution, dist_A_B, dist_B_C, dist_A_C )\n \n r1 = sqrt( (a+b+f+g)/pi );\n r2 = sqrt( (b+c+d+g)/pi );\n r3 = sqrt( (d+e+f+g)/pi );\n \n %\n % Using a little geometry, think of the three circle's centers\n % as vertecies of a triangle.\n %\n y = ( dist_A_C^2 - dist_B_C^2 + dist_A_B^2 ) / 2 / dist_A_B;\n \n size_x = max( r1 + dist_A_B + r2, 2*r3 );\n size_y = max( r1, r2 ) + sqrt( dist_A_C^2 - y^2 ) + r3;\n\n %find the circle centers\n center1_x = r1;\n center1_y = max( r1, r2 );\n center2_x = r1 + dist_A_B;\n center2_y = center1_y; \n center3_x = r1 + y;\n center3_y = center1_y + sqrt( dist_A_C^2 - y^2 );\n \n [X,Y] = meshgrid( 0:resolution:size_x, 0:resolution:size_y );\n\n %draw the circles\n img = zeros( size(Y,1), size(Y,2) );\n \n img = img + 2 .* ( (X - center1_x).^2 + (Y - center1_y).^2 < r1^2 );\n img = img + 4 .* ( (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 );\n img = img + 6 .* ( (X - center3_x).^2 + (Y - center3_y).^2 < r3^2 );\n \n clf\n imagesc(img)\n hold on\n \n \n %add the numbers and compute the error for each partition\n error = [];\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 > r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 > r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( a ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 > r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( b ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 > r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 > r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( c ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 > r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 < r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( d ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 > r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 > r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 < r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( e ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 > r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 < r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( f ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 ), ...\n (X - center3_x).^2 + (Y - center3_y).^2 < r3^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( g ) );\n set( h, 'FontWeight', 'bold' )\n \nfunction error = plot_venn2( a, b, c, resolution, dist )\n\n r1 = sqrt( (a+b)/pi );\n r2 = sqrt( (b+c)/pi );\n \n size_x = r1 + dist + r2;\n size_y = max( 2*r1, 2*r2 );\n \n center1_x = r1;\n center1_y = size_y/2;\n center2_x = r1 + dist;\n center2_y = size_y/2;;\n \n [X,Y] = meshgrid( 0:resolution:size_x, 0:resolution:size_y );\n \n %draw the two circles and the overlap region\n img = zeros( size(Y,1), size(Y,2) );\n \n img = img + 2 .* ( (X - center1_x).^2 + (Y - center1_y).^2 < r1^2 );\n img = img + 4 .* ( (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 );\n \n imagesc(img)\n hold on\n \n %\n % We want to draw the numbers at the center of mass\n % do this by computing the average x and y coordinates of\n % the center of each partition piece.\n %\n % Compute the error for each partition as the difference\n % between the area we meant to draw and the actual area\n % that was drawn\n %\n error = [];\n tmp = and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 > r2^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( a ) );\n set( h, 'FontWeight', 'bold' )\n \n tmp = and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( b ) );\n set( h, 'FontWeight', 'bold' )\n\n tmp = and( ...\n (X - center1_x).^2 + (Y - center1_y).^2 > r1^2, ...\n (X - center2_x).^2 + (Y - center2_y).^2 < r2^2 );\n [ i,j ] = find( tmp > 0 ); \n error = [ error; sum(sum(tmp)) * resolution^2 ];\n text_x = mean(j);\n text_y = mean(i);\n h = text( text_x, text_y, num2str( c ) );\n set( h, 'FontWeight', 'bold' )\n\n \nfunction dist = venn2( a, b, c, resolution )\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %VENN2\n % dist = venn2( a, b, c, resolution )\n %\n % Computes the distance between the centers of \n % the two venn diagram circles.\n %\n % a - values of A\n % b - value of A and B\n % c - value of B\n % resolution - measure of error \n %\n % dist - the distance between the two centers\n %\n % Does this by plotting the two circles in an\n % image with the specified resolution and\n % moving the centers towards each other until\n % the area of intersection is nearest the value\n % of b\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n r1 = sqrt( (a+b)/pi );\n r2 = sqrt( (b+c)/pi );\n \n size_x = 2*r1+2*r2;\n size_y = max( 2*r1, 2*r2 );\n \n center1_x = r1;\n center1_y = size_y/2;\n center2_x = 2*r1 + r2;\n center2_y = size_y/2;;\n \n [X,Y] = meshgrid( 0:resolution:size_x, 0:resolution:size_y );\n \n for new_center = (2*r1 + r2):-resolution:r1\n \n img = zeros( size(Y,1), size(Y,2) );\n img = and( (X - center1_x).^2 + (Y - center1_y).^2 < r1^2, ...\n (X - new_center).^2 + (Y - center2_y).^2 < r2^2 );\n \n if sum(sum(img)) * resolution^2 > b\n break\n end\n end\n \n dist = new_center - center1_x;", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/utilities/vennX/vennX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7732002295591979}} {"text": "function [MOIndex] = lipschitz(u, y, maxlag, model, fig)\n% A method to determine the lag space, based on Lipschitz quotients\n%\n%% Syntax\n% [MOIndex] = lipschitz(u, y, maxlag)\n% \n%% Description\n% Given a set of corresponding inputs and outputs the function calculates\n% so called Lipschitz number for each combination of m and l where m\n% represents the number of delayed outputs, and l the number of delayed\n% inputs for the case of dynamic system: y(t) = f(y(t-1),...,y(t-l),\n% u(t-1),..., u(t-m)). \n% To small m and l result in a large Lipschitz nuber, while to large lag\n% spaces do not have greater effect on the Lipschitz nuber. In order to \n% determine the proper lag space we have to look for the knee point, where\n% Lipscitz number stops decreasing.\n% \n% Input:\n% * u ... the system input(column vector)\n% * y ... the system output(column vector)\n% * maxlag ... the max lag space to investigate\n% * model ... optional - 'arx' if we only want to investigate m = l case \n%\n% Output:\n% * MOIndex ... the maxlag by maxlag matrix containing calculated Lipscitz\n% numbers (Model order index) for each combination of m and l\n\n\n%% Signature\n% Written by Tomaz Sustar\n% Based on the algorithm by Xiangdong He and Haruhiko Asada\n\n\nif(nargin<4), model='unknown'; end;\n\nNN = length(y); % number of samples \nMOIndex = zeros(maxlag); % matrix of lipschitz's indexes\n\nfor m=1:maxlag, % number of delayed outputs \n % m,\n for l=0:maxlag, % number of delayed inputs\n \n % if we are investigating arx model srtucture only, we calculate MOIndex only when m = l\n if(strcmp(model, 'arx') && l ~= m), continue; end; \n \n lag = max(l,m); % the greater from m, l\n % Because of the lag we can construct only NN - lag input output pairs\n N = NN-lag; % number of input - output pairs. \n p = floor(0.02*N); % number of Lipschitz quotients used to determine model order index\n\n [input target] = construct([m l], u, y); % construct regressors and target\n\n\n % calculation of Lipschitz quotients\n \n \n Q = zeros(N); % initialize Q matrix for storing Lipschitz qotients \n \n for i=1:N-1, \n % for each input/output pair calculate the their Lipschitz quotients all\n % further inputs/outputs pairs. In this way all possible Lipschitz\n % quotients q(i,j) are calculated.\n \n Q(i,i+1:N)=(target(i)-target(i+1:N)).^2 ./ ...\n sum((repmat(input(i,:), N-i, 1)-input(i+1:N,:)).^2, 2); \n \n end\n\n Q_max = Q(Q~=0); % remove zeros\n Q_max = (-sort(-Q_max(:))); % sort qoutients in descending order\n Q_max = sqrt(Q_max(1:p)); % take p - largest quotients\n\n n = m+l;\n MOIndex(m,l+1)=prod(sqrt(n)*Q_max)^(1/p); % calculates order index and stores it to the matrix\n \n end % end for l\n \nend % end for m\n\n% draw some figures\n\nif(~strcmp(model, 'arx'))\n \n figure('Name', 'Model order index vs. lag space')\n surf(1:maxlag, 0:maxlag,MOIndex');\n view([-600 40]);\n set(gca, 'Zscale','log');\n set(gca, 'XTick', 1:maxlag)\n set(gca, 'XTick', 1:maxlag)\n xlabel('l - number of past outputs')\n ylabel('m - number of past inputs')\n zlabel('Model Order Index')\nend\n\nif(nargin > 4)\n figure(fig);\nelse\n figure('Name', 'Model order index vs. lag space - arx case')\nend\nsemilogy(diag(MOIndex));\nxlabel('m = l - number of past inputs and outputs');\nylabel('Model order index');\nset(gca, 'XTick', 1:maxlag);\ngrid on;\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-utilities/lipschitz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7732002204471047}} {"text": "function [G1,Gd1,Wd,Wn,Juu,Jud]=randcase(ny,nu,nd)\n% RANDCASE A random case for self-optimizing control\n%\n% [G,Gd,Wd,Wn,Juu,Jud] = randcase(ny,nu,nd) produces matrices of a random\n% case for self-optimizing control corresponding to the following\n% optimizing control problem:\n%\n% min J(y,u,d)\n% s.t. y = G*u + Gd*Wd*d + Wn*e\n%\n% with Juu = \\partial^2 J/\\partial u \\partial u\n% Jud = \\partial^2 J/\\partial u \\partial d\n%\n% These matrices can then be used to test the b3wc program.\n%\n% See also b3wc, pb3wc, b3av, pb3av\n\n% By Yi Cao at Cranfield University, 9th January 2009; 23rd February 2010.\n%\n\n% Example.\n%{\nny=30;\nnu=15;\nnd=5;\n[G,Gd,Wd,Wn,Juu,Jud] = randcase(ny,nu,nd);\n[B,sset,ops,ctime] = b3wc(G,Gd,Wd,Wn,Juu,Jud);\n[B1,sset1,ops1,ctime1] = pb3wc(G,Gd,Wd,Wn,Juu,Jud,20);\n%}\nG1=randn(ny,nu);\nGd1=rand(ny,nd);\nWd=diag(rand(nd,1));\nWn=diag(rand(ny,1));\nx=randn(nu,nu+2*ny+nd);\nJuu=diag(sum(x.*x,2));\nJud=rand(nu,nd);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25870-bidirectional-branch-and-bound-for-average-loss-minimization/randcase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7732002185125773}} {"text": "function\tXcov = embed_covariance(X,D,tau)\n% Covariance matrix in time delay embedding space\n% Xcov = embed_covariance(X,D,tau)\n% --- Input\n% X : input signal : [Xdim x Tsample x Ntrial]\n% D : time embedding dimension (integer)\n% tau : delay time in sample number (integer)\n% --- Output\n% Xcov([i,t1],[j,t2]) = Xtau([i,t1],:) * Xtau([j,t2],:)'\n% Xtau([i,t0],t) = X(i ,t + tau*(D - t0)) : [(Xdim*D) x T x Ntrial]\n% T = Tsample - tau*(D-1)\n%\n% 2008-5-22 Masa-aki Sato\n\n[N ,Tall, Nr] = size(X);\n\nTdelay = tau*(D-1);\n\nT = Tall - Tdelay;\n\n% Time delayed embedding index\nTbgn = Tdelay + 1 - (0:tau:Tdelay);\nTend = Tbgn + T - 1;\n\n% X-dim index\nIend = (1:D)*N;\nIbgn = Iend - N + 1;\n\nXcov = zeros(N*D,N*D);\n\nfor i=1:D\n for j=1:i\n \tXX = reshape(X(:,Tbgn(i):Tend(i),:), N,T*Nr) ...\n \t * reshape(X(:,Tbgn(j):Tend(j),:), N,T*Nr)';\n \t \n \tXcov(Ibgn(i):Iend(i), Ibgn(j):Iend(j)) = XX;\n \tXcov(Ibgn(j):Iend(j), Ibgn(i):Iend(i)) = XX';\n end\nend\n\nXcov = (Xcov + Xcov')/2;\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/embed_covariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7731560201246697}} {"text": "function geometry_test0803 ()\n\n%*****************************************************************************80\n%\n%% TEST0803 tests POLYGON_INRAD_DATA_2D, POLYGON_OUTRAD_DATA_2D, POLYGON_SIDE_DATA_2D;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0803\\n' );\n fprintf ( 1, ' For a REGULAR polygon in 2D:\\n' );\n fprintf ( 1, ' the inradius, outradius and side are related.\\n' );\n fprintf ( 1, ' POLYGON_INRAD_DATA_2D uses the inradius;\\n' );\n fprintf ( 1, ' POLYGON_OUTRAD_DATA_2D uses the inradius;\\n' );\n fprintf ( 1, ' POLYGON_SIDE_DATA_2D uses the inradius;\\n' );\n\n for n = 3 : 5\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of polygonal sides = %d\\n', n );\n\n side = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Assuming SIDE = %f\\n', side );\n\n [ area, radin, radout ] = polygon_side_data_2d ( n, side );\n\n fprintf ( 1, ' AREA = %f\\n', area );\n fprintf ( 1, ' RADIN = %f\\n', radin );\n fprintf ( 1, ' RADOUT = %f\\n', radout );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Assuming RADIN = %f\\n', radin );\n\n [ area, radout, side ] = polygon_inrad_data_2d ( n, radin );\n\n fprintf ( 1, ' AREA = %f\\n', area );\n fprintf ( 1, ' RADOUT = %f\\n', radout );\n fprintf ( 1, ' SIDE = %f\\n', side );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Assuming RADOUT = %f\\n', radout );\n\n [ area, radin, side ] = polygon_outrad_data_2d ( n, radout );\n\n fprintf ( 1, ' AREA = %f\\n', area );\n fprintf ( 1, ' RADIN = %f\\n', radin );\n fprintf ( 1, ' SIDE = %f\\n', side );\n \n end\n\n return\nend\n", "meta": {"author": "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_test0803.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7730853839494707}} {"text": "function quad = piecewise_linear_product_quad ( a, b, f_num, f_x, f_v, ...\n g_num, g_x, g_v, quad_num )\n\n%*****************************************************************************80\n%\n%% PIECEWISE_LINEAR_PRODUCT_QUAD: estimate piecewise linear product integral.\n%\n% Discussion:\n%\n% We are given two piecewise linear functions F(X) and G(X) and we wish\n% to estimate the value of the integral\n%\n% INTEGRAL = Integral ( A <= X <= B ) F(X) * G(X) dx\n%\n% The functions F(X) and G(X) are defined as tables of coordinates X and\n% values V. A piecewise linear function is evaluated at a point X by\n% evaluating the interpolant to the data at the endpoints of the interval\n% containing X.\n%\n% It must be the case that A <= B.\n%\n% It must be the case that the node coordinates F_X(*) and G_X(*) are\n% given in ascending order.\n%\n% It must be the case that:\n%\n% F_X(1) <= A and B <= F_X(F_NUM)\n% G_X(1) <= A and B <= G_X(G_NUM)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the limits of integration.\n%\n% Input, integer F_NUM, the number of nodes for F.\n%\n% Input, real F_X(F_NUM), the node coordinates for F.\n%\n% Input, real F_V(F_NUM), the nodal values for F.\n%\n% Input, integer G_NUM, the number of nodes for G.\n%\n% Input, real G_X(G_NUM), the node coordinates for G.\n%\n% Input, real G_V(G_NUM), the nodal values for G.\n%\n% Input, integer QUAD_NUM, the number of quadrature points.\n%\n% Output, real QUAD, an estimate for the integral of F(X) * G(X)\n% from A to B.\n%\n quad = 0.0;\n\n f_left = 1;\n g_left = 1;\n\n a2 = a;\n a2 = max ( a2, f_x(1) );\n a2 = max ( a2, g_x(1) );\n\n b2 = b;\n b2 = min ( b2, f_x(f_num) );\n b2 = min ( b2, g_x(g_num) );\n\n for i = 1 : quad_num\n\n xq = ( ( 2 * i - 1 ) * b2 ...\n + ( 2 * quad_num - 2 * i + 1 ) * a2 ) ...\n / ( 2 * quad_num );\n\n f_left = r8vec_bracket3 ( f_num, f_x, xq, f_left );\n\n fq = f_v(f_left) + ( xq - f_x(f_left) ) * ( f_v(f_left+1) - f_v(f_left) ) ...\n / ( f_x(f_left+1) - f_x(f_left) );\n\n g_left = r8vec_bracket3 ( g_num, g_x, xq, g_left );\n\n gq = g_v(g_left) + ( xq - g_x(g_left) ) * ( g_v(g_left+1) - g_v(g_left) ) ...\n / ( g_x(g_left+1) - g_x(g_left) );\n\n quad = quad + fq * gq;\n\n end\n\n quad = quad * ( b - a ) / quad_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/piecewise_linear_product_integral/piecewise_linear_product_quad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7730853800608184}} {"text": "function value = r8_fall ( x, n )\n\n%*****************************************************************************80\n%\n%% R8_FALL computes the falling factorial function [X]_N.\n%\n% Discussion:\n%\n% Note that the number of \"injections\" or 1-to-1 mappings from\n% a set of N elements to a set of M elements is [M]_N.\n%\n% The number of permutations of N objects out of M is [M]_N.\n%\n% Moreover, the Stirling numbers of the first kind can be used\n% to convert a falling factorial into a polynomial, as follows:\n%\n% [X]_N = S^0_N + S^1_N * X + S^2_N * X^2 + ... + S^N_N X^N.\n%\n% Formula:\n%\n% [X]_N = X * ( X - 1 ) * ( X - 2 ) * ... * ( X - N + 1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 09 June 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the falling factorial function.\n%\n% Input, integer N, the order of the falling factorial function.\n% If N = 0, FALL = 1, if N = 1, FALL = X. Note that if N is\n% negative, a \"rising\" factorial will be computed.\n%\n% Output, real VALUE, the value of the falling factorial function.\n%\n value = 1.0;\n\n arg = x;\n\n if ( 0 < n )\n\n for i = 1 : n\n value = value * arg;\n arg = arg - 1.0;\n end\n\n elseif ( n < 0 )\n\n for i = -1 : -1 : n\n value = value * arg;\n arg = arg + 1.0;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_fall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7730853739440894}} {"text": "function U = fracdiffdemoydelay(alpha,alphad,beta,steps)\n\n% A demo to the article:\n% I. Podlubny, A.Chechkin, T. Skovranek, YQ Chen, \n% B. M. Vinagre Jara, \"Matrix approach to discrete \n% fractional calculus II: partial fractional differential \n% equations\". http://arxiv.org/abs/0811.1355\n%\n% This function was used in the above article for the\n% numerical solution and visualization of Example 5.\n% It illustrates the ease of use of the matrix approach\n% to discretization of partial differential equations\n% with fractional derivatives with respect to the time \n% variable with delays. Delays are considered to be multiples\n% of a selected time step.\n%\n% This function solves the time-fractional diffusion-wave equation\n% containing one delayed fractional derivative:\n% 0.5*u_{t}^(\\alpha) (x,t) + 0.5*u_{t}^(\\alphad) (x,t-tau*steps)\n% = a2 * u_{xx}^{(2)}(x,t) + f(x,t)\n% under zero initial and boundary conditions\n% \n% For alpha=1, alphad=1, beta=2, steps=0, and f(x,t)=8 \n% we have the part of the test example from the book: \n% W. E. Milne. \"Numerical Solution of Differential Equations\". \n% New York: Wiley (London: Chapman & Hall), 1953.\n%\n% which is the classical heat conduction equation\n% u_{t} (x,t) = a2 * u_{xx}(x,t) + f(x,t)\n\n\n\na2=1; % coefficient from the diffusion equation\nL = 1; % length of spatial interval\n\n% Number of spatial steps + 1 is:\nm = 21; % 11, 21\n\n% Number of steps in time + 1 is:\nn =148; % 37, 148 \n\nh = L / (m-1); % spatial step\ntau = h^2 / (6*a2); % time step\n\n\n% generating the matrix for approximation\nB1 = ban(alpha,n-1,tau)'; % alpha-th order derivative with respect to time\nTD = kron(B1, eye(m)); % time derivative matrix\n\nBdelay = shift (ban(alphad,n-1+steps,tau)', steps); % delayed derivative of order alphad\nTDdelay = kron(Bdelay, eye(m)); % delayed time derivative matrix\n\nB2 = ransym(beta,m,h); % beta-th order derivative with respect to X\nSD = kron(eye(n-1), B2); % spatial derivative matrix\n\nSystemMatrix = 0.5*TD + 0.5*TDdelay- a2*SD; % matrix corresponding to discretization \n % in space and time\n \n% remove columns with '1' and 'm' from SystemMatrix\nS = eliminator (m, [1 m]);\nSK = kron(eye(n-1), S);\nSystemMatrix_without_columns_1_m = SystemMatrix * SK';\n\n% remove rows with '1' and 'm' from SystemMatrix_without_columns_1_m\nS = eliminator (m, [1 m]);\nSK = kron(eye(n-1), S);\nSystemMatrix_without_rows_columns_1_m = SK * SystemMatrix_without_columns_1_m;\n\n% Right hand side\nF = 8*ones(size(SystemMatrix_without_rows_columns_1_m,1),1);\n\n% Solution of the system\nY = SystemMatrix_without_rows_columns_1_m\\F;\n\n% Reshape solution array -- values for k-th time step \n% are in the k-th column of YS:\nYS = reshape(Y,m-2,n-1);\nYS = fliplr(YS);\n\nU = YS;\n\n% plot graph\n[rows, columns] = size(U);\nU = [ zeros(1, columns); U; zeros(1, columns)];\nU = [zeros(1,m)' U]; \n[XX,YY]=meshgrid(tau*(0:n-1),h*(0:m-1));\n\nmesh(XX,YY,U)\nxlabel('t');\nylabel('x');\nzlabel('y(x,t)');\ntitle(['\\alpha = ', num2str(alpha), ', ', ...\n ' \\gamma = ', num2str(alphad), ', ', ... \n ' \\beta = ', num2str(beta), ', ', ...\n ' k = ', num2str(steps) ])\n\nset(gca, 'xlim', [0 tau*n], 'zlim', [0 1])\nbox on\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22071-matrix-approach-to-discretization-of-odes-and-pdes-of-arbitrary-real-order/fracdiffdemoydelay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7730143971853176}} {"text": "\nfunction D = EuDist2(fea_a,fea_b,bSqrt)\n%EUDIST2 Efficiently Compute the Euclidean Distance Matrix by Exploring the\n%Matlab matrix operations.\n%\n% D = EuDist(fea_a,fea_b)\n% fea_a: nSample_a * nFeature\n% fea_b: nSample_b * nFeature\n% D: nSample_a * nSample_a\n% or nSample_a * nSample_b\n%\n% Examples:\n%\n% a = rand(500,10);\n% b = rand(1000,10);\n%\n% A = EuDist2(a); % A: 500*500\n% D = EuDist2(a,b); % D: 500*1000\n%\n% version 2.1 --November/2011\n% version 2.0 --May/2009\n% version 1.0 --November/2005\n%\n% Written by Deng Cai (dengcai AT gmail.com)\n\n\nif ~exist('bSqrt','var')\n bSqrt = 1;\nend\n\nif (~exist('fea_b','var')) || isempty(fea_b)\n aa = sum(fea_a.*fea_a,2);\n ab = fea_a*fea_a';\n \n if issparse(aa)\n aa = full(aa);\n end\n \n D = bsxfun(@plus,aa,aa') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\n D = max(D,D');\nelse\n aa = sum(fea_a.*fea_a,2);\n bb = sum(fea_b.*fea_b,2);\n ab = fea_a*fea_b';\n\n if issparse(aa)\n aa = full(aa);\n bb = full(bb);\n end\n\n D = bsxfun(@plus,aa,bb') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\nend\n", "meta": {"author": "willard-yuan", "repo": "hashing-baseline-for-image-retrieval", "sha": "822837884bdb5d44e297015d05ad081cea695a56", "save_path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval/hashing-baseline-for-image-retrieval-822837884bdb5d44e297015d05ad081cea695a56/utils/EuDist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7730143896051804}} {"text": "function [k]=fetruss(el,leng,area,c,s)\n%--------------------------------------------------------------\n% Purpose:\n% Compute stiffness matrices for the 2-d truss element\n% nodal dof {u_1 v_1 u_2 v_2}\n%\n% Synopsis:\n% [k]=fetruss(el,leng,area,c,s)\n%\n% Variable Description:\n% k - element stiffness matrix (size of 4x4) \n% el - elastic modulus ( E )\n% leng - element length\n% area - area of truss cross-section\n%----------------------------------------------------------------\n% syms X1 X2 X3\nk=(area*el/leng)*[c*c c*s -c*c -c*s;...\n c*s s*s -c*s -s*s;...\n -c*c -c*s c*c c*s;...\n -c*s -s*s c*s s*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/12401-optimize-truss-by-fsd-and-slp/Optimize Truss by FSD and SLP/fetruss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7729729740148952}} {"text": "function c=ref_rdgt(f,g,a,M)\n%REF_RDGT Reference Real DGT\n% Usage: c=ref_rdgt(f,g,a,M);\n%\n% Linear algebra version of the algorithm. Create big matrix\n% containing all the basis functions and multiply with the transpose.\n\n\nL=size(f,1);\n\nb=L/M;\nN=L/a;\n\nMhalf=ceil(M/2);\n\n\nF=zeros(L,M*N);\n\nl=(0:L-1).';\n\nfor n=0:N-1\t \n\n % Do the unmodulated coefficient.\n F(:,M*n+1)=circshift(g,n*a);\n \n for m=1:Mhalf-1\n F(:,M*n+2*m)=sqrt(2)*cos(2*pi*m*l/M).*circshift(g,n*a);\n \n F(:,M*n+2*m+1)=sqrt(2)*sin(2*pi*m*l/M).*circshift(g,n*a);\n \n end;\n\n if mod(M,2)==0\n F(:,M*(n+1))=cos(pi*l).*circshift(g,n*a);\n end;\n \nend;\n\n% dot-transpose will work because F is real.\nc=F.'*f;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_rdgt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7729663840964504}} {"text": "function [azStart,dist,azEnd,latLonWaypoints]=indirectGreatCircleProb(latLonStart,latLonEnd,r,N,algorithm,waypointType,noJumps)\n%%INDIRECTGREATCIRCLEPROB Solve the indirect great circle problem. That is,\n% given two points on a spherical Earth, find the\n% initial bearing and distance one must travel to\n% take the shortest (geodesic) path between the\n% points. Additionaly, this function can compute\n% waypoints on the path. This type of navigation is\n% sometimes referred to as \"great circle sailing.\"\n% When used for navigation, it is less accurate than\n% an ellipsoidal Earth approximation.\n%\n%INPUTS: latLonStart The 2XnumPts set of numPts initial points given in\n% latitude and longitude in radians in the format\n% [latitude;longitude] (on a reference sphere, latitude is\n% spherical elevation; longitude is spherical azimuth). If\n% all these points are the same but latLonEnd varies, then a\n% single 2X1 vector can be passed. Extra rows, if passed,\n% will be ignored.\n% latLonEnd The 2XnumPts final points given in latitude and longitude\n% in adians in the format [latitude;longitude]. If all these\n% points are the same but latLonStart varies, then a single\n% 2X1 vector can be passed.\n% r The assumed radius of the spherical Earth model. If omitted\n% or an empty matrix is passed, the default of\n% r=osculatingSpher4LatLon(latLonStart) is used.\n% N The number of waypoints, besides the initial and final\n% points on the trajectory, to produce. If omitted or an\n% empty matrix is passed, then no waypoints are generated and\n% latLonWaypoints is an empty matrix.\n% algorithm An optional parameter selecting the algorithm to use.\n% Possible values are:\n% 0 Use the algorithm of [2], which avoids issues with\n% singularities at the poles.\n% 1 (The default if omitted or an empty matrix is passed and\n% waypointType=1) Use the COFI algorithm of [1]. Latitudes\n% within 2^24*eps(pi/2) of +/-pi/2 (the North and South\n% poles) will be clipped to that bound. This avoids a\n% singularity at the poles.\n% 2 (The default if omitted or an empty matrix is passed and\n% waypointType=0) Obtain angles using Equation 5-4b of [3],\n% which is stable at the poles. Obtaincthe distance using a\n% cross product formula, which is also used in algorithm 1,\n% as discussed below.\n% waypointType An optional parameter indicating how the waypoints will\n% be spaced. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed)\n% Space the N waypoints between the start and end\n% uniformly in distance.\n% 1 Space the N waypoints between the start and end\n% uniformly in longitude. This option is only available\n% for algorithm 0. If a trajectory is meridional, then\n% only the starting and stopping points will be returned.\n%\n%OUTPUTS: azStart The 1XnumPts scalar forward azimuths at the starting\n% point in radians East of true North on the reference\n% sphere.\n% dist The 1XnumPts distances on the sphere-approximated Earth\n% between the starting and stopping points.\n% azEnd The 1XnumPts forward azimuth at the ending point in\n% radians East of true North on the reference sphere.\n% latLonWaypoints A 2X(N+2) set of waypoints on the trajectory.\n% latLonWaypoints(:,i) is the ith points as\n% [latitude;longitude] in radians. The first point is\n% latLonStart and the final points is latLonEnd, though the\n% points are made to avoid jumps of 2*pi in longitude,\n% which can mean that the last point in this can be off\n% from the provided last point by a factor of 2*pi. The\n% other points are equally spaced along the trajectory. If\n% the trajectory is meridional and waypointType=1, then\n% only the starting and ending points will be returned.\n%\n%Great circles are geodesics on a sphere. A geodesic path between two\n%points on a sphere is much simpler to determine as compared to an\n%ellipsoid (which is what one gets using the indirectGeodeticProb\n%function). For the spherical model, the latitude is taken as the elevation\n%and the longitude as the azimuth on the sphere (we assume coordinate\n%system 0 in the spher2Cart function). The latitudes and longitudes\n%returned as waypoints by this function can be used to piece together an\n%_approximate_ geodesic trajectory on the reference ellipsoid. One can\n%obtain headings and distances between the reference points using rhumb\n%lines.\n%\n%The azimuthal values returned when one of the points is at the pole\n%depends on the longitude value given for the points. The getENUAxes\n%function can return East-North-Up axes anywhere on the globe (for a\n%sphere, the ellipsoidal flattening is 0). When given a pole, the result is\n%the equivalent one would get by taking a point with the same latitude and\n%with the latitude magnitude a tiny epsilon less than pi/2.\n%\n%The implementation of the COFI algorithm of [1] has been modified so that\n%the angular difference D is obtained using the angBetweenVecs given F and\n%T rather than the technique derived from the dot product relation starting\n%in Equation 13 in [1]. This is because the cross product relation used in\n%angBetweenVecs is more accurate. This is also used for the distance in\n%algorithm 2. Minor changes had to be made to algorithm 1 to deal with\n%trajectories going West, since the derivation in [1] is for East-bound\n%trajectories.\n%\n%EXAMPLE 1:\n%This is example 2 from [1]. It is a trajectory that crosses the\n%international date and and goes from the Northern hemisphere to the\n%southern hemisphere. We also compute the reverse path and show that the\n%start and end azimuth angles produced in each direction are consistent\n%with each other (when the same Earth radius is used eahc time). We then\n%plot the trajectory on an image of the spherical Earth. For better\n%plotting, the radius of the Earth has been normalized to 1.\n% N=500;\n% latStart=degMinSec2Rad(37,47.5);\n% lonStart=degMinSec2Rad(-122,-27.8);\n% latEnd=degMinSec2Rad(-33,-51.7);\n% lonEnd=degMinSec2Rad(151,12.7);\n% \n% latLonStart=[latStart;lonStart];\n% latLonEnd=[latEnd;lonEnd];\n% \n% [azStartFwd,distFwd,azEndFwd,latLonWayPoints]=indirectGreatCircleProb(latLonStart,latLonEnd,1,N);\n% [azStartRev,distRev,azEndRev,latLonWayPointsRev]=indirectGreatCircleProb(latLonEnd,latLonStart,1,N);\n% \n% %All four of these should be approximately zero if the algorithm works\n% %forwards and backwards:\n% distFwd-distRev\n% wrapRange(azStartFwd-wrapRange(azEndRev+pi,-pi,pi),-pi,pi)\n% wrapRange(azStartRev-wrapRange(azEndFwd+pi,-pi,pi),-pi,pi)\n% max(max(abs(wrapRange(latLonWayPoints-fliplr(latLonWayPointsRev),-pi,pi))))\n% \n% xStartCart=ellips2Cart([latLonStart;0],1,0);\n% xEndCart=ellips2Cart([latLonEnd;0],1,0);\n% %Give the points a nonzero elevation so the lines are easier to see.\n% pathPoints=ellips2Cart([latLonWayPoints;0.02*ones(1,N+2)],1,0);\n% \n% figure(1)\n% clf\n% hold on\n% plotMapOnEllipsoid([],1,0);\n% scatter3(xStartCart(1),xStartCart(2),xStartCart(3),100,'filled')\n% scatter3(xEndCart(1),xEndCart(2),xEndCart(3),100,'filled')\n% plot3(pathPoints(1,:),pathPoints(2,:),pathPoints(3,:),'-r','linewidth',4)\n% view([-75.368365161957513,3.494544111878512])\n%\n%EXAMPLE 2:\n%This is the same as example 1, except one point is given at the North\n%pole.\n% N=500;\n% latStart=pi/2;%North pole.\n% lonStart=degMinSec2Rad(-122,-27.8);\n% latEnd=degMinSec2Rad(-33,-51.7);\n% lonEnd=degMinSec2Rad(151,12.7);\n% \n% latLonStart=[latStart;lonStart];\n% latLonEnd=[latEnd;lonEnd];\n% \n% [azStartFwd,distFwd,azEndFwd,latLonWayPoints]=indirectGreatCircleProb(latLonStart,latLonEnd,1,N);\n% [azStartRev,distRev,azEndRev,latLonWayPointsRev]=indirectGreatCircleProb(latLonEnd,latLonStart,1,N);\n% \n% %All four of these should be approximately zero if the algorithm works\n% %forwards and backwards:\n% distFwd-distRev\n% wrapRange(azStartFwd-wrapRange(azEndRev+pi,-pi,pi),-pi,pi)\n% wrapRange(azStartRev-wrapRange(azEndFwd+pi,-pi,pi),-pi,pi)\n% max(max(abs(wrapRange(latLonWayPoints-fliplr(latLonWayPointsRev),-pi,pi))))\n% \n% xStartCart=ellips2Cart([latLonStart;0],1,0);\n% xEndCart=ellips2Cart([latLonEnd;0],1,0);\n% pathPoints=ellips2Cart([latLonWayPoints;0.02*ones(1,N+2)],1,0);\n% \n% figure(1)\n% clf\n% hold on\n% plotMapOnEllipsoid([],1,0);\n% scatter3(xStartCart(1),xStartCart(2),xStartCart(3),100,'filled')\n% scatter3(xEndCart(1),xEndCart(2),xEndCart(3),100,'filled')\n% plot3(pathPoints(1,:),pathPoints(2,:),pathPoints(3,:),'-r','linewidth',4)\n%\n%REFERENCES:\n%[1] C.-L. Chen, P.-F. Liu, and W.-T. Gong, \"A simple approach to great\n% circle sailing: The COFI method,\" The Journal of Navigation, vol. 67,\n% no. 3, pp. 403-418, May 2014.\n%[2] D. F. Crouse, \"Singularity-free great-circle sailing,\" Naval Research\n% Laboratory, Washington, DC, Tech. Rep. NRL/5340/MR-2021/4, 26\n% Jul. 2021.\n%[3] J. P. Snyder, \"Map projections-a working manual,\" U.S. Geological\n% Survey, Tech. Rep. 1395, 1987.\n%\n%August 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<7||isempty(noJumps))\n noJumps=true;\nend\n\nif(nargin<6||isempty(waypointType))\n waypointType=0;\nend\n\nif(nargin<5||isempty(algorithm))\n if(waypointType==1)\n algorithm=1;\n else\n algorithm=2;\n end\nend\n\nif(nargin<4)\n N=[];%Generate no waypoints.\nend\n\nif(nargin<3||isempty(r))\n r=osculatingSpher4LatLon(latLonStart);\nend\n\nif(nargout<3)\n N=[];%Do not generate waypoints.\nend\n\nnumPts1=size(latLonStart,2);\nnumPts2=size(latLonEnd,2);\nnumPts=max(numPts1,numPts2);\n\nif(numPts1>numPts2)\n latLonEnd=repmat(latLonEnd,[1,numPts]);\nelseif(numPts2>numPts1)\n latLonStart=repmat(latLonStart,[1,numPts]);\nend\n\nazStart=zeros(1,numPts);\ndist=zeros(1,numPts);\nazEnd=zeros(1,numPts);\nif(~isempty(N))\n latLonWaypoints=zeros(2,N+2,numPts);\nelse\n latLonWaypoints=[];\nend\n\nswitch(algorithm)\n case 0\n if(waypointType~=0)\n error('This algorithm only supports waypointType=0.');\n end\n \n for k=1:numPts\n [azStart(k),dist(k),azEnd(k),latLonWaypointsCur]=indirectGreatCircleProbCrouse(latLonStart(1:2,k),latLonEnd(1:2,k),r,N);\n if(~isempty(N))\n latLonWaypoints(:,:,k)=latLonWaypointsCur;\n end\n end\n case 1\n for k=1:numPts\n [azStart(k),dist(k),azEnd(k),latLonWaypointsCur]=indirectGreatCircleProbChen(latLonStart(1:2,k),latLonEnd(1:2,k),r,N,waypointType);\n if(~isempty(N))\n latLonWaypoints(:,:,k)=latLonWaypointsCur;\n end\n end\n case 2\n for k=1:numPts\n [azStart(k),dist(k),azEnd(k),latLonWaypointsCur]=indirectGreatCircleProbSnyder(latLonStart(1:2,k),latLonEnd(1:2,k),r,N);\n if(~isempty(N))\n latLonWaypoints(:,:,k)=latLonWaypointsCur;\n end\n end\n otherwise\n error('Unknown algorithm chosen.')\nend\n\nif(~isempty(N)&&noJumps&&N>0)\n cumOffset=0;\n for k=1:numPts\n for j=2:(N+2)\n diffVal=latLonWaypoints(2,j)+cumOffset-latLonWaypoints(2,j-1);\n if(diffVal>pi)\n cumOffset=cumOffset-2*pi;\n elseif(diffVal<-pi)\n cumOffset=cumOffset+2*pi;\n end\n latLonWaypoints(2,j)=latLonWaypoints(2,j)+cumOffset;\n end\n end\nend\nend\n\nfunction [azStart,dist,azEnd,latLonWayPoints]=indirectGreatCircleProbChen(latLonStart,latLonEnd,r,N,waypointType)\n%%INDIRECTGREATCIRCLEPROBCHEN Solve the indirect great circle problem using\n% the algorithm of [1], except the angular difference D\n% is obtained using the angBetweenVecs given F and T.\n%\n%Starting latitude values within 2^24*eps(pi/2); of the pole will be\n%clipped to be 2^24*eps(pi/2); away from the pole. This reduces problems\n%with singularities at the poles at the cost of a loss of accuracy compared\n%to elsewhere on the globe.\n%\n%REFERENCES:\n%[1] C.-L. Chen, P.-F. Liu, and W.-T. Gong, \"A simple approach to great\n% circle sailing: The COFI method,\" The Journal of Navigation, vol. 67,\n% no. 3, pp. 403-418, May 2014.\n%\n%August 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Latitude at the start.\nLF=latLonStart(1);\n%Deal with locations very close to the North or South pole by offsetting\n%them just enough to avoid finite precision issues.\nepsVal=2^24*eps(pi/2);\nif(abs(LF-pi/2) 1.9\n % % d = pi - dist(x, -y);\n % % end\n % It is rarely necessary to compute the distance between\n % almost-antipodal points with full accuracy in Manopt, hence we\n % favor a simpler code.\n\n end\n\n M.typicaldist = @() pi;\n\n M.proj = @(x, d) d - x*(x(:)'*d(:));\n\n M.tangent = M.proj;\n\n M.tangent2ambient_is_identity = true;\n M.tangent2ambient = @(X, U) U;\n\n % For Riemannian submanifolds, converting a Euclidean gradient into a\n % Riemannian gradient amounts to an orthogonal projection.\n M.egrad2rgrad = M.proj;\n\n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(x, egrad, ehess, u)\n rhess = M.proj(x, ehess - (x(:)'*egrad(:))*u);\n end\n\n M.exp = @exponential;\n\n M.retr = @retraction;\n M.invretr = @inverse_retraction;\n\n M.log = @logarithm;\n function v = logarithm(x1, x2)\n v = M.proj(x1, x2 - x1);\n di = M.dist(x1, x2);\n % If the two points are \"far apart\", correct the norm.\n if di > 1e-6\n nv = norm(v, 'fro');\n v = v * (di / nv);\n end\n end\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n\n M.rand = @() random(n, m, array_type);\n\n M.randvec = @(x) randomvec(n, m, x, array_type);\n\n M.zerovec = @(x) zeros(n, m, array_type);\n\n M.lincomb = @matrixlincomb;\n\n M.transp = @(x1, x2, d) M.proj(x2, d);\n\n % Isometric vector transport of d from the tangent space at x1 to x2.\n % This is actually a parallel vector transport, see Ch. 5 in\n % http://epubs.siam.org/doi/pdf/10.1137/16M1069298\n % \"A Riemannian Gradient Sampling Algorithm for Nonsmooth Optimization\n % on Manifolds\", by Hosseini and Uschmajew, SIOPT 2017\n M.isotransp = @(x1, x2, d) isometricTransp(x1, x2, d);\n function Td = isometricTransp(x1, x2, d)\n v = logarithm(x1, x2);\n dist_x1x2 = norm(v, 'fro');\n if dist_x1x2 > 0\n u = v / dist_x1x2;\n utd = u(:)'*d(:);\n Td = d + (cos(dist_x1x2)-1)*utd*u ...\n - sin(dist_x1x2) *utd*x1;\n else\n % x1 == x2, so the transport is identity\n Td = d;\n end\n end\n\n M.pairmean = @pairmean;\n function y = pairmean(x1, x2)\n y = x1+x2;\n y = y / norm(y, 'fro');\n end\n\n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [n, m]);\n M.vecmatareisometries = @() true;\n\n\n % Automatically convert a number of tools to support GPU.\n if gpuflag\n M = factorygpuhelper(M);\n end\n\n\nend\n\n% Exponential on the sphere\nfunction y = exponential(x, d, t)\n \n if nargin == 2\n % t = 1\n td = d;\n else\n td = t*d;\n end\n \n nrm_td = norm(td, 'fro');\n y = x*cos(nrm_td) + td*sinxoverx(nrm_td);\n \nend\n\n% Retraction on the sphere\nfunction y = retraction(x, d, t)\n\n if nargin == 2\n % t = 1;\n td = d;\n else\n td = t*d;\n end\n\n y = x + td;\n y = y / norm(y, 'fro');\n\nend\n\n% Given x and y two points on the manifold, if there exists a tangent\n% vector d at x such that Retr_x(d) = y, this function returns d.\nfunction d = inverse_retraction(x, y)\n\n % Since\n % x + d = y*||x + d||\n % and x'd = 0, multiply the above by x' on the left:\n % 1 + 0 = x'y * ||x + d||\n % Then solve for d:\n\n d = y/(x(:)'*y(:)) - x;\n\nend\n\n% Uniform random sampling on the sphere.\nfunction x = random(n, m, array_type)\n\n x = randn(n, m, array_type);\n x = x / norm(x, 'fro');\n\nend\n\n% Random normalized tangent vector at x.\nfunction d = randomvec(n, m, x, array_type)\n\n d = randn(n, m, array_type);\n d = d - x*(x(:)'*d(:));\n d = d / norm(d, 'fro');\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/sphere/spherefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7728188441064995}} {"text": "function value = p10_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P10_F evaluates the integrand for problem 10.\n%\n% Dimension:\n%\n% DIM_NUM arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integrand:\n%\n% sum ( abs ( x(1:dim_num) - 0.5 ) )\n%\n% Exact Integral:\n%\n% DIM_NUM / 4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Thomas Patterson,\n% [Integral #4],\n% On the Construction of a Practical Ermakov-Zolotukhin \n% Multiple Integrator,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast, Graeme Fairweather,\n% D. Reidel, 1987, pages 269-290,\n% LC: QA299.3.N38.\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 DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n value(point) = sum ( abs ( x(1:dim_num,point) - 0.5 ) );\n end\n\n p10_i4 ( 'I', '#', point_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p10_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.7728188326631047}} {"text": "%GSP_DEMO_GRAPH_TV Reconstruction of missing sample on a graph using TV\n%\n% In this demo, we try to reconstruct missing sample of a piece-wise\n% smooth signal on a graph. To do so, we will minimize the well-known TV\n% norm defined on the graph.\n%\n% For this example, you need the unlocbox. You can download it here:\n% http://unlocbox.sourceforge.net/download\n%\n% We express the recovery problem as a convex optimization problem of the\n% following form:\n%\n% .. argmin ||grad(x)||_1 s. t. ||Mx-b||_2 < epsilon\n%\n% .. math:: arg \\min_x \\|\\nabla(x)\\|_1 \\text{ s. t. } \\|Mx-b\\|_2 \\leq \\epsilon\n%\n% Where b represents the known measurements, M is an operator\n% representing the mask and $\\epsilon$ is the radius of the l2 ball.\n%\n% We set\n%\n% * $f_1(x)=||\\nabla x ||_1$\n% We define the prox of $f_1$ as:\n%\n% .. prox_{f1,gamma} (z) = argmin_{x} 1/2 ||x-z||_2^2 + gamma ||grad(z)||_1\n%\n% .. math:: prox_{f1,\\gamma} (z) = arg \\min_{x} \\frac{1}{2} \\|x-z\\|_2^2 + \\gamma \\| \\nabla z \\|_1\n%\n% * $f_2$ is the indicator function of the set S define by $||Mx-b||_2 < \\epsilon$\n% We define the prox of $f_2$ as\n%\n% .. prox_{f2,gamma} (z) = argmin_{x} 1/2 ||x-z||_2^2 + gamma i_S( x ),\n%\n% .. math:: prox_{f2,\\gamma} (z) = arg \\min_{x} \\frac{1}{2} \\|x-z\\|_2^2 + i_S(x) ,\n%\n% with $i_S(x)$ is zero if x is in the set S and infinity otherwise.\n% This previous problem has an identical solution as:\n%\n% .. argmin_{z} ||x - z||_2^2 s.t. ||b - M z||_2 < epsilon\n%\n% .. math:: arg \\min_{z} \\|x - z\\|_2^2 \\hspace{1cm} such \\hspace{0.25cm} that \\hspace{1cm} \\|Mz-b\\|_2 \\leq \\epsilon\n%\n% It is simply a projection on the B2-ball.\n%\n% Results\n% -------\n%\n% .. figure::\n%\n% Original signal on graph\n%\n% This figure shows the original signal on graph.\n%\n% .. figure::\n%\n% Depleted signal on graph\n%\n% This figure shows the signal on graph after the application of the\n% mask and addition of noise. Half of the vertices are set to 0.\n%\n% .. figure::\n%\n% Reconstructed signal on graph usign TV\n%\n% This figure shows the reconstructed signal thanks to the algorithm.\n%\n% Comparison with Tikhonov regularization\n% ---------------------------------------\n%\n% We can also use the Tikhonov regularizer that will promote smoothness.\n% In this case, we solve:\n%\n% .. argmin ||grad(x)||_2^2 s. t. ||Mx-b||_2 < epsilon\n%\n% .. math:: arg \\min_x \\tau \\|\\nabla(x)\\|_2^2 \\text{ s. t. } \\|Mx-b\\|_2 \\leq \\epsilon\n%\n% The result is presented in the following figure:\n%\n% .. figure::\n%\n% Reconstructed signal on graph using Tikhonov\n%\n% This figure shows the reconstructed signal thanks to the algorithm.\n%\n\n\n% Author: Nathanael Perraudin\n% Date: 4th March 2014\n\n\n%% Initialisation\nclear;\nclose all;\n% Load toolbox\ninit_unlocbox();\n\n%% Important parameters\n% size of the graph for the demo\nN = 250;\n% probability of having a label on a vertex.\np = 0.1;\nverbose = 1; % verbosity level\nsigma = 0.0;\n\n\n\n\n\n%% Create a graph\n% paramgraph.distribute = 1;\n% G = gsp_sensor(N, paramgraph);\nG = gsp_sensor(N);\nG = gsp_community(N);\n\n% for a path with irregular weights and distances\n% G = gsp_path(N);\n% G = gsp_update_coordinates(G, G.coords + [rand(G.N, 1), zeros(G.N, 1)]);\n% G = gsp_update_weights(G, G.W .* exp(-gsp_distanz(G.coords').^2));\n\nG = gsp_adj2vec(G);\nG = gsp_estimate_lmax(G);\nG = gsp_compute_fourier_basis(G);\n\n% x_0 = (1 + sign(G.U(:,4))) / 2;\nx_0 = round((1 + sign(G.U(:,2))) * 2+(1 + sign(G.U(:,3))) +(1 + sign(G.U(:,4))) / 2);\n% x_0 = round(linspace(0, 5, N))';\nx_0 = G.info.node_com;\n\n%% Set the labels\n% create the mask\n% ind_obs = boolean(full(sparse(1:4:G.N, 1, 1, G.N, 1)));\nind_obs = rand(G.N, 1) < p;\nind_unobs = not(ind_obs);\n\n%applying the Mask to the data\nx_obs = ind_obs.*(x_0+sigma*randn(G.N,1));\n\n\n%% Method 1: Graph TV\n% setting different parameter for the simulation\nparam_solver.verbose = verbose; % display parameter\nparam_solver.tol = 1e-5;\nparam_solver.maxit = 4000;\n\ntic;\nsol_tv = gsp_regression_tv(G, ind_obs, x_obs, 0, param_solver);\ntoc\n\n%% Method 2: Tikhonov\ntic;\nG2 = G;\nG2.L = G.L^3;\n%sol_tik = gsp_regression_tik(G, ind_obs, x_obs, 0, param_solver);\nsol_tik = gsp_regression_tik(G2, ind_obs, x_obs, 0, param_solver);\ntoc\n\n%% Method 3: My idea: inpaint using graph TV on one variable that is l-2\n%% away from another one that is smooth\n%%\n% x, y are primal variables: z is the dual\n% min_x,y,z ||grad(x_all)||_1 + a/2||x-y||^2 + b/2 ||grad(y_all)||^2\n%\n% grad(x_all) = grad([x;x_obs]) = A*x + A_obs * x_obs = A*x - b\n%\n% only rows of gradient corresponding to unknown values used:\n% min_x,y,z ||Ax - b||_1 + a/2||x-y||^2 + b/2 ||Ay - b||^2\n% Get rid of operator A by using dual variable:\n% min_x,y,z ||z - b||_1 + a/2||x-y||^2 + b/2 ||Ay - b||^2\n% Think of all primal variables as one vector w = [x;y] containing ONLY\n% the elements on the unlabeled nodes\n\n% choose parameters for solving the problem:\nalpha = .1;\nbeta = 1;\n\n% compute the Diff matrix of the graph\nG = gsp_adj2vec(G);\n\n% operators based on the Diff\nA_obs = G.Diff(:, ind_obs);\nA_unobs = G.Diff(:, not(ind_obs));\nn_unobs = nnz(not(ind_obs));\nzeros_x = zeros(n_unobs, 1);\nzeros_y = zeros_x;\n\n% graph TV term is the l-1 on the dual:\nb = - A_obs * x_obs(ind_obs);\nf1_params.y = b;\nf1.eval = @(z) norm(z - b, 1);\nf1.prox = @(z, gamma) prox_l1(z, gamma, f1_params);\nf1.L = @(w) A_unobs * w(1:n_unobs);\nf1.Lt = @(z) [A_unobs' * z; zeros_y];\nf1.norm_L = normest(A_unobs);\n%f1.norm_L = sqrt(G.lmax);\n\n% use prox for the second function\n% w = [x;y], w0 = [x0;y0]\n% prox_g(x) = ((1+g)x + gy)/(1+2g)\nf2.prox = @(w, gamma) [ ((1+alpha*gamma) * w(1:n_unobs) + ...\n alpha*gamma * w(n_unobs+1:end))/(1+2*alpha*gamma);...\n (alpha*gamma * w(1:n_unobs) + ...\n (1+alpha*gamma) * w(n_unobs+1:end))/(1+2*alpha*gamma)];\nf2.eval = @(w) alpha/2 * norm(w(1:n_unobs) - w(n_unobs+1:end))^2;\n\n% use gradient for the last function\nAtA = A_unobs' * A_unobs;\nAtb = A_unobs' * b;\nf3.grad = @(w) [zeros_x; beta * (AtA*w(n_unobs+1:end) - Atb)];\nf3.eval = @(w) beta/2 * norm(A_unobs * w(n_unobs+1:end) - b)^2;\nf3.beta = beta * normest(AtA);\n\n%% solve the problem\nparam_solver.verbose = 1;\nparam_solver.algo = 'FBF_PRIMAL_DUAL';\nparam_solver.normalized_timestep = 0.99;\ntic;\n[sol_mine, info_sol] = solvep([sol_tv(not(ind_obs)); sol_tik(not(ind_obs))], {f1,f2,f3}, param_solver);\ntoc\n\nsol_mine_x = x_obs;\nsol_mine_x(ind_unobs) = sol_mine(1:n_unobs);\nsol_mine_y = x_obs;\nsol_mine_y(ind_unobs) = sol_mine(n_unobs+1:end);\n\n%% Method 4: L-1 of Lx ||Lx||_1\ntic;\nparam_solver = rmfield(param_solver, 'algo');\nsol_Lx_l1 = gsp_regression_Lx_l1(G, ind_obs, x_obs, 0, param_solver);\ntoc\n\n\n%% Compute the errors\nans_tv = round(sol_tv);\nans_tik = round(sol_tik);\nans_mine = round(sol_mine_x);\nans_Lxl1 = round(sol_Lx_l1);\n\nerr_tv = nnz(ans_tv ~= x_0) / G.N\nerr_tik = nnz(ans_tik ~= x_0) / G.N\nerr_mine = nnz(ans_mine ~= x_0) / G.N\nerr_Lxl1 = nnz(ans_Lxl1 ~= x_0) / G.N\n\n%% Print the result\nparamplot.show_edges = 1;\nval_lims = lin_map([-.05, 1.05], [min([x_0; sol_tv; sol_tik]), max([x_0; sol_tv; sol_tik])], [0, 1]);\n\n\n%% Plot the original graph\nif not(strcmp(G.type, 'path'))\n figure(1)\n paramplot.vertex_highlight = ind_obs;\n gsp_plot_signal(G, x_0, paramplot)\n caxis(val_lims);\n title('Original signal: highlighted known values')\n \n \n % % Let show depleted graph\n % figure(2)\n % gsp_plot_signal(G,depleted_graph_value,paramplot)\n % caxis([-1 1])\n % title('Measurement')\n % Let show the reconstructed graph\n figure(3)\n paramplot.vertex_highlight = (ans_tv ~= x_0);\n gsp_plot_signal(G, ans_tv, paramplot)\n caxis(val_lims)\n title('TV solution: highlighted mistakes')\n \n % Let show the reconstructed graph\n figure(4)\n paramplot.vertex_highlight = (ans_tik ~= x_0);\n gsp_plot_signal(G, ans_tik, paramplot)\n caxis(val_lims)\n title('Tikhonov solution: highlighted mistakes')\n \n % Let show the reconstructed graph\n figure(5)\n paramplot.vertex_highlight = (ans_mine ~= x_0);\n gsp_plot_signal(G, ans_mine, paramplot)\n caxis(val_lims)\n title('My solution: highlighted mistakes')\n \n % Let show the reconstructed graph\n figure(6)\n paramplot.vertex_highlight = (ans_Lxl1 ~= x_0);\n gsp_plot_signal(G, ans_Lxl1, paramplot)\n caxis(val_lims)\n title('||Lx||_1 solution: highlighted mistakes')\n \n %%\nelse strcmp(G.type, 'path')\n figure; \n plot(G.coords(:, 1), sol_tv)\n hold on;\n plot(G.coords(:, 1), sol_tik)\n plot(G.coords(:, 1), x_0);\n plot(G.coords(:, 1), sol_Lx_l1)\n plot(G.coords(ind_obs, 1), x_0(ind_obs), 'o');\n legend('TV', 'Tikhonov', '||Lx||_1', 'true');\nend\n\n\nfigure; plot(sol_mine_x)\nhold on; plot(sol_mine_y)\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/demos/gsp_demo_tv_inpainting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7727946286829902}} {"text": "function p = normal2(mu, Sigma, dom)\n%NORMAL2 Bivariate normal distribution.\n% NORMAL2(MU, SIGMA, DOMAIN) returns the joint probability density for two\n% variables whose means are in the vector MU and whose covariance is the 2x2\n% positive definite matrix SIGMA. The result is a chebfun2 defined on the\n% (finite) domain DOMAIN.\n%\n% If DOMAIN is not supplied, the domain is taken to be large enough to make\n% the density essentially zero at the boundary.\n%\n% Example:\n% p = cheb.normal2([1,0], [1 1;1 5]);\n% surf(p)\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( any(eig(Sigma) < 0) || norm(Sigma - Sigma') > 0 )\n error('CHEB:NORMAL2:covariance:nonSymPosDef', ...\n 'Covariance matrix must be symmetric positive definite.')\nend\n\nif nargin < 3\n sig = svd(Sigma);\n dom = [ mu(1)+4*[-sig(1) sig(1)], mu(2)+4*[-sig(1) sig(1)] ];\nend\n\nx = chebfun2(@(x,y) x,dom);\ny = chebfun2(@(x,y) y,dom);\ninvSig = inv(Sigma);\nx = x - mu(1);\ny = y - mu(2);\nz = invSig(1,1)*x.^2 + (invSig(1,2)+invSig(2,1))*x.*y + invSig(2,2)*y.^2;\nconst = 2*pi*sqrt(det(Sigma));\n\np = exp(-z/2)/const;\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/normal2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7727865398594065}} {"text": "function [tscr] = triscr2(pp,tt)\n%TRISCR2 calc. area-len. ratios for triangles in a 2-simplex\n%triangulation in the two-dimensional plane.\n% [SCR2] = TRISCR2(VERT,TRIA) returns the area-len. ratios\n% where SCR2 is a T-by-1 vector, VERT is a V-by-2 array of\n% XY coordinates, and TRIA is a T-by-3 array of\n% vertex indexing, where each row defines a triangle, such\n% that VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(\n% TRIA(II,3),:) are the coordinates of the II-TH triangle.\n%\n% See also TRIAREA, TRIANG2, TRIBAL2\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 17/01/2017\n\n%--------------------------- compute signed area-len. ratios\n scal = 4.0 * sqrt(3.0) / 3.0;\n\n area = triarea(pp,tt) ; % also error checks!\n\n lrms = sum((pp(tt(:,2),:) ...\n - pp(tt(:,1),:)).^2,2) ...\n + sum((pp(tt(:,3),:) ...\n - pp(tt(:,2),:)).^2,2) ...\n + sum((pp(tt(:,3),:) ...\n - pp(tt(:,1),:)).^2,2) ;\n\n lrms =(lrms / 3.0) .^ 1.00 ;\n\n tscr = scal * area ./ lrms ;\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-cost/triscr2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7727549871354553}} {"text": "function L = gaussianNoiseLogLikelihood(noise, mu, varsigma, y)\n\n% GAUSSIANNOISELOGLIKELIHOOD Log likelihood of the data under the GAUSSIAN noise model.\n% FORMAT\n% DESC returns the log likelihood of a data set under the Gaussian noise model.\n% ARG noise : the noise structure for which the log likelihood is required.\n% ARG mu : input mean locations for the log likelihood.\n% ARG varSigma : input variance locations for the log likelihood.\n% ARG y : target locations for the log likelihood.\n%\n% SEEALSO : gaussianNoiseParamInit, gaussianNoiseLikelihood, noiseLogLikelihood\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n% NOISE\n\n\nN = size(mu, 1);\nD = size(mu, 2);\nvarsigma = varsigma + noise.sigma2;\nfor i = 1:D\n mu(:, i) = mu(:, i) + noise.bias(i);\nend\narg = (y - mu);\narg = arg.*arg./varsigma;\n\nL = - 0.5*sum(sum(log(varsigma))) ...\n - 0.5*sum(sum(arg)) ...\n - 0.5*N*D*log(2*pi);\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/gaussianNoiseLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7727549791910712}} {"text": "function [sigma,shrinkage]=cov1para(x,shrink)\n\n% function sigma=cov1para(x)\n% x (t*n): t iid observations on n random variables\n% sigma (n*n): invertible covariance matrix estimator\n%\n% Shrinks towards one-parameter matrix:\n% all variances are the same\n% all covariances are zero\n% if shrink is specified, then this value is used for shrinkage\n\n% This version: 04/2014\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is released under the BSD 2-clause license.\n\n% Copyright (c) 2014, Olivier Ledoit and Michael Wolf \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% 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\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 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, 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\n\n% de-mean returns\n[t,n]=size(x);\nmeanx=mean(x);\nx=x-meanx(ones(t,1),:);\n%x = bsxfun(@minus,x,meanx);\n\n% compute sample covariance matrix\nsample=(1/t).*(x'*x);\n\n% compute prior\n%meanvar=mean(diag(sample));\nmeanvar = trace(sample)/n;\nprior=meanvar*eye(n);\n\n%if (nargin < 2 | shrink == -1) % compute shrinkage parameters\n \n % what we call p \n y=x.^2;\n phiMat=y'*y/t-sample.^2;\n phi=sum(sum(phiMat));\n \n % what we call r is not needed for this shrinkage target\n \n % what we call c\n %gamma=norm(sample-prior,'fro')^2;\n gamma = sample-prior;\n gamma = sum(gamma(:).^2);\n\n % compute shrinkage constant\n kappa=phi/gamma;\n shrinkage=max(0,min(1,kappa/t));\n \n%else % use specified number\n% shrinkage=shrink;\n%end\n\n% compute shrinkage estimator\nsigma=shrinkage*prior+(1-shrinkage)*sample;\n\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/external/scilearnlab/private/cov1para.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8740772466456688, "lm_q1q2_score": 0.7727186213151874}} {"text": "function [A,b,x] = spikes(n,t_max)\n%SPIKES Test problem with a \"spiky\" solution.\n%\n% [A,b,x] = spikes(n,t_max)\n%\n% Artificially generated discrete ill-posed problem.\n%\n% The solution x consists of a unit step at t = .5, and a pulse train\n% of spikes of decrasing magnitude at t = .5, 1.5, 2.5, ...\n%\n% The parameter t_max is optional; its default value is 5.\n% It controls the length of the pulse train.\n\n% Per Christian Hansen, IMM, 04/21/97.\n\n% Initialization.\nif (nargin == 1), t_max = 5; end\ndel = t_max/n;\n\n% Compute the matrix A.\n[t,sigma] = meshgrid(del:del:t_max,del:del:t_max);\nA = sigma./(2*sqrt(pi*t.^3)).*exp(-(sigma.^2)./(4*t));\n\n% Compute the right-hand side b and the solution x.\nif (nargout > 1)\n heights = 2*ones(t_max,1); heights(1) = 25;\n heights(2) = 9; heights(3) = 5; heights(4) = 4; heights(5) = 3;\n x = zeros(n,1); n_h = 1;\n peak = 0.5/t_max; peak_dist = 1/t_max;\n if (peak < 1)\n n_peak = round(peak*n); x(n_peak) = heights(n_h);\n x(n_peak+1:n) = ones(n-n_peak,1);\n peak = peak + peak_dist; n_h = n_h + 1;\n end\n while (peak < 1)\n x(round(peak*n)) = heights(n_h);\n peak = peak + peak_dist; n_h = n_h + 1;\n end\n b = A*x;\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/spikes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7726946182478521}} {"text": "function a = covar2 ( m, n, b, a )\n\n%*****************************************************************************80\n%\n%% COVAR2 returns the covariance matrix for a rectangular matrix.\n%\n% Discussion:\n%\n% M should be at least N, and B has maximal rank N.\n% The covariance matrix is defined as\n%\n% A = inverse ( B' * B ).\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the order of B.\n% N <= M is required.\n%\n% Input, real B(M,N), the matrix whose covariance matrix \n% is desired.\n%\n% Output, real A(N,N), the covariance matrix of B.\n%\n% Output, integer IERROR, error flag.\n% IERROR = 0 for no error,\n% IERROR is nonzero to mean that A is singular.\n%\n if ( m < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COVAR2 - Fatal error!\\n' );\n fprintf ( 1, ' M < N\\n' );o\n error ( 'COVAR2 - Fatal error!' );\n end\n%\n% Compute B' * B.\n%\n btb(1:n,1:n) = b(1:m,1:n)' * b(1:m,1:n);\n%\n% Factor the matrix.\n%\n [ btb, pivot, error ] = r8mat_gefa ( btb, n );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COVAR2 - Fatal error!\\n' );\n fprintf ( 1, ' The matrix B'' * B does not have full rank.\\n' );\n fprintf ( 1, ' This means that B does not have rank N.\\n' );\n error ( 'COVAR2 - Fatal error!' );\n end\n%\n% Solve for A by solving the equations ( B' * B ) * A = I\n% one column at a time.\n%\n a = identity ( n, n );\n\n job = 0;\n\n for j = 1 : n\n a(1:n,j) = r8mat_gesl ( btb, n, pivot, a(1:n,j), job );\n end\n\n return\nend\n", "meta": {"author": "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/covar2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7726510082919339}} {"text": "function [deltaPoseNoisy] = poseSubNoisy(p_j , p_i, sigmaT, sigmaR, isUniform)\n% pose_sub = (p_j , p_i) = inv(p_i) * p_j + noise\n% returns the planar roto-translation that tranform pj in pi\n% plus noise (sigmaT is the std of the noise on the cartesian components,\n% sigmaR is the std of the noise added to the angle before wrapping)\n\nif nargin < 5\n isUniform = 0; % Gaussian noise by default \nend\n\nif nargin == 2\n sigmaT = 0;\n sigmaR = 0;\nend\n\np_j = p_j(:);\np_i = p_i(:);\n\nrho_i = p_i(1:2);\nrho_j = p_j(1:2);\nth_i = p_i(3);\nth_j = p_j(3);\n\nR = rot2D(th_i);\n\ndelta_th = wrapToPi(th_j - th_i);\n\nif(abs(delta_th) > pi)\n disp('Error in pose_sub')\n disp(delta_th)\nend\n\ndeltaPose = [ R' * (rho_j - rho_i)\n delta_th ];\n\nif isUniform == 0 % Gaussian noise\n noise = [sigmaT*randn(2,1) ; sigmaR*randn];\nelse % uniform noise in the interval [-sigma, + sigma]\n noise = [sigmaT*2*(rand(2,1)-0.5*ones(2,1)) ; sigmaR*2*(rand-0.5)];\nend\n \ndeltaPoseNoisy = deltaPose + noise;\ndeltaPoseNoisy(3) = wrapToPi(deltaPoseNoisy(3)); % wrap angle\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/lib/poseSubNoisy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7726035622970411}} {"text": "function [A,C] = fd_bilinear_coefficients(mn,mx,side,V)\n % FD_BILINEAR_COEFFICIENTS Given a grid from minimum corner mn to maximum\n % corner mx, with `side` nodes on each side, compute a matrix `A` so that\n % `V=A*C` if `C` are the node centers.\n %\n % [A,C] = fd_bilinear_coefficients(mn,mx,side,V)\n %\n % Inputs:\n % mn 3d position of minimum corner\n % mx 3d position of maximum corner\n % side number of nodes in each dimension [x y]\n % V #V by 2 list of query points\n % Outputs:\n % A x*y by #V matrix\n % C x*y by 3 list of node center positions \n % \n\n [X,Y] = meshgrid( ...\n linspace(mn(1),mx(1),side(1)), ...\n linspace(mn(2),mx(2),side(2)));\n C = [X(:) Y(:)];\n r = (mx-mn)./(side-1);\n\n I = floor(bsxfun(@times,bsxfun(@rdivide,bsxfun(@minus,V,mn),mx-mn),side-1));\n A = sparse(size(V,1),prod(side));\n for x = 1:2\n for y = 1:2\n Ixy = sub2ind(side([2 1]),I(:,2)+x,I(:,1)+y);\n Sxy = C(Ixy,:);\n Axy = prod(bsxfun(@minus,r,abs(V-Sxy)),2)/prod(r);\n A = A + sparse((1:size(V,1))',Ixy,Axy,size(V,1),size(C,1));\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/fd_bilinear_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.94499471015743, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7726035593631418}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\n\n[c,p] = max(sigmoid(X*all_theta'),[],2);\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "Ayatans", "repo": "Machine-Learning-homework", "sha": "4550cfc0426c9da8072dff165130fff40d138c10", "save_path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework", "path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework/Machine-Learning-homework-4550cfc0426c9da8072dff165130fff40d138c10/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7725783014047283}} {"text": "function [x,minCost]=convexQuadProgIntegerNoConst2D(Q,b,nonNeg)\n%%CONVEXQUADPROGINTEGERNOCONST2D Perform quadratic programming on a 2D\n% convex problem with no constraints except that the solutions must\n% be integers that are either unconstrained or are non-negative.\n% This functions solves the optimization problem\n% minimize_x x'*Q*x+2*b'*x\n% subject to x is a 2X1 set of integers (optionally non-negative\n% integers).\n%\n%INPUTS: Q An 2X2 real, positive definite symmetric matrix.\n% b An 2X1 real vector.\n% nonNeg This is true if all the x elements should be non-negative and\n% false otherwise. The default if omitted or an empty matrix is\n% passed is false.\n%\n%OUTPUTS: x The 2X1 optimal solution (or an empty matrix if the optimal\n% cost is infinite).\n% minCost The cost of the optimal constrained solution. If the cost isn't\n% finite, then this is an empty matrix.\n%\n%One could implement the branch-and bound algorithm for large scale\n%problems as in [1]. However, in the 2D case, there are so few branches, it\n%isn't worth it. Instead, we simply branch as in [1] (with a\n%simple modification for non-negative constraints) and we traverse all 8\n%hypotheses and then choose the lowest cost one. In [1], when branching,\n%one creates smaller Q and b submatrices to optimize over rather than\n%redoing the entire problem with an added eualaity constraint. In the 2D\n%case, fixing an index means that the subproblem is just optimizing a scalar\n%quadratic equation. Thus, we don't need to explicitely form submatrices;\n%we just directly evaluate the scalar solution to the quadratic.\n%\n%EXAMPLE 1:\n%Here is a simple example. We get the unconstrained solution. Then, we get\n%the integer constrained solution and see that the cost is higher. Finally,\n%we get the integer constrained solution with non-negativity constraints.\n%That is NOT just clipping the integer constrained solution to 0. To show\n%that, we compute the cost of the clipped solution and we see that it is\n%much larger than the solution returned by the function.\n% Q=[32, 20;\n% 20, 22]; \n% b=[-178;-1200];\n% [xOpt,minCost]=convexQuadProgEqConst(Q,b)\n% nonNeg=false;\n% [xOptInt,minCostInt]=convexQuadProgIntegerNoConst2D(Q,b,nonNeg)\n% nonNeg=true;\n% [xNonNegInt,minCostNonNegInt]=convexQuadProgIntegerNoConst2D(Q,b,nonNeg)\n% %We show that the zero-clipped solution is much higher than the one with\n% %non-negativity constraints.\n% xTest=max(xOptInt,0);\n% testCost=xTest'*Q*xTest+2*b'*xTest\n%\n%EXAMPLE 2:\n%One might be tempted the think that one can always obtain the globally\n%optimal solution by solving the unconstrained problem and then just\n%rouning the result or by just trying the 4 points obtained by taking the\n%floor and ceiling of each element of the unconstrained solution. However,\n%that is not the case. In this example, we show the unconstrained solution\n%and then the optimal integer constrained differ by more than 1 index.\n% Q=[25, 0.3;\n% 0.3, 0.01];\n% b=[-156.9;\n% -3.31];\n% xUnconst=convexQuadProgEqConst(Q,b)\n% [x,minCost]=convexQuadProgIntegerNoConst2D(Q,b)\n% %Now, we show that the cost of just rouning up or down the non-integer part\n% %of xUnconst does not produce a globally optimal solution. Only the first\n% %element of xUnConst is not an integer, so we only need to consider points\n% %rounding that one up or down (as opposed to 4 points rounding each\n% %element).\n% xJustRoundUp=ceil(xUnconst);\n% costJustRoundUp=xJustRoundUp'*Q*xJustRoundUp+2*b'*xJustRoundUp\n% xJustRoundDown=floor(xUnconst);\n% costJustRoundDown=xJustRoundDown'*Q*xJustRoundDown+2*b'*xJustRoundDown\n%\n%REFERENCES:\n%[1] F. Koerner, \"An efficient branch and bound algorithm to solve the\n% quadratic integer programming problem,\" Computing, vol. 30, pp. 253-\n% 260, Sep. 1983.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(nonNeg))\n nonNeg=false;\nend\n\nxOpt=convexQuadProgEqConst(Q,b);\n\n%Impose the non-negativity constraint. When branching on each value, if the\n%non-negativity constraint was enforce,d both branches will be the same.\n%However, we aren't going to bother checking to see whether a branch should\n%be skipped, because there are so few branches.\nif(nonNeg)\n xOpt=max(xOpt,0);\nend\n\nx=[];\nminCost=Inf;\n\n%Branch on the first index.\nfor x1=[floor(xOpt(1)),ceil(xOpt(1))]\n %The part of the cost function that depends only on x1 and not x2\n %(which is fixed).\n constCostTerm=2*b(1)*x1+Q(1,1)*x1^2;\n %The optimal solution for x2 given x1 and no constraints.\n x2Node=-(b(2)+Q(1,2)*x1)/(Q(2,2));\n if(nonNeg)\n %Apply a non-negativity constraint.\n x2Node=max(x2Node,0);\n end\n\n %Now, branch on the second index. With it fixed, we just evaluate the\n %cost (There is nothing else to optimize).\n for x2=[floor(x2Node),ceil(x2Node)]\n costCur=2*b(2)*x2+2*Q(1,2)*x1*x2+Q(2,2)*x2^2+constCostTerm;\n if(costCur2),\n error('X must have one or two columns');\nelseif (trow~=1),\n error('T must only have one row'); \nelseif (2^nextpow2(N)~=N),\n fprintf('For a faster computation, N should be a power of two\\n');\nend; \n\ntfr= zeros (N,tcol); \nif trace, disp('Wigner-Ville distribution'); end;\nfor icol=1:tcol,\n ti= t(icol); taumax=min([ti-1,xrow-ti,round(N/2)-1]);\n tau=-taumax:taumax; indices= rem(N+tau,N)+1;\n tfr(indices,icol) = x(ti+tau,1) .* conj(x(ti-tau,xcol));\n tau=round(N/2); \n if (ti<=xrow-tau)&(ti>=tau+1),\n tfr(tau+1,icol) = 0.5 * (x(ti+tau,1) * conj(x(ti-tau,xcol)) + ...\n x(ti-tau,1) * conj(x(ti+tau,xcol))) ;\n end;\n if trace, disprog(icol,tcol,10); end;\nend; \ntfr= fft(tfr); \nif (xcol==1), tfr=real(tfr); end ;\n\nif (nargout==0),\n tfrqview(tfr,x,t,'tfrwv');\nelseif (nargout==3),\n f=(0.5*(0:N-1)/N)';\nend;\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrwv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7724457186343333}} {"text": "function F = Gaus_filter(I,sigma)\n\nR = ceil(3*sigma); \nfor i = -R:R,\n for j = -R:R,\n M(i+ R+1,j+R+1) = exp(-(i*i+j*j)/2/sigma/sigma)/(2*pi*sigma*sigma);\n end\nend\nM = M/sum(sum(M)); % normalize\nF = xconv2(I,M);\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/42435-adaptive-diffusion-flow-active-contours-for-image-segmentation/ADF code/Gaus_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7723358011409239}} {"text": "%% inpainting RobustPCA example: moon picture corrupted with some text\naddpath('../');\n\n% read image and add the mask\nimg = double(imread('moon.tif'))/255;\nimg = img(141:140+256, 51:50+256);\nmsk = zeros(size(img));\nmsk(65:192,65:192) = imresize(imread('text.png'), 0.5);\nimg_corrupted = img;\nimg_corrupted(msk > 0) = nan;\n\nfprintf(1, '%d corrupted entries\\n', nnz(isnan(img_corrupted)));\n\n% create a matrix X from overlapping patches\nws = 16; % window size\nno_patches = size(img, 1) / ws;\nX = zeros(no_patches^2, ws^2);\nk = 1;\nfor i = (1:no_patches*2-1)\n for j = (1:no_patches*2-1)\n r1 = 1+(i-1)*ws/2:(i+1)*ws/2;\n r2 = 1+(j-1)*ws/2:(j+1)*ws/2;\n patch = img_corrupted(r1, r2);\n X(k,:) = patch(:);\n k = k + 1;\n end\nend\n\n% apply Robust PCA\nlambda = 0.02; % close to the default one, but works better\ntic\n[L, S] = RobustPCA(X, lambda, 1.0, 1e-5);\ntoc\n\n% reconstruct the image from the overlapping patches in matrix L\nimg_reconstructed = zeros(size(img));\nimg_noise = zeros(size(img));\nk = 1;\nfor i = (1:no_patches*2-1)\n for j = (1:no_patches*2-1)\n % average patches to get the image back from L and S\n % todo: in the borders less than 4 patches are averaged\n patch = reshape(L(k,:), ws, ws);\n r1 = 1+(i-1)*ws/2:(i+1)*ws/2;\n r2 = 1+(j-1)*ws/2:(j+1)*ws/2;\n img_reconstructed(r1, r2) = img_reconstructed(r1, r2) + 0.25*patch;\n patch = reshape(S(k,:), ws, ws);\n img_noise(r1, r2) = img_noise(r1, r2) + 0.25*patch;\n k = k + 1;\n end\nend\nimg_final = img_reconstructed;\nimg_final(~isnan(img_corrupted)) = img_corrupted(~isnan(img_corrupted));\n\n% show the results\nfigure;\nsubplot(2,2,1), imshow(img_corrupted), title('Corrupted image')\nsubplot(2,2,2), imshow(img_final), title('Recovered image')\nsubplot(2,2,3), imshow(img_reconstructed), title('Recovered low-rank')\nsubplot(2,2,4), imshow(img_noise), title('Recovered sparse')\n\nfprintf(1, 'ws=%d\\tlambda=%f\\trank(L)=%d\\tcard(S)=%d\\terr=%f\\n', ...\n ws, lambda, rank(L), nnz(S), norm(img - img_final, 'fro'));\n", "meta": {"author": "dlaptev", "repo": "RobustPCA", "sha": "db61a39162bc693a6e3ab404e1e680b0720d5aa8", "save_path": "github-repos/MATLAB/dlaptev-RobustPCA", "path": "github-repos/MATLAB/dlaptev-RobustPCA/RobustPCA-db61a39162bc693a6e3ab404e1e680b0720d5aa8/examples/inpainting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7722990297391751}} {"text": "function yval = r8poly_der_val ( n, poly_cof, xval )\n\n%*****************************************************************************80\n%\n%% R8POLY_DER_VAL evaluates the derivative of a polynomial in standard form.\n%\n% Discussion:\n%\n% A polynomial in standard form, with coefficients POLY_COF(*),\n% may be written:\n%\n% P(X) = POLY_COF(1)\n% + POLY_COF(2) * X\n% ...\n% + POLY_COF(N) * X**(N-1)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the polynomial.\n%\n% Input, real POLY_COF(1:N), the polynomial coefficients.\n% POLY_COF(1) is the constant term, and POLY_COF(N) is the coefficient of\n% X**(N-1).\n%\n% Input, real XVAL, a value where the derivative of the\n% polynomial is to be evaluated.\n%\n% Output, real YVAL, the value of the derivative of the\n% polynomial at XVAL.\n%\n yval = ( n - 1 ) * poly_cof(n);\n\n for i = n-1 : -1 : 2\n yval = yval * xval + ( i - 1 ) * poly_cof(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/divdif/r8poly_der_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7722550807880365}} {"text": "function pdf = truncated_normal_a_pdf ( x, mu, sigma, a )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_A_PDF evaluates the lower truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real MU, S, the mean and standard deviation of the\n% parent Normal distribution.\n%\n% Input, real A, the lower truncation limit.\n%\n% Output, real PDF, the value of the PDF.\n%\n alpha = ( a - mu ) / sigma;\n xi = ( x - mu ) / sigma;\n\n alpha_cdf = normal_01_cdf ( alpha );\n xi_pdf = normal_01_pdf ( xi );\n\n pdf = xi_pdf / ( 1.0 - alpha_cdf ) / sigma;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/truncated_normal/truncated_normal_a_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7722201353759481}} {"text": "function [c,s,r] = Givens(x,y)\n%\n% computes c,s,r such that\n%\n% [c s] [x] = [r]\n% [-s c] [y] [0]\n%\n% with c*c + s*s = 1;\n%\n if (y == 0),\n c = 1; s = 0; r = x;\n else \n if (abs(x) >= abs(y))\n t = y/x; r = sqrt(1 + t*t);\n c = 1/r;\n s = t*c;\n r = x*r;\n else \n t = x/y; r = sqrt(1 + t*t);\n s = 1/r;\n c = t*s;\n r = y*r;\n end\n end \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/Givens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.772220127973551}} {"text": "function a = mirt_dctn(a)\n%MIRT_DCTN N-D (multidimensional) discrete cosine transform.\n% B = MIRT_DCTN(A) returns the discrete cosine transform of A.\n% The array B is the same size as A and contains the\n% discrete cosine transform coefficients.\n%\n% This function works much faster than Matlab standard\n% dct (for 1D case) or dct2 (for 2D case), and also allows the ND input.\n% The function takes advantage of 1) FFT 2) fast permutation through indicies\n% 3) persistent precomputation (coefficients and indicies are precomputed during \n% the first run). \n%\n% This transform can be inverted using MIRT_IDCTN.\n% Author: Andriy Myronenko, see www.bme.ogi.edu/~myron\n% revised on May 06, 2010\n%\n% See also MIRT_IDCT.\n\npersistent siz ww ind isreala;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Check input \nif (nargin == 0) || isempty(a) ,\n error('Insufficient input');\nend\n\n\nisreala=isreal(a);\nndim=ndims(a);\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Check for the row vector\ntranspose=0;\nif (ndim==2) && (size(a,1)==1)\n transpose=1; a=a';\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Check if the variable size has changed and we need to\n%%% precompute weights and indicies\n\nprecompute=0;\nif ~exist('siz','var'),\n precompute=1;\nelseif abs(numel(siz)-ndims(a))>0\n precompute=1;\nelseif sum(abs(siz-size(a)),2)>0,\n precompute=1;\nelseif isreala~=isreal(a),\n precompute=1;\nend\n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Precompute weights and indicies\nif precompute,\n siz=size(a);\n ndim=ndims(a);\n \n for i=1:ndim,\n n=siz(i);\n \n ww{i} = 2*exp(((-1i*pi)/(2*n))*(0:n-1)')/sqrt(2*n);\n ww{i}(1) = ww{i}(1) / sqrt(2);\n ind{i}=bsxfun(@plus, [(1:2:n) fliplr(2:2:n)]', 0:n:n*(prod(siz)/n-1));\n if (siz(i)==1), break; end;\n end\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Actual multidimensional DCT. Handle 1D and 2D cases\n%%% separately, because .' is much faster than shiftdim.\n\n% check for 1D or 2D cases\nif ndim==2\n if (min(siz)==1),\n a=dct(a,ww{1},ind{1});if transpose, a=a'; end; % 1D case\n else a = dct(dct(a,ww{1},ind{1}).',ww{2},ind{2}).'; % 2D case\n end \nelse\n % ND case (3D and higher)\n for i=1:ndim\n a=reshape(dct(reshape(a,siz(1),[]),ww{i},ind{i}), siz); % run dct along vectors (1st dimension)\n siz=[siz(2:end) siz(1)]; % circular shift of size array by 1\n a=shiftdim(a,1); % circular shift dimensions by 1\n end\nend\n\n\nfunction a=dct(a,ww,ind)\n%DCT Discrete cosine transform 1D (operates along first dimension)\n\nisreala=isreal(a);\nk=1; if ~isreala, ia = imag(a); a = real(a); k=2; end; % check if complex\n \n% k=1 (if 'a' is real) and 2 (if 'a' is complex)\nfor i=1:k\n a=a(ind); % rearange\n a = fft(a); % ifft\n a = real(bsxfun(@times, ww, a)); % multiply weights\n\n % check if the data is not real\n if ~isreala,\n if i==1, ra = a; a = ia; clear ia; % proceed to imaginary part\n else a = complex(ra,a); end; % finalize the output\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/24050-multidimensional-discrete-cosine-transform-dct/mirt_dctn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7722088995880046}} {"text": "function [ vWm, vWc, scalingFactor ] = CalcSigmaPointsWeights( paramAlpha, paramBeta, paramKappa, stateOrder )\n% ----------------------------------------------------------------------------------------------- %\n% [ vWm, vWc, scalingFactor ] = CalcSigmaPointsWeights( paramAlpha, paramBeta, paramKappa, stateOrder )\n% Calculates the weights for the mean, covariance and scaling factor of \n% the Unscented Transform.\n% Input:\n% - paramAlpha - Parameter Alpha.\n% Influences how far the Sigma Points are form the\n% mean.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, 1].\n% - paramBeta - Parameter Beta.\n% For Gaussian PDF the optimal value is 2.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: NA.\n% - paramKappa - Parameter Kappa.\n% Influences how far the Sigma Points are form the\n% mean.\n% Type: 'Single' / 'Double'.\n% Range: [0, inf).\n% - stateOrder - State Vector Dimension.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, ...}.\n% Output:\n% - vWm - Mean Weights Vector.\n% Weights used for calculation of the mean of the\n% transformed data.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vWc - Covariance Weights Vector.\n% Weights used for calculation of the covariance of \n% the transformed data.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - scalingFctr - Scaling Factor.\n% Parameter of the Generalized Unscented Transform\n% which controls \n% Equals to 'size(hF(mX(:, 1), 1)'.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, ...}.\n% References\n% 1. Unscented Transform (Wikipedia) - https://en.wikipedia.org/wiki/Unscented_transform.\n% 2. Lecture 5: Unscented Kalman Filter and General Gaussian Filtering (Simo Sarkka).\n% 3. Robot Mapping - Unscented Kalman Filter (Cyrill Stachniss).\n% Remarks:\n% 1. This method of parameters is often called Generalized / Scaled\n% Unscented Kalman Filter.\n% TODO:\n% 1. U.\n% Release Notes:\n% - 1.0.000 24/08/2018 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nnumSigmaPoints = (2 * stateOrder) + 1;\n\nvWm = zeros(numSigmaPoints, 1);\nvWc = zeros(numSigmaPoints, 1);\n\nparamLambda = ((paramAlpha * paramAlpha) * (stateOrder + paramKappa)) - stateOrder;\n\nvWm(1) = paramLambda / (stateOrder + paramLambda);\nvWm(2:end) = 1 / (2 * (stateOrder + paramLambda));\nvWc(1) = vWm(1) + (1 - (paramAlpha * paramAlpha) + paramBeta);\nvWc(2:end) = vWm(2:end);\n\nscalingFactor = sqrt(stateOrder + paramLambda);\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/Q51386/CalcSigmaPointsWeights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7722088921415101}} {"text": "function distance_map_in_meters = distance_in_meters_cityscapes(...\n depth_map_in_meters, camera_parameters_file)\n%DISTANCE_IN_METERS_CITYSCAPES Compute air thickness, i.e. distance of depicted\n%object from camera center, expressed in meters, as a dense map with same\n%resolution as the image, using a dense depth map and intrinsic camera\n%parameters as inputs.\n\n% Retrieve relevant intrinsic camera parameters: focal length and optical\n% center, both expressed in pixel coordinates.\n[~, f_x, c_x, c_y] = camera_parameters_cityscapes(camera_parameters_file);\n\n% Compute medium (i.e. air) thickness in meters from depth. The derivation of\n% the formula in the final lines of code is based on similar triangles.\n\n[height, width] = size(depth_map_in_meters);\n[X, Y] = meshgrid(1:width, 1:height);\n\ndistance_map_in_meters = depth_map_in_meters .*...\n sqrt((f_x ^ 2 + (X - c_x) .^ 2 + (Y - c_y) .^ 2) / f_x ^ 2);\n\nend\n\n", "meta": {"author": "sakaridis", "repo": "fog_simulation-SFSU_synthetic", "sha": "8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3", "save_path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic", "path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic/fog_simulation-SFSU_synthetic-8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3/source/Depth_processing/distance_in_meters_cityscapes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7721740774495662}} {"text": "function a = combin ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% COMBIN returns the combinatorial matrix.\n%\n% Formula:\n%\n% If ( I = J ) then\n% A(I,J) = ALPHA + BETA\n% else\n% A(I,J) = BETA\n%\n% Example:\n%\n% N = 5, ALPHA = 2, BETA = 3\n%\n% 5 3 3 3 3\n% 3 5 3 3 3\n% 3 3 5 3 3\n% 3 3 3 5 3\n% 3 3 3 3 5\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% det ( A ) = ALPHA**(N-1) * ( ALPHA + N * BETA ).\n%\n% LAMBDA(1:N-1) = ALPHA,\n% LAMBDA(N) = ALPHA + N * BETA.\n%\n% The eigenvector associated with LAMBDA(N) is (1,1,1,...,1)/sqrt(N).\n%\n% The other N-1 eigenvectors are simply any (orthonormal) basis\n% for the space perpendicular to (1,1,1,...,1).\n%\n% A is nonsingular if ALPHA /= 0D+00 and ALPHA + N * BETA /= 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% Example 3.25,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, New York, 1969, page 53,\n% LC: QA263.G68.\n%\n% Donald Knuth,\n% The Art of Computer Programming,\n% Volume 1, Fundamental Algorithms, Second Edition,\n% Addison-Wesley, Reading, Massachusetts, 1973, page 36.\n%\n% Parameters:\n%\n% Input, real ALPHA, BETA, scalars that define A.\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a(1:n,1:n) = beta;\n\n for i = 1 :n\n a(i,i) = a(i:i) + alpha;\n end\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/condition/combin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7721548159457857}} {"text": "function [J grad] = nnCostFunction(nn_params, ...\n input_layer_size, ...\n hidden_layer_size, ...\n num_labels, ...\n X, y, lambda)\n%NNCOSTFUNCTION Implements the neural network cost function for a two layer\n%neural network which performs classification\n% [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...\n% X, y, lambda) computes the cost and gradient of the neural network. The\n% parameters for the neural network are \"unrolled\" into the vector\n% nn_params and need to be converted back into the weight matrices. \n% \n% The returned parameter grad should be a \"unrolled\" vector of the\n% partial derivatives of the neural network.\n%\n\n% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices\n% for our 2 layer neural network\nTheta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...\n hidden_layer_size, (input_layer_size + 1));\n\nTheta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...\n num_labels, (hidden_layer_size + 1));\n\n% Setup some useful variables\n\nm = size(X, 1);\nX = [ones(size(X,1),1), X];\n\n% You need to return the following variables correctly \nJ = 0;\nTheta1_grad = zeros(size(Theta1));\nTheta2_grad = zeros(size(Theta2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the code by working through the\n% following parts.\n%\n% Part 1: Feedforward the neural network and return the cost in the\n% variable J. After implementing Part 1, you can verify that your\n% cost function computation is correct by verifying the cost\n% computed in ex4.m\n%\n% Part 2: Implement the backpropagation algorithm to compute the gradients\n% Theta1_grad and Theta2_grad. You should return the partial derivatives of\n% the cost function with respect to Theta1 and Theta2 in Theta1_grad and\n% Theta2_grad, respectively. After implementing Part 2, you can check\n% that your implementation is correct by running checkNNGradients\n%\n% Note: The vector y passed into the function is a vector of labels\n% containing values from 1..K. You need to map this vector into a \n% binary vector of 1's and 0's to be used with the neural network\n% cost function.\n%\n% Hint: We recommend implementing backpropagation using a for-loop\n% over the training examples if you are implementing it for the \n% first time.\n%\n% Part 3: Implement regularization with the cost function and gradients.\n%\n% Hint: You can implement this around the code for\n% backpropagation. That is, you can compute the gradients for\n% the regularization separately and then add them to Theta1_grad\n% and Theta2_grad from Part 2.\n%\n\n\n\nZ2 = X*Theta1';\nA2 = sigmoid(Z2);\n\nA2 = [ones(size(A2,1),1), A2];\nZ3 = A2*Theta2';\n\nA3 = sigmoid(Z3);\n\n\n% Y = zeros(m, max(y(:)));\n% Y(y,:)\n\nY = dummyvar(y);\n\nJ = sum(sum(-1.*Y.*log(A3)-(1-Y).*log(1-A3),2))/m;\n\nreg = (sum(sum(Theta1(:,2:end).^2)) + sum(sum(Theta2(:,2:end).^2)))*lambda/(2*m);\nJ = J+reg;\n\n\ndelta3 = A3 - Y;\n\nTheta2_grad = Theta2_grad + (delta3'*A2)/m;\n\ndelta2 = delta3*Theta2(:,2:end).*sigmoidGradient(Z2);\n\nTheta1_grad = Theta1_grad+(delta2'*X)/m;\n\n\nTheta1_grad(:,2:end) = Theta1_grad(:,2:end) + lambda*Theta1(:,2:end)/m;\nTheta2_grad(:,2:end) = Theta2_grad(:,2:end) + lambda*Theta2(:,2:end)/m;\n% -------------------------------------------------------------\n\n% =========================================================================\n\n% Unroll gradients\ngrad = [Theta1_grad(:) ; Theta2_grad(:)];\n\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex4/nnCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7721254205221403}} {"text": "function variance = nakagami_variance ( a, b, c )\n\n%*****************************************************************************80\n%\n%% NAKAGAMI_VARIANCE returns the variance of the Nakagami PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, the parameters of the PDF.\n% 0.0 < B\n% 0.0 < C\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n t1 = gamma ( c + 0.5 );\n t2 = gamma ( c );\n\n variance = b * b * ( 1.0 - t1 * t1 / ( c * t2 * t2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/nakagami_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7720804367127384}} {"text": "function z = spadaptdemo\n% SPADAPTDEMO Simple example of dimension-adaptive interpolation\n% A 2D-example for dimension-adaptive multi-linear sparse grid \n% interpolation using the Chebyshev grid and vectorized processing\n% of the model function. \n%\n% See also SPINTERP, SPVALS.\n\n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.1\n% Date : September 29, 2003\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\n% The Branin function is used here\nf = inline(['(5/pi*x-5.1/(4*pi^2)*x.^2+y-6).^2 + 10*(1-1/(8*pi))*' ...\n\t ' cos(x)+10']); \n\n% Define objective box\nrange = [-5 10; 0 15];\n\n% Define problem dimension\nd = 2;\n\n% Create full grid for plotting\ngs = 33;\n[X,Y] = meshgrid(linspace(range(1,1),range(1,2),gs),...\n\t\t\t\t\t\t\t\t linspace(range(2,1),range(2,2),gs));\n\n% Set options: Switch vectorized processing on.\noptions = spset('Vectorized', 'on','RelTol', 1e-2, ...\n\t\t\t\t\t\t\t\t'GridType', 'Chebyshev', ...\n\t\t\t\t\t\t\t\t'DimensionAdaptive', 'on', ...\n\t\t\t\t\t\t\t\t'DimadaptDegree', 1, ...\n 'MinPoints', 10);\n\n% Compute sparse grid weights over range\nz = spvals(f, d, range, options);\n\n% Compute inpterpolated values at full grid\nip = spinterp(z, X, Y);\n\n% Plot original function, interpolation, and error\nsubplot(2,2,1);\nmesh(X,Y,f(X,Y));\ntitle('original');\naxis tight;\n\nsubplot(2,2,2);\nmesh(X,Y,ip);\ntitle('interpolated');\naxis tight;\n\nsubplot(2,2,3);\nmesh(X,Y,abs(f(X,Y)-ip));\ntitle('absolute error');\naxis tight;\n\nsubplot(2,2,4);\nplotindices(z);\ntitle('resulting index sets');\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spinterp/examples/spadaptdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7720804336072198}} {"text": "function x = fibonacci_lattice_q_nodes ( k )\n\n%*****************************************************************************80\n%\n%% FIBONACCI_LATTICE_Q_NODES returns Fibonacci lattice nodes in 2D.\n%\n% Discussion:\n%\n% Because this is a standard lattice rule, it is really only suited\n% for functions which are periodic, of period 1, in both X and Y.\n%\n% The number of nodes returned is\n%\n% M = fibonacci ( k ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 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 K, the index of the Fibonacci number to be used.\n% K must be at least 3.\n%\n% Output, real X(2,M), the nodes.\n%\n dim_num = 2;\n\n m = fibonacci ( k );\n\n z(1) = 1;\n z(2) = fibonacci ( k - 1 );\n\n for j = 0 : m - 1\n x(1:dim_num,j+1) = mod ( j * z(1:dim_num) / m, 1.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/lattice_rule/fibonacci_lattice_q_nodes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7720804311626864}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% KNOCK-OUT BARRIER OPTION PRICE COMPARISON (RUN SCRIPT)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Compare Methods For Barrier Options Under Black Scholes Model\n% This script compares accuracy/CPU of the following methods,\n% Monte Carlo\n% PROJ\n%\n% Author: Justin Kirkby\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\naddpath('../../PROJ/LEVY/RN_CHF')\naddpath('../../PROJ/LEVY/Helper_Functions')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nS_0 = 100; %Initial price\nW = 100; %Strike %NOTE: no error handling in place for extreme values of W (increase grid if strike falls outside)\nr = 0.05; %Interest rate\nq = 0.02; %dividend yield\nT = 1; %Time (in years)\ncall = 1; %For call use 1 (else, its a put)\ndown = 1; %down-out or up-out (down=1 => down-and-out)\nH = 90; %barrier (Knock-Out)\nM = 52; %number of discrete monitoring points\nrebate = 0; % rebate paid immediately upon passing the barrier (knocking-out) \n\nsigma = 0.15; % volatility of diffusion\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmodel = 1; params = {}; params.sigmaBSM = sigma;\nmodelInput = getModelInput(model, T/M, r, q, params);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Reference Price (Using PROJ)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../PROJ/LEVY/Barrier_Options')\nL1_ref = 20; N_ref = 2^17;\nalpha_ref = getTruncationAlpha(T, L1_ref, modelInput, model);\nprice_ref = PROJ_Barrier(N_ref, alpha_ref, call, down, S_0, W, H, M, r, q, modelInput.rnCHF, T, rebate); \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PROJ Method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nN = 2^12; % grid roughly centered on [c1 - alph, c1 + alph]\nL1 = 10;\nalpha = getTruncationAlpha(T, L1, modelInput, model);\n\ntic\nprice_PROJ = PROJ_Barrier(N, alpha, call, down, S_0, W, H, M, r, q, modelInput.rnCHF, T, rebate); \ntime_PROJ = toc;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Monte Carlo Pricer (Exact Sim, Multi-Step)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NOTE: Variance reduction techniques should be used in practice\naddpath('../../Monte_Carlo/')\naddpath('../../Monte_Carlo/Barrier')\nN_sim = 5*10^5; % number of paths\nmult = 3; % multiplier for simulation (see below) to reduce bias\n\ntic\nM_mult = M*mult; %time partitioning to reduce bias\nSpath = Simulate_Jump_Diffusion_func( N_sim, M_mult + 1, T, S_0, r, q, sigma);\n\n[price_MC, stdErr] = Price_MC_Barrier_Strikes_func(Spath, call, down, H, W, M, mult, rebate, r, T);\n\nprice_MC_L = price_MC - 2*stdErr; price_MC_U = price_MC + 2*stdErr;\ntime_MC = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% COMPARE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfprintf('\\n---------------------------------------------\\n')\nfprintf('Method | Price | Err | CPU \\n')\nfprintf('---------------------------------------------\\n')\nfprintf('Reference | %.8f | | \\n', price_ref)\nfprintf('---------------------------------------------\\n')\nfprintf('PROJ | %.8f | %.2e | %.4f \\n', price_PROJ, abs(price_ref-price_PROJ), time_PROJ)\nfprintf('---------------------------------------------\\n')\nfprintf('MC-Exact |[%.3f,%.3f]| %.2e | %.4f \\n', price_MC_L, price_MC_U, abs(price_ref-price_MC), time_MC)\nfprintf('---------------------------------------------\\n')\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Comparisons/BlackScholes/Script_Compare_Barrier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.772080427895027}} {"text": "function sample = SampleGaussian(mu, sigma)\n\n% sample from the Gaussian distribution specifed by mean value mu and standard deviation sigma\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\n sample = mu + sigma*randn(1,1);\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/8.Learning Tree Structured Networks/SampleGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7720559768467966}} {"text": "function X = fast_pca(in_X, K)\n\nin_X = in_X - repmat(mean(in_X),size(in_X,1),1);\n[U, S, ~] = rsvd(in_X, K);\nK = min(size(S,2),K);\nX = U(:,1:K)*diag(sqrt(diag(S(1:K,1:K))));\nX = X./repmat(sqrt(sum(X.*X,2)),1,K);\nend\n\nfunction [U,S,V] = rsvd(A,K)\n%-------------------------------------------------------------------------------------\n% random SVD\n% Extremely fast computation of the truncated Singular Value Decomposition, using\n% randomized algorithms as described in Halko et al. 'finding structure with randomness\n%\n% usage : \n%\n% input:\n% * A : matrix whose SVD we want\n% * K : number of components to keep\n%\n% output:\n% * U,S,V : classical output as the builtin svd matlab function\n%-------------------------------------------------------------------------------------\n% Antoine Liutkus (c) Inria 2014\n\n[M,N] = size(A);\nP = min(2*K,N);\nX = randn(N,P);\nY = A*X;\nW1 = orth(Y);\nB = W1'*A;\n[W2,S,V] = svd(B,'econ');\nU = W1*W2;\nK=min(K,size(U,2));\nU = U(:,1:K);\nS = S(1:K,1:K);\nV=V(:,1:K);\nend", "meta": {"author": "BatzoglouLabSU", "repo": "SIMLR", "sha": "bf44967cd40d9d4c789ecf866b3aae15ae6190f5", "save_path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR", "path": "github-repos/MATLAB/BatzoglouLabSU-SIMLR/SIMLR-bf44967cd40d9d4c789ecf866b3aae15ae6190f5/MATLAB/src/fast_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7719348977824715}} {"text": "function M = euclideancomplexfactory(m, n)\n% Returns a manifold struct to optimize over complex m-by-n matrices.\n%\n% function M = euclideancomplexfactory(m, n)\n%\n% Returns M, a structure describing the vector space of complex m-by-n\n% matrices, as a manifold for Manopt.\n%\n% The complex plane is here viewed as R^2. The inner product between two\n% m-by-n matrices A and B is given by: real(trace(A'*B)). This choice\n% guides the proper definition of gradient and Hessian for this geometry.\n% This is not the classical Euclidean inner product for complex matrices;\n% it is a real inner product.\n%\n% See also: euclideanfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, April 7, 2015.\n% Contributors: \n% Change log: \n\n \n if ~exist('n', 'var') || isempty(n)\n n = 1;\n end\n\n M.name = @() sprintf('Vector space C^(%dx%d)', m, n);\n \n M.dim = @() 2*m*n;\n \n M.inner = @(x, d1, d2) real(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([real(x(:)) ; imag(x(:))])];\n \n M.rand = @() (randn(m, n) + 1i*randn(m, n))/sqrt(2);\n \n M.randvec = @randvec;\n function u = randvec(x) %#ok\n u = randn(m, n) + 1i*randn(m, n);\n u = u / norm(u, 'fro');\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(m, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n mn = m*n;\n M.vec = @(x, u_mat) [real(u_mat(:)) ; imag(u_mat(:))];\n M.mat = @(x, u_vec) reshape(u_vec(1:mn), [m, n]) + 1i*reshape(u_vec((mn+1):end), [m, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/euclidean/euclideancomplexfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7719169298746034}} {"text": "function signal = logCompression(signal, a, normalise)\n%LOGCOMPRESSION Log compress an input signal.\n%\n% DESCRIPTION:\n% logCompression compresses the input signal using the expression\n% signal = log10(1 + a*signal)./log10(1 + a) \n%\n% USAGE:\n% signal = logCompression(signal, a)\n% signal = logCompression(signal, a, normalise)\n%\n% INPUTS:\n% signal - input signal\n% a - compression factor\n%\n% OPTIONAL INPUTS\n% normalise - Boolean controlling whether the maximum of the input\n% signal is normalised to unity before compression\n% (default = false). If set to true, the original\n% magnitude is restored after compression.\n%\n% OUTPUTS:\n% signal - log compressed signal\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 24th February 2011\n% last update - 24th February 2011\n%\n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\n% check for optional normalise input\nif nargin == 2\n normalise = false;\nend\n\n% compress signal\nif normalise\n mx = max(signal(:));\n signal = mx*(log10(1 + a*signal./mx)./log10(1 + a));\nelse \n signal = log10(1 + a*signal)./log10(1 + a);\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/logCompression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7719116835439863}} {"text": "function varargout = alldist2(varargin)\n% VL_ALLDIST2 Pairwise distances\n% D = VL_ALLDIST2(X,Y) returns the pairwise distance matrix D of the\n% columns of S1 and S2, yielding\n%\n% D(i,j) = sum (X(:,i) - Y(:,j)).^2\n%\n% VL_ALLDIST2(X) returns the pairwise distance matrix fo the columns of\n% S, yielding\n%\n% D(i,j) = sum (X(:,i) - X(:,j)).^2\n%\n% VL_ALLDIST2(...,'METRIC') changes the computed distance. Supported\n% values for METRIC are\n%\n% METRIC D(i,j)\n% --------------------------------------------------------\n% LINF max |X - Y|\n% L2 sum (X - Y).^2\n% L1 sum |X - Y|\n% L0 sum (X ~= Y)\n% CHI2 sum (X - Y).^2 ./ (X + Y)\n% HELL sum (X^.5 - Y^.5) .^ 2\n%\n% (Notice that the standard definition of chi2 is half of what is\n% computed here).\n%\n% VL_ALLDIST2(...,'KERNEL') computes the following 'kernels' K:\n%\n% KERNEL K(i,j)\n% ---------------------------------------------------------\n% KL2 sum X .* Y\n% KL1 sum min (X, Y)\n% KCHI2 2 * sum (X .* Y) ./ (X + Y)\n% KHELL (X .* Y) .^ 0.5\n%\n% The constant are chosen so that D(i,j) = K(i,i) + K(j,j) - 2 K(i,j)\n% where D is the metric corresponding to the kenrel (if the arguments\n% are non-negative vectors). Each kernel can be interpreted as the\n% inner product inducing the corresponding metric in an embedding of\n% the real space into an approrpiate reproducing Kenrel Hilbert\n% space.\n%\n% VL_ALLDIST2() supports several storage classes. X and Y must have the\n% same storage class. The sotrage class of D is promoted to reduce\n% the chance of overvlow, but this is not checked.\n%\n% X & Y class D class\n% ---------------------------\n% UINT8 UINT32\n% INT8 INT32\n% UINT16 UINT32\n% INT16 INT32\n% UINT32 UINT32\n% INT32 INT32\n% SINGLE SINGLE\n% DOUBLE DOUBLE\n%\n% Warning: Both chi2 and kchi2 use integer math when presented with\n% integer data types. This can easily result in zeros where you did\n% not expect them.\n%\n% See also: VL_HELP().\n[varargout{1:nargout}] = vl_alldist2(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/alldist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7719098442848231}} {"text": "function a = daub10 ( n )\n\n%*****************************************************************************80\n%\n%% DAUB10 returns the DAUB10 matrix.\n%\n% Discussion:\n%\n% The DAUB10 matrix is the Daubechies wavelet transformation matrix\n% with 10 coefficients.\n%\n% Note that in the reference, the coefficient 0.0775714938400459\n% is given incorrectly, with the \"8\" misrepresented as a \"0\".\n%\n% Properties:\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gilbert Strang, Truong Nguyen,\n% Wavelets and Filter Banks,\n% Wellesley-Cambridge Press, 1997,\n% ISBN: 0-9614088-7-1,\n% LC: TK7872.F5S79 / QA403.3.S87\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be at least 10, and a multiple of 2.\n%\n% Output, real A(N,N), the matrix.\n%\n c = [ ...\n 0.1601023979741929, ...\n 0.6038292697971895, ...\n 0.7243085284377726, ...\n 0.1384281459013203, ...\n -0.2422948870663823, ...\n -0.0322448695846381, ...\n 0.0775714938400459, ...\n -0.0062414902127983, ...\n -0.0125807519990820, ...\n 0.0033357252854738 ];\n\n if ( n < 10 || mod ( n, 2 ) ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DAUB10 - Fatal error!\\n' );\n fprintf ( 1, ' N must be at least 10 and a multiple of 2.\\n' );\n error ( 'DAUB10 - Fatal error!' );\n end\n\n a = zeros ( n, n );\n\n for i = 1 : 2 : n - 1\n\n a(i,i) = c(1);\n a(i,i+1) = c(2);\n a(i,i4_wrap(i+2,1,n)) = c(3);\n a(i,i4_wrap(i+3,1,n)) = c(4);\n a(i,i4_wrap(i+4,1,n)) = c(5);\n a(i,i4_wrap(i+5,1,n)) = c(6);\n a(i,i4_wrap(i+6,1,n)) = c(7);\n a(i,i4_wrap(i+7,1,n)) = c(8);\n a(i,i4_wrap(i+8,1,n)) = c(9);\n a(i,i4_wrap(i+9,1,n)) = c(10);\n\n a(i+1,i) = c(10);\n a(i+1,i+1) = - c(9);\n a(i+1,i4_wrap(i+2,1,n)) = c(8);\n a(i+1,i4_wrap(i+3,1,n)) = - c(7);\n a(i+1,i4_wrap(i+4,1,n)) = c(6);\n a(i+1,i4_wrap(i+5,1,n)) = - c(5);\n a(i+1,i4_wrap(i+6,1,n)) = c(4);\n a(i+1,i4_wrap(i+7,1,n)) = - c(3);\n a(i+1,i4_wrap(i+8,1,n)) = c(2);\n a(i+1,i4_wrap(i+9,1,n)) = - c(1);\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/daub10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.771868475040418}} {"text": "function order = level_to_order_open ( dim_num, level )\n\n%*****************************************************************************80\n%\n%% LEVEL_TO_ORDER converts a level to an order for open rules.\n%\n% Discussion:\n%\n% Sparse grids can naturally be nested. A natural scheme is to use\n% a series of one-dimensional rules arranged in a series of \"levels\"\n% whose order roughly doubles with each step.\n%\n% The arrangement described here works naturally for the Fejer Type 1,\n% Fejer Type 2, Newton Cotes Open, Newton Cotes Half Open,\n% and Gauss-Patterson rules. It also can be used, partially, to describe\n% the growth of Gauss-Legendre rules.\n%\n% The idea is that we start with LEVEL = 0, ORDER = 1 indicating the single\n% point at the center, and for all values afterwards, we use the relationship\n%\n% ORDER = 2**(LEVEL+1) - 1.\n%\n% The following table shows how the growth will occur:\n%\n% Level Order\n%\n% 0 1\n% 1 3 = 4 - 1\n% 2 7 = 8 - 1\n% 3 15 = 16 - 1\n% 4 31 = 32 - 1\n% 5 63 = 64 - 1\n%\n% For the Fejer Type 1, Fejer Type 2, Newton Cotes Open,\n% Newton Cotes Open Half, and Gauss-Patterson rules, the point growth is\n% nested. If we have ORDER points on a particular LEVEL, the next level\n% includes all these old points, plus ORDER+1 new points, formed in the\n% gaps between successive pairs of old points plus an extra point at each\n% end.\n%\n% Level Order = New + Old\n%\n% 0 1 = 1 + 0\n% 1 3 = 2 + 1\n% 2 7 = 4 + 3\n% 3 15 = 8 + 7\n% 4 31 = 16 + 15\n% 5 63 = 32 + 31\n%\n% If we use a series of Gauss-Legendre rules, then there is almost no\n% nesting, except that the central point is shared. If we insist on\n% producing a comparable series of such points, then the \"nesting\" behavior\n% is as follows:\n%\n% Level Order = New + Old\n%\n% 0 1 = 1 + 0\n% 1 3 = 2 + 1\n% 2 7 = 6 + 1\n% 3 15 = 14 + 1\n% 4 31 = 30 + 1\n% 5 63 = 62 + 1\n%\n% Moreover, if we consider ALL the points used in such a set of \"nested\"\n% Gauss-Legendre rules, then we must sum the \"NEW\" column, and we see that\n% we get roughly twice as many points as for the truly nested rules.\n%\n% In this routine, we assume that a vector of levels is given,\n% and the corresponding orders are desired.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL(DIM_NUM), the nesting level.\n%\n% Output, integer ORDER(DIM_NUM,1), the order (number of points) of the rule.\n%\n order = zeros ( dim_num, 1 );\n\n for dim = 1 : dim_num\n\n if ( level(dim) < 0 )\n order(dim,1) = -1;\n elseif ( level(dim) == 0 )\n order(dim,1) = 1;\n else\n order(dim,1) = 2^( level(dim) + 1 ) - 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hermite/level_to_order_open.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8459424411924674, "lm_q1q2_score": 0.7718684689976006}} {"text": "function cx = laguerre_poly ( n, x )\n\n%*****************************************************************************80\n%\n%% LAGUERRE_POLY evaluates the Laguerre polynomials at 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 \n% + 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 < Infinity ) 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% 26 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N, the highest order polynomial to compute.\n% Note that polynomials 0 through N will be computed.\n%\n% Input, real X, the point at which the polynomials are to be evaluated.\n%\n% Output, real CX(1:N+1), the Laguerre polynomials of degree 0 through \n% N evaluated at the point X.\n%\n if ( n < 0 )\n cx = [];\n return\n end\n\n cx(1) = 1.0;\n\n if ( n == 0 )\n return\n end\n\n cx(2) = 1.0 - x;\n \n for i = 2 : n\n\n cx(i+1) = ( ( ( 2 * i - 1 ) - x ) * cx(i ) ...\n - ( i - 1 ) * cx(i-1) ) ...\n / ( i );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/laguerre_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7718684685129145}} {"text": "%% EXAMPLE 8: Band-pass filtering.\n%\n% Reference:\n% [1] A. Nekkanti, O. T. Schmidt, Frequency–time analysis, low-rank reconstruction and denoising of turbulent flows using SPOD, \n% Journal of Fluid Mechanics 926, A26, 2021\n%\n% O. T. Schmidt (oschmidt@ucsd.edu)\n% Last revision: 5-Sep-2022\n\nclc, clear variables\naddpath('utils')\ndisp('Loading the entire test database might take a second...')\nload(fullfile('jet_data','jetLES.mat'),'p','p_mean','x','r','dt');\n\n% trapezoidal quadrature weights for cylindrical coordinates\nintWeights = trapzWeightsPolar(r(:,1),x(1,:));\n\n%% SPOD\n% We will use standard parameters: a Hann window of length 256 and 50%\n% overlap.\nnDFT = 256;\nnOvlp = nDFT/2;\n[L,P,f,~,A] = spod(p,nDFT,intWeights,nOvlp,dt);\n\nfigure\nloglog(f,L)\ntitle('SPOD of full data')\nxlabel('frequency'), ylabel('SPOD mode energy')\nylims = ylim;\n\n%% Filtering\n% An band-pass filter that focusses on the 'low-rank' portion of the\n% spectrum is implemented by setting to zero the SPOD expansion\n% coefficients in the range f<=0.08 and f>=1.0.\nf_lowpass = 1;\nf_highpass = 0.08; \nA(f>=f_lowpass|f<=f_highpass,:,:) ...\n = 0;\n\n% The inverse SPOD using the modified SPOD expansion coefficients yields\n% the band-pass filtered data.\nnt = size(p,1);\np_rec = invspod(P,A,nDFT,nOvlp);\n\n%% Animate\n% Animate the original, filtered, and removed data.\nfigure\nfor t_i=1:1:30\n subplot(3,1,1)\n pcolor(x,r,squeeze(p(t_i,:,:))-p_mean); shading interp, axis equal tight\n title('Original data')\n if t_i==1; pmax = max(abs(caxis)); end, caxis(0.5*pmax*[-1 1]), colorbar \n subplot(3,1,2)\n pcolor(x,r,squeeze(p_rec(t_i,:,:))); shading interp, axis equal tight\n title('Reconstructed data')\n caxis(0.5*pmax*[-1 1]), colorbar\n subplot(3,1,3)\n pcolor(x,r,(squeeze(p(t_i,:,:))-p_mean)-squeeze(p_rec(t_i,:,:))); shading interp, axis equal tight\n title('Filtered/removed component')\n caxis(0.5*pmax*[-1 1]), colorbar\n drawnow\nend\n\n%% SPOD of filtered data\n% The effect of the band-pass filter should to a large degree remove\n% high-frequency components above the filter cut-on frequency.\n[L,P,f,~,A] = spod(p_rec,nDFT,intWeights,nOvlp,dt);\n\nfigure\nloglog([f_lowpass f_lowpass],ylims,'k--'); hold on\nloglog([f_highpass f_highpass],ylims,'k:');\nloglog(f,L)\ntitle('SPOD of filtered data')\nxlabel('frequency'), ylabel('SPOD mode energy')\nylim(ylims);\nlegend('f_{low-pass}','f_{high-pass}')\n\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_8_invspod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7718684654537418}} {"text": "%% Coarsening for Algebraic Multigrid\n%\n% Given a SPD matrix A, we describe an algebraic coarsening of a graph of A\n% based on the concept of strong connectness. The measure of strong\n% connectness is slightly different with the standard definition. The\n% parameter theta is used to define strong connectness and the default\n% value is 0.025.\n\n%% Usage of the function\nclear all\nhelp coarsenAMGc\n\n%% Generate a test matrix\n[node,elem] = squaremesh([0,1,0,1],1/8);\n% [node,elem] = uniformrefine(node,elem);\n% load lakemesh\n[A,M] = assemblematrix(node,elem);\n% A = M; % test mass matrix. No coarsening is needed.\n\n%% Parameters\ntheta = 0.025;\nN = size(A,1);\nN0 = min(sqrt(N),50); % number of the coarest nodes\n\n%% Generate strong connectness matrix\nD = spdiags(1./sqrt(diag(A)),0,N,N);\nAm = D*A*D; % normalize diagonal of A\n[im,jm,sm] = find(Am); \nidx = (-sm > theta); % delete weakly connect off-diagonal and diagonal\nAs = sparse(im(idx),jm(idx),sm(idx),N,N); % matrix for strong connectness\n% The diagonal of Am is 1. The negative off-diagonal measures the\n% diffusivity. The positive off-diagonal is filtered. \n\n%% Compute degree of vertex\ndeg = sum(spones(As)); % number of strongly connected neighbors\ndeg = full(deg');\n% deg = deg + rand(N,1); % break the equal degree case but deteriorate performance\nif sum(deg>0) < 0.1*sqrt(N) % too few connected nodes e.g. A is mass matrix\n isC(round(rand(N0,1)*N)) = true; % randomly chose N0 nodes\n return % smoother is a good preconditioner\nend \nidx = (deg>0);\ndeg(idx) = deg(idx) + 0.1*rand(sum(idx),1); % break the equal degree case\n\n%% Find an approximate maximal independent set and put to C set\nisC = false(N,1); % C: coarse node\nisF = false(N,1); % F: fine node\nisU = true(N,1); % S: selected set\nisF(deg == 0) = true; % isolated nodes are added into F set\n% debug\nclose all;\n%%\n% * magneta dots: indepedent nodes in U\n% * yellow dots: F (fine) nodes\n% * red dots: C (coarse) nodes\n% * black dots: U (undecided) nodes\nset(gcf,'Units','normal'); \nset(gcf,'Position',[0.5,0.5,0.5,0.5]);\nshowmesh(node,elem); \nfindnode(node,isU,'noindex','Color','k','MarkerSize',32)\nm = 1;\nwhile sum(isC) < N/2 && sum(isU) >N0 \n % Mark all undecided nodes\n isS = false(N,1); % S: selected set, changing in the coarsening\n isS(deg>0) = true;\n S = find(isS); \n % debug\n fprintf('Coarsening ... \\n');\n \n % Find marked nodes with local maximum degree\n [i,j] = find(triu(As(S,S),1)); % i,j and i= deg(S(j)); % compare degree of vertices\n isS(S(j(idx))) = false; % remove vertices with smaller degree \n isS(S(i(~idx))) = false; \n isC(isS) = true;\n findnode(node,isS,'noindex','Color','m');\n fprintf('Number of chosen points: %6.0u\\n',sum(isS));\n snapnow\n \n % Remove coarse nodes and neighboring nodes from undecided set\n [i,j] = find(As(:,isC)); %#ok<*NASGU>\n isF(i) = true; % neighbor of C nodes are F nodes\n isU = ~(isF | isC); % U: undecided set\n deg(~isU) = 0; % remove current C and F from the graph\n % -- No improvement by adding weight to nodes connected to F nodes --\n% degFin = sum(spones(As(isF,isU)));\n% degFin = full(degFin'); % degrer of strong connected with F points\n% deg(isU) = deg(isU) + degFin; % add weight to nodes connected to F\n \n if sum(isU) <= N0 % add small undecided nodes into C nodes\n isC(isU) = true;\n isU = []; % to exit the while loop;\n end\n % debug\n showmesh(node,elem); \n findnode(node,isU,'noindex','Color','k','MarkerSize',32)\n findnode(node,isF,'noindex','Color','y','MarkerSize',32)\n findnode(node,isC,'noindex','Color','r','MarkerSize',36); \n snapnow\n m = m + 1;\nend\nfprintf('Apply %2.0u times and Number of Coarse Nodes: %6.0u\\n',m,sum(isC));\n\n%%\n% Note that the red nodes are connected in the grid but not connected in\n% the graph of the 5-point stencil.", "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/coarsenAMGdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7718684614251966}} {"text": "function spquad_test02 ( )\n\n%*****************************************************************************80\n%\n%% SPQUAD_TEST02 reports the size of various sparse grids.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPQUAD_TEST02:\\n' );\n fprintf ( 1, ' Print out the order (number of points) used\\n' );\n fprintf ( 1, ' for sparse grids of various levels and spatial dimensions.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Dimension / Level size table for Sparse Grid Rule\\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 = 0 : 5\n fprintf ( 1, ' %2d: ', k );\n for d = 1 : 10\n [ x, w ] = spquad ( d, k );\n n = length ( w );\n fprintf ( 1, ' %6d', n );\n end\n fprintf ( 1, '\\n' );\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spquad/spquad_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7717161031063112}} {"text": "function [ err ] = baselines( Xtrain, Ytrain, Xtest, Ytest, lambda, opts)\n% Inputs\n% Xtrain: input training data\n% Ytrain: output training data\n% Xtest: input test data\n% Ytest: output test data\n% lambda: regularization parameter (for global and local models)\n% opts:\n% opts.avg: whether to compute avg or total error\n% opts.obj: 'R' for regression, 'C' for classification\n% opts.type:\n% consant - for each task, the model is the average (R) or mode (C) of the labels\n% global - concatenate data from all tasks, fit one global model\n% local - fit m separate models\n\n% Output\n% Average or total RMSE (R) or classification error (C) across tasks\n\n%% set variables\nm = length(Xtrain); % # of tasks\nd = size(Xtrain{1}, 2); % # of features\n\n%% compute baselines\nswitch opts.type\n case 'constant'\n % predict the mean output (R) or mode class (C) from training\n if(opts.obj == 'R') % regression\n if(opts.avg)\n errs = zeros(m, 1);\n for t=1:m\n pred = mean(Ytrain{t});\n errs(t) = sqrt(mean((Ytest{t} - pred).^2));\n end\n err = mean(errs);\n else\n Y_hat = cell(m,1);\n for t=1:m\n Y_hat{t} = repmat(mean(Ytrain{t}), length(Ytest{t}), 1);\n end\n Y = cell2mat(Ytest(:));\n Y_hat = cell2mat(Y_hat);\n err = sqrt(mean((Y - Y_hat).^2));\n end\n else % classification\n if(opts.avg)\n errs = zeros(m, 1);\n for t=1:m\n pred = mode(Ytrain{t});\n errs(t) = mean(pred ~= Ytest{t});\n end\n err = mean(errs);\n else\n pred = mode(opts.Ytrainactual);\n err = sum(pred ~= opts.Yactual) / length(opts.Yactual);\n end\n end\n \n case 'global'\n % compute one global model for the data\n allX = cat(1, Xtrain{:});\n allY = cat(1, Ytrain{:});\n allXtest = cat(1, Xtest{:});\n allYtest = cat(1, Ytest{:});\n if(opts.obj == 'R') % regression\n w = inv(allX' * allX + lambda * eye(d)) * allX' * allY;\n err = sqrt(mean((allYtest - allXtest * w).^2));\n else % classification\n w = simple_svm(allX, allY, lambda, opts);\n if(opts.avg)\n errs = zeros(m, 1);\n for t=1:m\n predvals = sign(Xtest{t} * w);\n errs(t) = mean(predvals ~= Ytest{t});\n end\n err = mean(errs);\n else\n predvals = sign(allXtest * w);\n err = mean(allYtest ~= predvals);\n end\n end\n \n case 'local'\n % compute m completely separate local models\n if(opts.obj == 'R') % regression\n if(opts.avg)\n errs = zeros(m,1);\n for t=1:m\n wt = inv(Xtrain{t}' * Xtrain{t} + lambda * eye(d)) * Xtrain{t}' * Ytrain{t};\n errs(t) = sqrt(mean((Ytest{t} - Xtest{t} * wt).^2));\n end\n % compute average rmse\n err = mean(errs);\n else\n Y_hat = cell(m,1);\n for t=1:m\n wt = inv(Xtrain{t}' * Xtrain{t} + lambda * eye(d)) * Xtrain{t}' * Ytrain{t};\n Y_hat{t} = Xtest{t} * wt;\n end\n % compute total rmse\n Y = cell2mat(Ytest(:));\n Y_hat = cell2mat(Y_hat);\n size(Y_hat)\n size(Y)\n err = sqrt(mean((Y - Y_hat).^2));\n end\n else % classification\n Y_hat = cell(m,1);\n for t=1:m\n wt = simple_svm(Xtrain{t}, Ytrain{t}, lambda, opts);\n Y_hat{t} = sign(Xtest{t} * wt);\n end\n if(opts.avg)\n errs = zeros(m,1);\n for t=1:m\n errs(t) = mean(Ytest{t} ~= Y_hat{t});\n end\n err = mean(errs);\n else\n Y = cell2mat(Ytest);\n Y_hat = cell2mat(Y_hat);\n err = mean(Y ~= Y_hat);\n end\n end\nend\n\nend", "meta": {"author": "gingsmith", "repo": "fmtl", "sha": "6ca7fb7b33a00ab73e8a584d3992fa96e6024438", "save_path": "github-repos/MATLAB/gingsmith-fmtl", "path": "github-repos/MATLAB/gingsmith-fmtl/fmtl-6ca7fb7b33a00ab73e8a584d3992fa96e6024438/util/baselines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7716963619842768}} {"text": "% Equalizer design example\n% \"Filter design\" lecture notes (EE364) by S. Boyd\n% (figures are generated)\n%\n% Designs a frequency-domain and time-domain FIR equalizer for\n% a single-input single-output (SISO) channel.\n%\n% Frequency-domain equalization uses a Chebychev criteria and\n% is specified in terms of frequency response functions.\n% It is a convex problem (which can be formulated as an SOCP):\n%\n% minimize max |G(w)H(w) - G_des(w)| for w in [0,pi] \n%\n% where H is the frequency response function and our variable\n% is the filter impulse response h. Function G is the unequalized\n% frequency response and G_des is the desired freq response.\n%\n% Time-domain equalization immediately designs the impulse\n% response function by specifying the problem in time (it's an LP):\n%\n% minimize max_{t neq D} |g_tilde(t)|\n% s.t. g_tilde(D) = 1\n%\n% where g_tilde is the impulse response of equalized system,\n% and D is the delay of the system.\n%\n% Written for CVX by Almir Mutapcic 02/02/06\n\n%********************************************************************\n% problem specs\n%********************************************************************\n% sample channel with impulse response g\ng =.5*[ 0.6526; 0.2157; -0.2639; 1.8024; -0.6430; ...\n 0.1096; -0.7190; 0.4206; -0.0193; 0.6603;];\n\n% problem parameters\nn = 30; % filter order\nD = 10; % overall delay\n\n%********************************************************************\n% frequency domain equalization\n%********************************************************************\n% number of freq samples (rule-of-thumb)\nm = 15*(length(g) + n);\n\nw = linspace(0,pi,m)';\nG = exp( -j*kron(w,[0:length(g)-1]) )*g;\nA = exp( -j*kron(w,[0:n-1]) );\n\n% desired frequency response is a pure delay (equalized channel)\nGdes = exp(-j*D*w);\n\n% formulate and solve the Chebyshev design problem\ncvx_begin\n variable hf(n,1)\n minimize( max( abs( G.*(A*hf) - Gdes ) ) ) \ncvx_end\n\n% check if problem was successfully solved\ndisp(['Frequency equalization problem is ' cvx_status])\nif ~strfind(cvx_status,'Solved')\n return\nend\n\n%********************************************************************\n% time-domain equalization\n%********************************************************************\n% define the convolution matrix\nTconv = toeplitz([g; zeros(n-1,1)],[g(1) zeros(1,n-1)]);\n\n% create array of all times without t=D\ntimes_not_D = [1:D D+2:size(Tconv,1)];\n\n% formulate and solve the time equalization problem\ncvx_begin\n variable t\n variable ht(n,1)\n\n minimize( max( abs( Tconv(times_not_D,:)*ht ) ) )\n subject to\n Tconv(D+1,:)*ht == 1;\ncvx_end\n\n% check if problem was successfully solved\nif ~strfind(cvx_status,'Solved')\n disp(['Frequency equalization problem is ' cvx_status])\n return\nend\n\n%********************************************************************\n% equalizer plots\n%********************************************************************\n% plot g\nfigure(1)\nplot([0:length(g)-1],g,'o',[0:length(g)-1],g,'b:')\nxlabel('t')\nylabel('g(t)')\n\nfigure(2)\nH = exp(-j*kron(w,[0:length(g)-1]))*g;\n% magnitude\nsubplot(2,1,1);\nplot(w,20*log10(abs(H)))\naxis([0,pi,-20,20])\nxlabel('w')\nylabel('mag G(w) in dB')\n% phase\nsubplot(2,1,2)\nplot(w,angle(H))\naxis([0,pi,-pi,pi])\nxlabel('w')\nylabel('phase G(w)')\n\n% freq equalizer\nfigure(3)\nplot([0:n-1],hf,'o',[0:n-1],hf,'b:')\nxlabel('t')\nylabel('h(t)')\n\n% plot g_tilde\nfigure(4)\ngt=conv(g,hf);\nplot([1:length(gt)]-1,gt,'o',[1:length(gt)]-1,gt,'b:')\nxlabel('t')\nylabel('g tilde(t)')\naxis([0,length(gt)-1,-.2 1.2])\n\nfigure(5)\nH = exp(-j*kron(w,[0:length(gt)-1]))*gt;\n% amplitude\nsubplot(2,1,1)\nplot(w,20*log10(abs(H)))\naxis([0,pi,-20,20])\nxlabel('w')\nylabel('mag G tilde(w) in dB')\n% phase\nsubplot(2,1,2)\nplot(w,angle(H))\naxis([0,pi,-pi,pi])\nxlabel('w')\nylabel('phase G tilde(w)')\n\n% time equalizer\nfigure(6)\nplot([0:n-1],ht,'o',[0:n-1],ht,'b:')\nxlabel('t')\nylabel('h(t)')\n\n% plot g_tilde\nfigure(7)\ngt=conv(g,ht);\nplot([1:length(gt)]-1,gt,'o',[1:length(gt)]-1,gt,'b:')\nxlabel('t')\nylabel('g tilde(t)')\n\nfigure(8)\nH = exp(-j*kron(w,[0:length(gt)-1]))*gt;\n% magnitude\nsubplot(2,1,1)\nplot(w,20*log10(abs(H)))\naxis([0,pi,-20,20])\nxlabel('w')\nylabel('mag G tilde(w) in dB')\n% phase\nsubplot(2,1,2)\nplot(w,angle(H))\naxis([0,pi,-pi,pi])\nxlabel('w')\nylabel('phase G tilde(w)')\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/filter_design/equalizer_design.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7716782650198756}} {"text": "function [ n_data, x, fx ] = gud_values ( n_data )\n\n%*****************************************************************************80\n%\n%% GUD_VALUES returns some values of the Gudermannian function.\n%\n% Discussion:\n%\n% The Gudermannian function relates the hyperbolic and trigonomentric\n% functions. For any argument X, there is a corresponding value\n% GD so that\n%\n% SINH(X) = TAN(GD).\n%\n% This value GD is called the Gudermannian of X and symbolized\n% GD(X). The inverse Gudermannian function is given as input a value \n% GD and computes the corresponding value X.\n%\n% GD(X) = 2 * arctan ( exp ( X ) ) - PI / 2\n%\n% In Mathematica, the function can be evaluated by:\n%\n% 2 * Atan[Exp[x]] - Pi/2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 13;\n\n fx_vec = [ ...\n -0.1301760336046015E+01, ...\n -0.8657694832396586E+00, ...\n 0.0000000000000000E+00, ...\n 0.9983374879348662E-01, ...\n 0.1986798470079397E+00, ...\n 0.4803810791337294E+00, ...\n 0.8657694832396586E+00, ...\n 0.1131728345250509E+01, ...\n 0.1301760336046015E+01, ...\n 0.1406993568936154E+01, ...\n 0.1471304341117193E+01, ...\n 0.1510419907545700E+01, ...\n 0.1534169144334733E+01 ];\n\n x_vec = [ ...\n -2.0E+00, ...\n -1.0E+00, ...\n 0.0E+00, ...\n 0.1E+00, ...\n 0.2E+00, ...\n 0.5E+00, ...\n 1.0E+00, ...\n 1.5E+00, ...\n 2.0E+00, ...\n 2.5E+00, ...\n 3.0E+00, ...\n 3.5E+00, ...\n 4.0E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/gud_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7716163930097136}} {"text": "function x = simplex_grid_index_to_point ( m, n, ng, g, v )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_GRID_INDEX_TO_POINT returns points corresponding to simplex indices.\n%\n% Discussion:\n%\n% The M-dimensional simplex is defined by M+1 vertices.\n%\n% Given a regular grid that uses N subintervals along the edge between\n% each pair of vertices, a simplex grid index G is a set of M+1 values\n% each between 0 and N, and summing to N. \n%\n% This function determines the coordinates X of the point corresponding\n% to the index G.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of subintervals.\n%\n% Input, integer NG, the number of grid indices to be converted.\n%\n% Input, integer G(M+1,NG), the grid indices of 1 or more points.\n%\n% Input, real V(M,M+1), the coordinates of the vertices of the simplex.\n%\n% Output, real X(M,NG), the coordinates of one or more points.\n%\n x = v(1:m,1:m+1) * g(1:m+1,1:ng) / 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/simplex_grid/simplex_grid_index_to_point.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7715718083856727}} {"text": "function z = round2(x,y)\n%ROUND2 rounds number to nearest multiple of arbitrary precision.\n% Z = ROUND2(X,Y) rounds X to nearest multiple of Y.\n%\n%Example 1: round PI to 2 decimal places\n% >> round2(pi,0.01)\n% ans =\n% 3.14\n%\n%Example 2: round PI to 4 decimal places\n% >> round2(pi,1e-4)\n% ans =\n% 3.1416\n%\n%Example 3: round PI to 8-bit fraction\n% >> round2(pi,2^-8)\n% ans =\n% 3.1406\n%\n%Examples 4-6: round PI to other multiples\n% >> round2(pi,0.05)\n% ans =\n% 3.15\n% >> round2(pi,2)\n% ans =\n% 4\n% >> round2(pi,5)\n% ans =\n% 5 \n%\n% See also ROUND.\n\n%% defensive programming\nerror(nargchk(2,2,nargin))\nerror(nargoutchk(0,1,nargout))\nif numel(y)>1\n error('Y must be scalar')\nend\n\n%%\nz = round(x/y)*y;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4261-round2/round2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.7714308925467523}} {"text": "function featureVector = gaborFeatures(img,gaborArray,d1,d2)\n\n% GABORFEATURES extracts the Gabor features of an input image.\n% It creates a column vector, consisting of the Gabor features of the input\n% image. The feature vectors are normalized to zero mean and unit variance.\n%\n%\n% Inputs:\n% img :\tMatrix of the input image \n% gaborArray\t:\tGabor filters bank created by the function gaborFilterBank\n% d1 :\tThe factor of downsampling along rows.\n% d2 :\tThe factor of downsampling along columns.\n% \n% Output:\n% featureVector\t: A column vector with length (m*n*u*v)/(d1*d2). \n% This vector is the Gabor feature vector of an \n% m by n image. u is the number of scales and\n% v is the number of orientations in 'gaborArray'.\n%\n%\n% Sample use:\n% \n% img = imread('cameraman.tif');\n% gaborArray = gaborFilterBank(5,8,39,39); % Generates the Gabor filter bank\n% featureVector = gaborFeatures(img,gaborArray,4,4); % Extracts Gabor feature vector, 'featureVector', from the image, 'img'.\n% \n% \n% \n% Details can be found in:\n% \n% M. Haghighat, S. Zonouz, M. Abdel-Mottaleb, \"CloudID: Trustworthy \n% cloud-based and cross-enterprise biometric identification,\" \n% Expert Systems with Applications, vol. 42, no. 21, pp. 7905-7916, 2015.\n% \n% \n% \n% (C)\tMohammad Haghighat, University of Miami\n% haghighat@ieee.org\n% PLEASE CITE THE ABOVE PAPER IF YOU USE THIS CODE.\n\n\nif (nargin ~= 4) % Check correct number of arguments\n error('Please use the correct number of input arguments!')\nend\n\nif size(img,3) == 3 % Check if the input image is grayscale\n warning('The input RGB image is converted to grayscale!')\n img = rgb2gray(img);\nend\n\nimg = double(img);\n\n\n%% Filter the image using the Gabor filter bank\n\n% Filter input image by each Gabor filter\n[u,v] = size(gaborArray);\ngaborResult = cell(u,v);\nfor i = 1:u\n for j = 1:v\n gaborResult{i,j} = imfilter(img, gaborArray{i,j});\n end\nend\n\n\n%% Create feature vector\n\n% Extract feature vector from input image\nfeatureVector = [];\nfor i = 1:u\n for j = 1:v\n \n gaborAbs = abs(gaborResult{i,j});\n gaborAbs = downsample(gaborAbs,d1);\n gaborAbs = downsample(gaborAbs.',d2);\n gaborAbs = gaborAbs(:);\n \n % Normalized to zero mean and unit variance. (if not applicable, please comment this line)\n gaborAbs = (gaborAbs-mean(gaborAbs))/std(gaborAbs,1);\n \n featureVector = [featureVector; gaborAbs];\n \n end\nend\n\n\n%% Show filtered images (Please comment this section if not needed!)\n\n% % Show real parts of Gabor-filtered images\n% figure('NumberTitle','Off','Name','Real parts of Gabor filters');\n% for i = 1:u\n% for j = 1:v \n% subplot(u,v,(i-1)*v+j) \n% imshow(real(gaborResult{i,j}),[]);\n% end\n% end\n% \n% % Show magnitudes of Gabor-filtered images\n% figure('NumberTitle','Off','Name','Magnitudes of Gabor filters');\n% for i = 1:u\n% for j = 1:v \n% subplot(u,v,(i-1)*v+j) \n% imshow(abs(gaborResult{i,j}),[]);\n% end\n% end\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/特征提取算法/gabor-master/gaborFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7714308840193809}} {"text": "function area = disk01_area ( )\n\n%*****************************************************************************80\n%\n%% DISK01_AREA returns the area of the unit disk.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real AREA, the area of the unit disk.\n%\n r = 1.0;\n area = pi * r * r;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/disk_integrals/disk01_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.7714308728287216}} {"text": "function mc1 = moc1 ( a, b, n, f )\n\n%*****************************************************************************80\n%\n%% MOC1 estimates a function related to the modulus of continuity.\n%\n% Discussion;\n%\n% The modulus of continuity function MC(T) for a function F(X) over an \n% interval [A,B] is defined as\n%\n% MC(T) = max | F(X+DX) - F(X) | for 0 <= DX <= T, and X and X+DX in [A,B].\n%\n% If we define the simpler function\n%\n% MC1(DX) = max | F(X+DX) - F(X) | for 0 <= DX, and X and X+DX in [A,B],\n%\n% then we can evaluate MC(T) as\n%\n% MC(T) = max ( MC1(DX) ), for DX <= T.\n%\n% This function estimates the MC1 function based on a discrete\n% set of data at N equally spaced points in the interval [A,B].\n% \n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the left and right endpoints of the interval.\n%\n% Input, integer N, the number of equally spaced sample points.\n%\n% Input, function F(x), a handle to the function.\n%\n% Output, real MC1(N), the maximum difference |F(X+DX)-F(X)| estimated at \n% DX = 0 exactly, H exactly, 2*H exactly, ..., (N-1)*H exactly.\n%\n if ( nargin < 1 )\n a = 0.0;\n end\n\n if ( nargin < 2 )\n b = a + 1.0;\n end\n\n if ( nargin < 3 )\n n = 501;\n end\n%\n% Set the evaluation points, and evaluate the function.\n%\n x = linspace ( a, b, n );\n fx = f ( x );\n%\n% Compute the maximum difference with a separation of 0*H, 1*H, 2*H, \n% ..., (N-1)*H.\n%\n mc1 = zeros ( n, 1 );\n for i = 0 : n - 1\n mc1(i+1) = max ( abs ( fx(1+i:n) - fx(1:n-i) ) );\n end\n\n return\nend\n ", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/moc_display/moc1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7713906369916471}} {"text": "function solution = optimalConservationVectors(S, lambda, delta)\n% DC programming for solving the cardinality optimization problem\n%\n% .. math::\n%\n% min ~& \\lambda ||x||_0 - \\delta ||y||_0 \\\\\n% s.t. ~& x + S^T y = 0 \\\\\n% ~& 0 \\leq y \\leq 1e4\n%\n% USAGE:\n%\n% solution = optimalConservationVectors(S, lambda, delta)\n%\n% INPUT:\n% S: `m` x `n` stoichiometric matrix\n%\n% OPTIONAL INPUTS:\n% lambda: default = 1\n% delta: default = 1\n%\n% OUTPUT:\n% solution: result of the solved cardinality optimization problem\n\nif ~exist('lambda','var')\n lambda=1;\nend\nif ~exist('delta','var')\n delta=1;\nend\n\n[mlt,nlt]=size(S');\nprob.p=mlt;\nprob.q=nlt;\nprob.r=0;\nprob.c=zeros(nlt+mlt,1);\nprob.A=[speye(mlt,mlt),S'];\nprob.b=zeros(mlt,1);\nprob.lb=[-inf*ones(mlt,1);zeros(nlt,1)];\nprob.ub=[inf*ones(nlt,1);1e4*ones(mlt,1)];\nprob.csense(1:mlt,1)='E';\nparams.lamda=lambda;\nparams.delta=delta;\nsolution = optimizeCardinality(prob,params);\n% DC programming for solving the cardinality optimization problem\n% The l0 norm is approximated by capped-l1 function.\n% min c'(x,y,z) + lambda*||x||_0 - delta*||y||_0\n% s.t. A*(x,y,z) <= b\n% l <= (x,y,z) <=u\n% x in R^p, y in R^q, z in R^r\n%\n% solution = optimizeCardinality(problem,params)\n%\n% problem Structure containing the following fields describing the problem\n% p size of vector x\n% q size of vector y\n% r size of vector z\n% c (p+q+r) x 1 linear objective function vector\n% lambda trade-off parameter of ||x||_0\n% delta trade-off parameter of ||y||_0\n% A s x (p+q+r) LHS matrix\n% b s x 1 RHS vector\n% csense s x 1 Constraint senses, a string containting the constraint sense for\n% each row in A ('E', equality, 'G' greater than, 'L' less than).\n% lb (p+q+r) x 1 Lower bound vector\n% ub (p+q+r) x 1 Upper bound vector\n%\n% OPTIONAL INPUTS\n% params parameters structure\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 = 2)\n%\n% OUTPUT\n% solution Structure containing the following fields\n% x p x 1 solution vector\n% y q x 1 solution vector\n% z r x 1 solution vector\n% stat status\n% 1 = Solution found\n% 2 = Unbounded\n% 0 = Infeasible\n% -1= Invalid input\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/modelGeneration/stoichConsistency/optimalConservationVectors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384733, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7713472494011645}} {"text": "function y = geo_lpdf(x,p)\n%GEO_LPDF Geometric log probability density function (lpdf).\n% Y = GEO_LPDF(X,P) returns the log of geometric pdf with probability, P, \n% at the values in X.\n%\n% The size of Y is the common size of X and P. A scalar input \n% functions as a constant matrix of the same size as the other input. \n%\n% Copyright (c) 1999-2000 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\ny = log(p) + log(1-p) * x;\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/geo_lpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7713472493442484}} {"text": "function [pp, mse] = fitSpline(tData, xData, tKnot)\n% pp = fitSpline(tData, xData, tGrid)\n%\n% Fits a piece-wise cubic spline to {tData, xData} using the\n% knot-points in tKnot.\n%\n% INPUTS:\n% tData = [1,nData] = time stamps for data (uniform spacing, monotonic!)\n% xData = [nFunc,nData] = function value at each time\n% tKnot = [1,nKnot] = time for each knot point (monotonic!)\n% \n% OUTPUTS:\n% pp = struct to be evaluated by Matlab's ppval command\n% \n% NOTES: (strongly suggested)\n% \n% tData([1,end]) == tKnot([1,end]) \n%\n\nnFunc = size(xData,1);\nnKnot = length(tKnot);\n\nxGuess = interp1(tData',xData',tKnot')';\n\n%Numerically estimate the local slope\nvData = zeros(size(xData));\nfor i=1:nFunc\nvData(i,:) = diffCenter(xData(i,:),mean(diff(tData)));\nend\n\nvGuess = interp1(tData',vData',tKnot')';\nzGuess = reshape([xGuess;vGuess],2*nFunc*nKnot,1);\noptions = optimoptions('fminunc',...\n 'MaxFunEvals',200*length(zGuess),...\n 'Display','off',...\n 'Algorithm','quasi-newton');\n\nobjFun = @(z)checkFit(z,tData,xData,tKnot,nFunc,nKnot);\nzSoln = fminunc(objFun,zGuess,options);\n\n% Check the solution and return the answer:\n[mse, pp] = checkFit(zSoln,tData,xData,tKnot,nFunc,nKnot);\n\nend\n\n\n\nfunction [mse, pp] = checkFit(z,tData,xData,tKnot,nFunc,nKnot)\n\nzKnot = reshape(z,2*nFunc,nKnot);\nxKnot = zKnot(1:nFunc,:);\nvKnot = zKnot((nFunc+1):end,:);\n\npp = pwch(tKnot,xKnot,vKnot);\nxFit = ppval(pp,tData);\nmse = sum(mean((xFit-xData).^2));\n\nend\n\n\nfunction dx = diffCenter(x,dt)\n% dx = diffCenter(x,dt)\n%\n% Computes the second-order finite difference approximation of x with\n% respect to t. A one-sided second order difference is used at the end\n% points, so size(dx) == size(x).\n%\n% INPUTS:\n% x = [1 x n] vector of function values \n% dt = sampling period of x (default = 1)\n%\n% OUTPUTS:\n% d = dx/dt = first derivative of x wrt t\n%\n% See also: cumInt, diff\n\nif nargin == 1\n dt = 1;\nend\n\nif length(dt) ~= 1\n error('Time-step (dt) must be a scalar');\nend\n\nn = length(x);\nif n < 2\n error('length(x) must be at least 2');\nelseif n == 2\n dx = diff(x)/dt;\nelse %Then enough points for second-order finite difference\n dx = zeros(size(x));\n Dx = diff(x); %Matlab first-order finite difference\n dx(1) = (-3*x(1) + 4*x(2) - x(3))/(2*dt);\n dx(2:(end-1)) = (Dx(1:(end-1)) + Dx(2:end))/(2*dt); %Mid-points are easy\n dx(end) = (x(end-2) - 4*x(end-1) + 3*x(end))/(2*dt);\nend\n\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/pwPoly/fitSpline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7713472479262105}} {"text": "\n% Fast computation of the vector q defined by \n% q_k = \\sum_{l = 1}^{N_y} G(X_k - Y_l) f_l, k = 1 .. Nx\n% Using the \"Efficient Bessel Decomposition\"\n% Code developped by Martin Averseng\n% See also SCSD method by François Alouges and Matthieu Aussal. \n\n\naddpath(genpath(pwd)); % Add folders of the toolbox to the path. \nclear all;%#ok\nclose all;\nclc;\n\n\nNx = 10^4;\nNy = 10^4;\nfprintf('10^%s x 10^%s cloud of points \\n \\n',num2str(round(log(Nx)/log(10))),num2str(round(log(Ny)/log(10))))\n% Data points\nX = uniformCircle([0,0],1,Nx);\nY = X; %uniformCircle([0,0],1,Ny)+0.5; %uniformDisk([0.2,0],1,Ny);\nf = rand(size(Y,1),1); % Vector f\n\n% Parameter for rescaling\nrMax = rMaxCalc(X,Y);\n\n\n% Kernel choice:\n\n% G = LogKernel; % G(x) = log(x)\n\nG = Y0Kernel(0.3); % G(x) = Y0(0.3*x) => Bessel decomposition with Robin \n% conditions. \n\n% G = 3*Y0Kernel(4); % G(x) = Y0(2*x) => Method of rescaling to a root of Y0\n\n% G = H0Kernel(1000); % G(x) = Y0(1000*x) => Selects frequencies near 0 and 1000\n\n\n% G = Kernel(@(r)(exp(-r.^2)),@(r)(-2*r.*exp(-r.^2))); % Arbitrary (smooth)\n% kernel\n\n% G = Kernel(@(r)(1./r.^2 ),@(r)(-2./r.^3)); % Arbitrary (singular) kernel\n\n\n% Choice of the cutoff parameter. \nlambda = 3;\na = lambda/sqrt(sqrt(Nx*Ny)); %this value is of the order of the optimal \n% value for data uniformly distributed in a disk. Choose lambda by trial\n% and error to minimize the online time.\n\ntol = 1e-3; % input tolerance\n\n% Offline computations.\ngradOpt = true;\ntimeOff = tic;\n[dxGxy,dyGxy,rq,loc] = offline_dEBD(G,X,Y,a,tol); \ntimeOff = toc(timeOff);\nfprintf('Offline computations performed in \\n %s seconds \\n',num2str(timeOff))\n% show the radial quadrature : \n% rq.showDer;\n\n% Online procedure.\ntimeOn = tic;\nqx = dxGxy(f);\nqy = dyGxy(f);\ntimeOn = toc(timeOn);\nfprintf('Online products computed in \\n %s seconds \\n',num2str(timeOn))\n\n% Error on first entry of q \ndist = sqrt((X(1,1) - Y(:,1)).^2 + (X(1,2) - Y(:,2)).^2);\ndistInv = 1./dist;\ndistInv(dist<1e-12) = 0;\nY_X_x = (Y(:,1) - X(1,1));\nY_X_y = (Y(:,2) - X(1,2));\nqvalx = sum((G.evalDer(dist).*Y_X_x.*distInv).*f);\nqvaly = sum((G.evalDer(dist).*Y_X_y.*distInv).*f);\ndisp('error on first entry');\ndisp(abs(qvalx - qx(1))/(norm(qx,1)));\ndisp(abs(qvaly - qy(1))/(norm(qy,1)));\n\n% Error when f = [1 0 0 ... 0]\ndist = sqrt((Y(1,1) - X(:,1)).^2 + (Y(1,2) - X(:,2)).^2);\ndistInv = 1./dist;\ndistInv(dist < 1e-12) = 0;\nY_X_x = (Y(1,1) - X(:,1));\nY_X_y = (Y(1,2) - X(:,2));\nqvalx = (G.evalDer(dist).*Y_X_x.*distInv);\nqvaly = (G.evalDer(dist).*Y_X_y.*distInv);\nf = [1; zeros(size(Y,1)-1,1)];\n\nqx = dxGxy(f);\nqy = dyGxy(f); \n\nfprintf('Linf error for f = [1 0 0 ... 0] \\n (effective error / target accuracy) \\n');\nfprintf('%s / %s \\n\\n',num2str(max(abs(qvalx - qx))),num2str(tol))\nfprintf('%s / %s \\n\\n',num2str(max(abs(qvaly - qy))),num2str(tol))\n\ndisp('Done');\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/openEbd/DemoGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7713438263553914}} {"text": "function determ = minij_determinant ( n )\n\n%*****************************************************************************80\n%\n%% MINIJ_DETERMINANT returns the determinant of the MINIJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n determ = 1.0;\n\n for i = 1 : n\n angle = ( 2 * i - 1 ) * pi / ( 2 * n + 1 );\n determ = determ * 0.5 / ( 1.0 - cos ( angle ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/minij_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7713344394136457}} {"text": "function dms=rad2dms(rad)\n% RAD2DMS Converts radians to degrees-minutes-seconds. Vectorized.\n% Version: 12 Mar 00\n% Useage: dms=rad2dms(rad)\n% Input: rad - vector of angles in radians\n% Output: dms - [d m s] array of angles in deg-min-sec, where\n% d = vector of degrees\n% m = vector of minutes\n% s = vector of seconds\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nd=abs(rad).*180/pi;\nid=floor(d);\nrm=(d-id).*60;\nim=floor(rm);\ns=(rm-im).*60;\n\n%if rad<0\n% if id==0\n% if im==0\n% s = -s;\n% else\n% im = -im;\n% end\n% else\n% id = -id;\n% end\n%end\n\nind=(rad<0 & id~=0);\nid(ind)=-id(ind);\n\nind=(rad<0 & id==0 & im~=0);\nim(ind)=-im(ind);\n\nind=(rad<0 & id==0 & im==0);\ns(ind)=-s(ind);\n\ndms=[id im 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/15285-geodetic-toolbox/geodetic/rad2dms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7713344372379032}} {"text": "% Detecting a small subset of infeasible linear inequalities\n% Section 5.8, Boyd & Vandenberghe \"Convex Optimization\"\n% Written for CVX by Almir Mutapcic - 02/18/06\n%\n% We consider a set of linear inequalities A*x <= b which are\n% infeasible. Here A is a matrix in R^(m-by-n) and b belongs\n% to R^m. We apply a l1-norm heuristic to find a small subset\n% of mutually infeasible inequalities from a larger set of\n% infeasible inequalities. The heuristic finds a sparse solution\n% to the alternative inequality system.\n%\n% Original system is A*x <= b and it alternative ineq. system is:\n%\n% lambda >= 0, A'*lambda == 0. b'*lambda < 0\n%\n% where lambda in R^m. We apply the l1-norm heuristic:\n%\n% minimize sum( lambda )\n% s.t. A'*lambda == 0\n% b'*lambda == -1\n% lambda >= 0\n%\n% Positive lambdas gives us a small subset of inequalities from\n% the original set which are mutually inconsistent.\n\n% problem dimensions (m inequalities in n-dimensional space)\nm = 150;\nn = 10;\n\n% fix random number generator so we can repeat the experiment\nseed = 0;\nrandn('state',seed);\n\n% construct infeasible inequalities\nA = randn(m,n);\nb = randn(m,1);\n\nfprintf(1, ['Starting with an infeasible set of %d inequalities ' ...\n 'in %d variables.\\n'],m,n);\n\n% you can verify that the set is infeasible\n% cvx_begin\n% variable x(n)\n% A*x <= b;\n% cvx_end\n\n% solve the l1-norm heuristic problem applied to the alternative system\ncvx_begin\n variables lambda(m)\n minimize( sum( lambda ) )\n subject to\n A'*lambda == 0;\n b'*lambda == -1; \n lambda >= 0;\ncvx_end\n\n% report the smaller set of mutually inconsistent inequalities\ninfeas_set = find( abs(b.*lambda) > sqrt(eps)/n );\ndisp(' ');\nfprintf(1,'Found a smaller set of %d mutually inconsistent inequalities.\\n',...\n length(infeas_set));\ndisp(' ');\ndisp('A smaller set of mutually inconsistent inequalities are the ones');\ndisp('with row indices:'), infeas_set'\n\n% check that this set is infeasible\n% cvx_begin\n% variable x_infeas(n)\n% A(infeas_set,:)*x_infeas <= b(infeas_set);\n% cvx_end\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/sparse_heuristics/sparse_infeas_dual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7712929649987722}} {"text": "function res = glp(im,thresh)\n\n% inputs\n% im is the fourier transform of the image\n% thresh is the cutoff circle radius\n\n%outputs\n% res is the filtered image\n\n[r,c]=size(im);\nd0=thresh;\n\nd=zeros(r,c);\nh=zeros(r,c);\n\nfor i=1:r\n for j=1:c\n d(i,j)= sqrt( (i-(r/2))^2 + (j-(c/2))^2);\n end\nend\n\nfor i=1:r\n for j=1:c\n h(i,j)= exp ( -( (d(i,j)^2)/(2*(d0^2)) ) );\n end\nend\n\n\nfor i=1:r\n for j=1:c\n res(i,j)=(h(i,j))*im(i,j);\n\n end\nend\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40579-frequency-domain-filtering-for-grayscale-images/freqfilters/glp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.930458263207691, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7712929599641298}} {"text": "function test_rosenbrock()\n\n clc;\n clear;\n close all;\n\n \n %% Set algorithms\n if 0\n algorithms = gd_solver_list('ALL'); \n else\n algorithms = gd_solver_list('NCG'); \n end\n \n \n % initialize\n d = 2;\n w_init = zeros(d,1);\n \n \n %% define problem definitions\n problem = rosenbrock(d);\n \n \n % obtain optimal solution\n w_opt = problem.calc_solution(); \n f_opt = problem.cost(w_opt); \n fprintf('f_opt: %.24e\\n', f_opt); \n\n \n % initialize\n w_list = cell(1); \n info_list = cell(1);\n \n \n %% perform algorithms\n for alg_idx=1:length(algorithms)\n fprintf('\\n\\n### [%02d] %s ###\\n\\n', alg_idx, algorithms{alg_idx});\n \n clear options;\n % general options for optimization algorithms \n options.w_init = w_init;\n options.tol_gnorm = 1e-10;\n options.max_iter = 100;\n options.verbose = true; \n options.f_opt = f_opt; \n options.store_w = true;\n\n switch algorithms{alg_idx}\n case {'SD-STD'}\n \n options.step_alg = 'fix';\n options.step_init = 1;\n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);\n\n case {'SD-BKT'}\n \n options.step_alg = 'backtracking';\n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);\n\n case {'SD-EXACT'}\n \n options.step_alg = 'exact'; \n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);\n \n case {'SD-WOLFE'}\n \n options.step_alg = 'strong_wolfe';\n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options); \n \n case {'SD-SCALE-EXACT'}\n \n options.sub_mode = 'SCALING';\n options.step_alg = 'exact'; \n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);\n \n case {'Newton-STD'}\n \n [w_list{alg_idx}, info_list{alg_idx}] = newton(problem, options);\n \n case {'Newton-DAMP'}\n\n options.sub_mode = 'DAMPED'; \n options.step_alg = 'backtracking';\n [w_list{alg_idx}, info_list{alg_idx}] = newton(problem, options);\n \n case {'Newton-CHOLESKY'}\n\n options.sub_mode = 'CHOLESKY'; \n options.step_alg = 'backtracking';\n [w_list{alg_idx}, info_list{alg_idx}] = newton(problem, options); \n\n case {'CG-PRELIM'}\n \n options.sub_mode = 'PRELIM';\n options.step_alg = 'exact'; \n %options.beta_alg = 'PR';\n [w_list{alg_idx}, info_list{alg_idx}] = cg(problem, options);\n \n case {'CG-BKT'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'backtracking'; \n %options.beta_alg = 'PR'; \n [w_list{alg_idx}, info_list{alg_idx}] = cg(problem, options);\n \n case {'CG-EXACT'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'exact'; \n %options.beta_alg = 'PR'; \n [w_list{alg_idx}, info_list{alg_idx}] = cg(problem, options);\n \n case {'CG-PRECON-EXACT'}\n \n options.sub_mode = 'PRECON';\n % diagonal scaling\n options.M = diag(diag(A)); \n options.step_alg = 'exact'; \n options.beta_alg = 'PR'; \n \n [w_list{alg_idx}, info_list{alg_idx}] = cg(problem, options); \n \n case {'NCG-PR-BTK'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'backtracking'; \n options.beta_alg = 'PR'; \n [w_list{alg_idx}, info_list{alg_idx}] = ncg(problem, options); \n \n case {'NCG-PR-WOLFE'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'strong_wolfe'; \n options.beta_alg = 'PR'; \n [w_list{alg_idx}, info_list{alg_idx}] = ncg(problem, options); \n \n \n case {'NCG-FR-BTK'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'backtracking'; \n options.beta_alg = 'FR'; \n [w_list{alg_idx}, info_list{alg_idx}] = ncg(problem, options); \n \n case {'NCG-FR-WOLFE'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'strong_wolfe'; \n options.beta_alg = 'FR'; \n [w_list{alg_idx}, info_list{alg_idx}] = ncg(problem, options); \n \n case {'BFGS-H-BKT'}\n \n options.step_alg = 'backtracking'; \n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options);\n \n case {'BFGS-H-EXACT'}\n \n options.step_alg = 'exact'; \n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options);\n \n case {'BFGS-B-BKT'}\n \n options.step_alg = 'backtracking'; \n options.update_mode = 'B';\n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options);\n \n case {'BFGS-B-EXACT'}\n \n options.step_alg = 'exact'; \n options.update_mode = 'B'; \n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options); \n \n case {'DAMPED-BFGS-BKT'}\n \n options.step_alg = 'backtracking'; \n options.update_mode = 'Damping';\n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options);\n \n case {'DAMPED-BFGS-EXACT'}\n \n options.step_alg = 'exact'; \n options.update_mode = 'Damping'; \n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options); \n \n case {'L-BFGS-BKT'}\n \n options.step_alg = 'backtracking'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options);\n \n case {'L-BFGS-EXACT'}\n \n options.step_alg = 'exact'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options); \n \n case {'L-BFGS-WOLFE'}\n \n options.step_alg = 'strong_wolfe'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options); \n \n case {'BB'}\n \n options.step_alg = 'exact'; \n [w_list{alg_idx}, info_list{alg_idx}] = bb(problem, options); \n \n case {'SGD'} \n\n options.batch_size = 1;\n options.step = 0.1 * options.batch_size;\n %options.step_alg = 'decay';\n options.step_alg = 'fix';\n\n [w_list{alg_idx}, info_list{alg_idx}] = sgd(problem, options); \n \n otherwise\n warn_str = [algorithms{alg_idx}, ' is not supported.'];\n warning(warn_str);\n w_list{alg_idx} = '';\n info_list{alg_idx} = ''; \n end\n \n end\n \n \n %% plot all\n close all;\n \n % display iter vs cost/gnorm\n display_graph('iter','cost', algorithms, w_list, info_list);\n display_graph('iter','gnorm', algorithms, w_list, info_list); \n \n % draw convergence sequence\n w_history = cell(1);\n cost_history = cell(1); \n for alg_idx=1:length(algorithms) \n w_history{alg_idx} = info_list{alg_idx}.w;\n cost_history{alg_idx} = info_list{alg_idx}.cost;\n end \n draw_convergence_sequence(problem, w_opt, algorithms, w_history, cost_history); \n\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/gd_test/test_rosenbrock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7712929598357208}} {"text": "function p4 = angle_half ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% ANGLE_HALF finds half an angle.\n%\n% Discussion:\n%\n% The original angle is defined by the sequence of points P1, P2 and P3.\n%\n% The point P4 is calculated so that:\n%\n% (P1,P2,P4) = (P1,P2,P3) / 2\n%\n% P1\n% /\n% / P4\n% / .\n% / .\n% P2--------->P3\n%\n% Thanks to Cesar Fraga Bobis for pointing out a typographical error in\n% a previous version of this routine.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), P3(2,1), points defining the angle.\n%\n% Input, real P4(2,1), a point defining the half angle.\n% The vector P4 - P2 will have unit norm.\n%\n p4(1:2,1) = 0.5 * ( ...\n ( p1(1:2,1) - p2(1:2,1) ) / sqrt ( sum ( ( p1(1:2,1) - p2(1:2,1) ).^2 ) ) ...\n + ( p3(1:2,1) - p2(1:2,1) ) / sqrt ( sum ( ( p3(1:2,1) - p2(1:2,1) ).^2 ) ) );\n\n p4(1:2,1) = p2(1:2,1) + p4(1:2,1) / sqrt ( sum ( ( p4(1:2,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polygon_properties/angle_half.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7712790725330525}} {"text": "function xBnd = SmoothBnd(x,alpha,Bnd)\n%\n% xBnd = SmoothBnd(x,alpha,Bnd)\n%\n% This function is used to smoothly bound the input x;\n% \n% INPUTS:\n% x = a vector of real numbers to apply bounds\n% alpha = a positive smoothing parameter. Small values correspond to\n% little smoothing\n% Bnd = the desired bounds of the function, expressed as a 2-element row\n% vector. If ommitted it will default to [0,1];\n%\n% Written by Matthew Kelly\n% October 2013\n% Cornell University\n%\n\nif nargin==2\n Low = 0;\n Upp = 1;\nelse\n Low = Bnd(1);\n Upp = Bnd(2);\nend\n\ninfTest1 = exp(max(x-Low)/alpha);\ninfTest2 = exp(max(-(x-Upp))/alpha);\n\nif isinf(infTest1) || isinf(infTest2) %Then there is a sharp transition\n xBnd = x;\n xBnd(xUpp) = Upp;\nelse\n %Apply bounding to each part of the input:\n xLow = Low + alpha*log(exp((x-Low)/alpha)+1);\n xUpp = Upp - alpha*log(exp(-(x-Upp)/alpha)+1);\n \n %Combine:\n xBnd = xLow + xUpp - x;\nend\n\nend\n\n ", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/smoothing/exponentialSmoothing/SmoothBnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7712790539543746}} {"text": "function pdf = coupon_complete_pdf ( type_num, box_num )\n\n%*****************************************************************************80\n%\n%% COUPON_COMPLETE_PDF evaluates the Complete Coupon Collection PDF.\n%\n% Discussion:\n%\n% PDF(TYPE_NUM;BOX_NUM) is the probability that, given an inexhaustible \n% supply of boxes, inside each of which there is one of TYPE_NUM distinct\n% coupons, which are uniformly distributed among the boxes, that it will \n% require opening exactly BOX_NUM boxes to achieve at least one of each\n% kind of coupon.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 August 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Herbert Wilf,\n% Some New Aspects of the Coupon Collector's Problem,\n% SIAM Review,\n% Volume 48, Number 3, September 2006, pages 549-565.\n%\n% Parameters:\n%\n% Input, integer BOX_NUM, the number of boxes that had to be opened\n% in order to just get at least one of each coupon.\n% 0 <= BOX_NUM. If BOX_NUM < TYPE_NUM, then PDF is surely 0.\n%\n% Input, integer TYPE_NUM, the number of distinct coupons.\n% 1 <= TYPE_NUM.\n%\n% Output, real PDF, the value of the PDF.\n%\n\n%\n% Nonsense cases.\n%\n if ( box_num < 0 )\n\n pdf = 0.0;\n\n elseif ( type_num < 1 )\n\n pdf = 0.0;\n%\n% Degenerate but meaningful case.\n%\n elseif ( type_num == 1 )\n\n if ( box_num == 1 )\n pdf = 1.0;\n else\n pdf = 0.0;\n end\n%\n% Easy cases.\n%\n elseif ( box_num < type_num )\n\n pdf = 0.0;\n%\n% General case.\n%\n else\n\n factor = 1.0;\n for i = 1 : type_num\n factor = factor * i / type_num;\n end\n for i = type_num+1 : box_num\n factor = factor / type_num;\n end\n \n pdf = factor * stirling2_value ( box_num-1, type_num-1 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/coupon_complete_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7712790521124445}} {"text": "function integral = piecewise_linear_product_integral ( a, b, f_num, f_x, ...\n f_v, g_num, g_x, g_v )\n\n%*****************************************************************************80\n%\n%% PIECEWISE_LINEAR_PRODUCT_INTEGRAL: piecewise linear product integral.\n%\n% Discussion:\n%\n% We are given two piecewise linear functions F(X) and G(X) and we wish\n% to compute the exact value of the integral\n%\n% INTEGRAL = Integral ( A <= X <= B ) F(X) * G(X) dx\n%\n% The functions F(X) and G(X) are defined as tables of coordinates X and\n% values V. A piecewise linear function is evaluated at a point X by\n% evaluating the interpolant to the data at the endpoints of the interval\n% containing X.\n%\n% It must be the case that A <= B.\n%\n% It must be the case that the node coordinates F_X(*) and G_X(*) are\n% given in ascending order.\n%\n% It must be the case that:\n%\n% F_X(1) <= A and B <= F_X(F_NUM)\n% G_X(1) <= A and B <= G_X(G_NUM)\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, real A, B, the limits of integration.\n%\n% Input, integer F_NUM, the number of nodes for F.\n%\n% Input, real F_X(F_NUM), the node coordinates for F.\n%\n% Input, real F_V(F_NUM), the nodal values for F.\n%\n% Input, integer G_NUM, the number of nodes for G.\n%\n% Input, real G_X(G_NUM), the node coordinates for G.\n%\n% Input, real G_V(G_NUM), the nodal values for G.\n%\n% Output, real INTEGRAL, the integral of F(X) * G(X)\n% from A to B.\n%\n integral = 0.0;\n\n if ( f_x(f_num) <= a || g_x(g_num) <= a )\n return\n end\n\n if ( f_num < 2 || g_num < 2 )\n return\n end\n\n xr = a;\n\n f_left = 1;\n f_left = r8vec_bracket3 ( f_num, f_x, xr, f_left );\n fr = f_v(f_left) + ( xr - f_x(f_left) ) * ( f_v(f_left+1) - f_v(f_left) ) ...\n / ( f_x(f_left+1) - f_x(f_left) );\n\n g_left = 1;\n g_left = r8vec_bracket3 ( g_num, g_x, xr, g_left );\n gr = g_v(g_left) + ( xr - g_x(g_left) ) * ( g_v(g_left+1) - g_v(g_left) ) ...\n / ( g_x(g_left+1) - g_x(g_left) );\n\n xr_max = b;\n xr_max = min ( xr_max, f_x(f_num) );\n xr_max = min ( xr_max, g_x(g_num) );\n\n while ( xr < xr_max )\n%\n% Shift right values to left.\n%\n xl = xr;\n fl = fr;\n gl = gr;\n%\n% Determine the new right values.\n% The hard part is figuring out how to advance XR some, but not too much.\n%\n xr = xr_max;\n\n for i = 1 : 2\n if ( f_left + i <= f_num )\n if ( xl < f_x(f_left+i) && f_x(f_left+i) < xr )\n xr = f_x(f_left+i);\n break\n end\n end\n end\n\n for i = 1 : 2\n if ( g_left + i <= g_num )\n if ( xl < g_x(g_left+i) && g_x(g_left+i) < xr )\n xr = g_x(g_left+i);\n break\n end\n end\n end\n\n f_left = r8vec_bracket3 ( f_num, f_x, xr, f_left );\n fr = f_v(f_left) + ( xr - f_x(f_left) ) * ( f_v(f_left+1) - f_v(f_left) ) ...\n / ( f_x(f_left+1) - f_x(f_left) );\n\n g_left = r8vec_bracket3 ( g_num, g_x, xr, g_left );\n gr = g_v(g_left) + ( xr - g_x(g_left) ) * ( g_v(g_left+1) - g_v(g_left) ) ...\n / ( g_x(g_left+1) - g_x(g_left) );\n%\n% Form the linear polynomials for F(X) and G(X) over [XL,XR],\n% then the product H(X), integrate H(X) and add to the running total.\n%\n if ( eps <= abs ( xr - xl ) )\n\n f1 = fl - fr;\n f0 = fr * xl - fl * xr;\n\n g1 = gl - gr;\n g0 = gr * xl - gl * xr;\n\n h2 = f1 * g1;\n h1 = f1 * g0 + f0 * g1;\n h0 = f0 * g0;\n\n h2 = h2 / 3.0;\n h1 = h1 / 2.0;\n\n bit = ( ( h2 * xr + h1 ) * xr + h0 ) * xr ...\n - ( ( h2 * xl + h1 ) * xl + h0 ) * xl;\n\n integral = integral + bit / ( xr - xl ) / ( xr - xl );\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/piecewise_linear_product_integral/piecewise_linear_product_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7712718219312956}} {"text": "function [x,z]=constrainedLSEq(A,b,B,d,algorithm)\n%%CONSTRAINEDLSEQ Find x to minimize norm(A*x-b)^2 under the constraint\n% that B*x=d. It is assumed that the (m+p)Xn stacked matrix\n% [A;B] has linearly independent columns (left invertible)\n% and B has linearly independent rows (right invertible).\n% This means that p<=n<=m+p. This is equality constrained\n% least squares.\n%\n%INPUTS: A A real mXn matrix\n% b A real mX1 vector.\n% B A real pXn matrix.\n% d A real pX1 vector.\n% algorithm An optional prameter specfying the algorithm to use. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is passed) Use\n% Algorithm 6.2.2 in Chapter 6.2.3 of [1].\n% 1 In Chapter 14 of [2], it is shown that x solves the\n% constrained least squares problem if and only if there exists\n% a z such that [A'*A, B'; B, zeros(p,p)]*[x;z]=[A'*b;d]\n% This is a set of n+p equations and unknowns. This solution\n% just solves that system.\n% 2 Use the algorithm of Chapter 6.2.5 of [1], which makes use of\n% the generalized singular value decomposition (GSVD).\n%\n%OUTPUTS: x The solution to the equality constrained least squares problem.\n% An mX1 vector.\n% z If algorithm=0, this is an (n-p)X1 unconstrained solution that\n% is an intermediate result. If algorithm=1, this is the pX1 set\n% of Lagrangian multipliers used in the solution. If algorithm=2,\n% this is an empty matrix.\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%[2] S. Boyd and L. Vandenberghe, Vectors, Matrices, and Least Squares,\n% Sep. 2015, draft version of book. [Online].\n% Available: http://www.seas.ucla.edu/~vandenbe/133A/133A-textbook.pdf\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(algorithm))\n algorithm=0;\nend\n\nswitch(algorithm)\n case 0%Algorithm 6.2.2 in Chapter 6.2.3 of [1].\n [~,n1]=size(A);\n [m2,~]=size(B);\n\n [Q,R]=qr(B');\n opts.UT=false;\n opts.LT=true;\n opts.RECT=false;\n y=linsolve(R(1:m2,1:m2)',d,opts);\n\n A=A*Q;\n z=linearLeastSquares(A(:,(m2+1):n1),b-A(:,1:m2)*y);\n x=Q(:,1:m2)*y+Q(:,(m2+1):n1)*z;\n case 1%From Chapter 14 of [2].\n m=size(A,2);\n p=size(B,1);\n H=A'*A;\n c=A'*b;\n xz=[H,B';\n B,zeros(p,p)]\\[c;d];\n\n x=xz(1:m);\n z=xz((m+1):end); %The Lagrangian multipliers.\n case 2%The GSVD approach of Chapter 6.2.5 of [1].\n [~,n1]=size(A);\n [m2,~]=size(B);\n\n [U1,U2,X,DA,DB]=gsvd(A,B);\n bTilde=U1'*b;\n dTilde=U2'*d;\n\n %The definition of the GSVD used in Chapter 6.1.6 of [1] is not the\n %same as that implemented by Matlab's gsvd function. Specifically,\n %we have to modify X as follows:\n X=inv(X');\n\n alphaVals=diag(DA);\n betaVals=diag(DB);\n\n x=zeros(n1,1);\n for i=1:m2\n x=x+(dTilde(i)/betaVals(i))*X(:,i);\n end\n\n for i=(m2+1):n1\n x=x+(bTilde(i)/alphaVals(i))*X(:,i);\n end\n z=[];\n otherwise\n error('Unknown algorithm specified.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Continuous_Optimization/constrainedLSEq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7712718219312956}} {"text": "function M = makeFslXfmMatrix(T,R,S,filename)\n%MAKEFSLXFMMATRIX Make FSL-compatible transformation matrix.\n% M = MAKEFSLXFMMATRIX(T,R,S,FILENAME) outputs a 4x4 transformation\n% matrix performing the translations in T, the rotations in R and the\n% scalings in S and writes this matrix to the file specified by the \n% string FILENAME. This file is compatible with FSL's flirt and thus can\n% be directly used without further modification.\n% \n% This function is actually the inverse function of FSL's avscale in that\n% avscale reads a transformation matrix file and lists the corresponding\n% translation, rotation and so on. \n%\n% MAKEFSLXFMMATRIX can be especially useful if you would like to run\n% simulations. \n%\n% Please note that, just as in avscale, T is in millimeters, R is in\n% radians and S is unitless. \n%\n% Usage example:\n% ==============\n% T = [1.433440 19.715600 0.786690]; % in mm.\n% R = [0.102735 -0.155470 0.121564]; % in rad.\n% S = [1 1 1]; % unitless\n% filename = 'thisIsWhatIWant.mat'; % :))\n% \n% M = makeFslXfmMatrix(T,R,S,filename);\n% \n% Now you can use avscale to see if things are working correctly.\n%\n% [status,result] = system(['avscale --allparams thisIsWhatIWant.mat']);\n% disp(result)\n% \n% Best.\n\n% Check inputs\nif ~isnumeric(T) || ~isnumeric(R) || ~isnumeric(S) \n error('T, R and S have to be numeric...');\nend\n\nif ~ischar(filename)\n error('FILENAME has to be a string...');\nend \n\n% Get rotation angles about each axis.\nthetaX = R(1);\nthetaY = R(2);\nthetaZ = R(3);\n\n% Compute the rotation matrices.\nRx = [1 0 0; 0 cos(thetaX) sin(thetaX);0 -sin(thetaX) cos(thetaX)];\nRy = [cos(thetaY) 0 -sin(thetaY);0 1 0;sin(thetaY) 0 cos(thetaY)];\nRz = [cos(thetaZ) sin(thetaZ) 0;-sin(thetaZ) cos(thetaZ) 0;0 0 1];\n\n% Concatenate rotations.\nR_3x3 = Rx*Ry*Rz;\n\n% Put scalings on the diagonal.\nS_3x3 = diag(S); \n\n% Make the 4x4 transformation matrix.\nM = [R_3x3*S_3x3 T(:); 0 0 0 1];\n\n% Try to open the file\nfid = fopen(filename,'w');\n\n% Check if it worked\nif fid == -1\n error(['Could not open for writing: ' filename]);\nend\n\nfor k = 1:4\n fprintf(fid,[num2str(M(k,:)) '\\n']);\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/30804-make-fsl-compatible-transformation-matrix/makeFslXfmMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7712718109615665}} {"text": "function variance = english_word_length_variance ( )\n\n%*****************************************************************************80\n%\n%% ENGLISH_WORD_LENGTH_VARIANCE: variance of the English Word Length PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 July 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Henry Kucera, Winthrop Francis,\n% Computational Analysis of Present-Day American English,\n% Brown University Press, 1967.\n%\n% Parameters:\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n word_length_max = 27;\n\n pdf_vec = [ ...\n 0.03160, ...\n 0.16975, ...\n 0.21192, ...\n 0.15678, ...\n 0.10852, ...\n 0.08524, ...\n 0.07724, ...\n 0.05623, ...\n 0.04032, ...\n 0.02766, ...\n 0.01582, ...\n 0.00917, ...\n 0.00483, ...\n 0.00262, ...\n 0.00099, ...\n 0.00050, ...\n 0.00027, ...\n 0.00022, ...\n 0.00011, ...\n 0.00006, ...\n 0.00005, ...\n 0.00002, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001 ];\n pdf_sum = 0.99997;\n\n mean = 0.0;\n for j = 1 : word_length_max\n mean = mean + j * pdf_vec(j);\n end\n\n mean = mean / pdf_sum;\n\n variance = 0.0;\n for j = 1 : word_length_max\n variance = variance + pdf_vec(j) * ( j - mean )^2; \n end\n\n variance = variance / pdf_sum;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/english_word_length_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7712718071836446}} {"text": "function [ x, w ] = nco_set ( n )\n\n%*****************************************************************************80\n%\n%% NCO_SET sets abscissas and weights for open Newton-Cotes quadrature.\n%\n% Discussion:\n%\n% The open Newton-Cotes rules use equally spaced abscissas, and\n% hence may be used with equally spaced data.\n%\n% The rules are called \"open\" because they do not include the interval\n% endpoints.\n%\n% Most of the rules involve negative weights. These can produce loss\n% of accuracy due to the subtraction of large, nearly equal quantities.\n%\n% The integral:\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% 02 May 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Abramowitz and Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Daniel Zwillinger, editor,\n% Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n% N must be between 1 and 7, and 9.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n x = zeros ( n, 1 );\n w = zeros ( n, 1 );\n\n if ( n == 1 )\n\n w(1) = 2.0;\n\n elseif ( n == 2 )\n\n w(1) = 1.0;\n w(2) = 1.0;\n\n elseif ( n == 3 )\n\n d = 3.0;\n\n w(1) = 4.0 / d;\n w(2) = - 2.0 / d;\n w(3) = 4.0 / d;\n\n elseif ( n == 4 )\n\n d = 12.0;\n\n w(1) = 11.0 / d;\n w(2) = 1.0 / d;\n w(3) = 1.0 / d;\n w(4) = 11.0 / d;\n\n elseif ( n == 5 )\n\n d = 10.0;\n\n w(1) = 11.0 / d;\n w(2) = - 14.0 / d;\n w(3) = 26.0 / d;\n w(4) = - 14.0 / d;\n w(5) = 11.0 / d;\n\n elseif ( n == 6 )\n\n d = 1440.0;\n\n w(1) = 1222.0 / d;\n w(2) = - 906.0 / d;\n w(3) = 1124.0 / d;\n w(4) = 1124.0 / d;\n w(5) = - 906.0 / d;\n w(6) = 1222.0 / d;\n\n elseif ( n == 7 )\n\n d = 945.0;\n\n w(1) = 920.0 / d;\n w(2) = - 1908.0 / d;\n w(3) = 4392.0 / d;\n w(4) = - 4918.0 / d;\n w(5) = 4392.0 / d;\n w(6) = - 1908.0 / d;\n w(7) = 920.0 / d;\n\n elseif ( n == 9 )\n\n d = 4536.0;\n\n w(1) = 4045.0 / d;\n w(2) = - 11690.0 / d;\n w(3) = 33340.0 / d;\n w(4) = - 55070.0 / d;\n w(5) = 67822.0 / d;\n w(6) = - 55070.0 / d;\n w(7) = 33340.0 / d;\n w(8) = - 11690.0 / d;\n w(9) = 4045.0 / d;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NCO_SET - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of N = %d\\n', n );\n fprintf ( 1, ' Legal values are 1 to 7, and 9.\\n' );\n error ( 'NCO_SET - Fatal error!' );\n\n end\n%\n% Set the abscissas.\n%\n for i = 1 : n\n x(i) = ( 2 * i - n - 1 ) / ( 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/quadrule/nco_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7712718054084449}} {"text": " function [lo hi] = ir_dwt_filters(wname, varargin)\n%|function [coef codes] = ir_odwt1(x, varargin)\n%|\n%| filters for discrete wavelet transform DWT\n%|\n%| in\n%|\t'wname'\tchar\t'haar' (default) or 'db4' or 'sym2'\n%|\n%| option\n%|\t'usemat' 0|1\tdefault: 0. (if 1 then use matlab wfilters)\n%|\t'ortho'\t0|1\tdefault: 1 (make normalized)\n%|\t'abs'\t0|1\tdefault: 0. (if 1 then take abs of filters)\n%|\n%| out\n%|\tlo\t[K]\tlow-pass decomposition filter\n%|\thi\t[K]\thi-pass decomposition filter\n%|\n%| 2012-05-21, Jeff Fessler, Univ. of Michigan\n%| 2014-01-23, Matt Muckley: added 'db4'\n\nif nargin < 1, ir_usage, end\nif streq(wname, 'test'), ir_dwt_filters_test, return, end\n\narg.wname = wname;\narg.ortho = true;\narg.usemat = false;\narg.abs = false;\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.wname)\n\t arg.wname = 'haar';\nend\n\n% decomposition filters\nif arg.usemat\n\t[lo hi lo_r hi_r] = wfilters(arg.wname);\n\tlo = lo'; lo_r = lo_r';\n\thi = hi'; hi_r = hi_r';\n\n\tjf_equal(lo_r, flipud(lo))\n\tjf_equal(hi_r, flipud(hi))\nelse\n\tswitch arg.wname\n\tcase 'haar'\n\t\tlo = [1 1]';\n\t\thi = [-1 1]';\n\n\tcase 'db4'\n\t\th1 = (1 + sqrt(3))/4;\n\t\th2 = (3 + sqrt(3))/4;\n\t\th3 = (3 - sqrt(3))/4;\n\t\th4 = (1 - sqrt(3))/4;\n\t\tlo = [h1 h2 h3 h4]';\n\t\thi = [h4 -h3 h2 -h1]';\n\t\tclear h1 h2 h3 h4;\n\n\tcase 'sym2'\n\t\tlo = [-0.129409522550921; 0.224143868041857; ...\n\t\t\t0.836516303737469; 0.482962913144690];\n\t\thi = [-0.482962913144690; 0.836516303737469; ...\n\t\t\t-0.224143868041857; -0.129409522550921];\n\totherwise\n\t\tfail('unknown wname \"%s\"', arg.wname)\n\tend\nend\n\nif arg.ortho\n\tlo = lo / norm(lo);\n\thi = hi / norm(hi);\nend\n\nif arg.abs\n\tlo = abs(lo);\n\thi = abs(hi);\nend\n\n\n% ir_dwt_filters_test()\nfunction ir_dwt_filters_test\n\nlist = {'haar', 'sym2', 'db4'};\nfor ii=1:numel(list)\n\twname = list{ii};\n\n\t[lo0 hi0] = ir_dwt_filters(wname, 'usemat', 0);\n\tif numel(lo0) == 2\n\t\tjf_equal(lo0' * hi0, 0)\n\telse\n\t\tequivs(1, 1 + lo0' * hi0)\n\tend\n\n\tif exist('dwt', 'file') == 2 && exist('wfilters', 'file') == 2\n\t\t[lo1 hi1] = ir_dwt_filters(wname, 'usemat', 1);\n\tend\n\n\t[lo hi] = ir_dwt_filters(wname, 'ortho', 0);\n\tjf_equal(lo/norm(lo), lo0)\n\tjf_equal(hi/norm(hi), hi0)\n\n\t[lo hi] = ir_dwt_filters(wname, 'abs', 1);\n\tjf_equal(abs(lo0), lo)\n\tjf_equal(abs(hi0), hi)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/ir_dwt_filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7712376485274944}} {"text": "%% RATE OF CONVERGENCE OF LINEAR FINITE ELEMENT METHOD\n%\n% This example is to show the rate of convergence of linear finite element\n% approximation of the Poisson equation on the unit square:\n%\n% $$- \\Delta u = f \\; \\hbox{in } (0,1)^2$$\n%\n% for the following boundary condition:\n%\n% # Non-empty Dirichlet boundary condition. $u=g_D \\hbox{ on }\\Gamma_D, \\quad \\nabla u\\cdot n=g_N \\hbox{ on }\\Gamma_N. \\Gamma _D = \\{(x,y): x=0, y\\in [0,1]\\}, \\; \\Gamma _N = \\partial \\Omega \\backslash \\Gamma _D$. \n% # Pure Neumann boundary condition. $\\Gamma _N = \\partial \\Omega$.\n% # Robin boundary condition. $g_R u + \\nabla u\\cdot n=g_N \\hbox{ on }\\partial \\Omega$\n\n%% \nclear all; close all;\n[node,elem] = cubemesh([0,1,0,1,0,1],0.25); \npde = sincosdata3;\noption.L0 = 0;\noption.maxIt = 4;\noption.printlevel = 1;\noption.elemType = 'CR';\noption.plotflag = 0;\n\n%% Non-empty Dirichlet boundary condition.\nbdFlag = setboundary3(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\n% bdFlag = setboundary3(node,elem,'Dirichlet');\nfemPoisson3(node,elem,pde,bdFlag,option);\n\n%% Pure Neumann boundary condition.\n% pde = sincosNeumanndata;\nbdFlag = setboundary3(node,elem,'Neumann');\nfemPoisson3(node,elem,pde,bdFlag,option);\n\n%% Pure Robin boundary condition.\npdeRobin = sincosRobindata3;\nbdFlag = setboundary3(node,elem,'Robin');\nfemPoisson3(node,elem,pdeRobin,bdFlag,option);\n\n%% Conclusion\n%\n% The optimal rate of convergence of the H1-norm (1st order) and L2-norm\n% (2nd order) is observed. No superconvergence for ||DuI-Duh||.\n%\n% MGCG converges uniformly in all cases.", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/example/femrate3CR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.771237643206085}} {"text": "function [xx, yy, zz] = chebpts3(nx, ny, nz, dom, kind)\n%CHEBPTS3 3D tensor product Chebyshev grid.\n% [XX YY ZZ] = CHEBPTS3(N) constructs an N by N by N grid of Chebyshev \n% tensor points on [-1 1]^3.\n%\n% [XX YY ZZ] = CHEBPTS3(NX,NY,NZ) constructs an NX by NY by NZ grid of \n% Chebyshev tensor points on [-1 1]^3.\n%\n% [XX YY ZZ] = CHEBPTS3(NX,NY,NZ,DOM) constructs an NX by NY by NZ grid \n% of Chebyshev tensor points on the cube [a b] x [c d] x [e g], where \n% DOM = [a b c d e g].\n%\n% [XX YY ZZ] = CHEBPTS3(NX,NY,NZ,D,KIND) constructor Chebyshev tensor \n% grid of the kind KIND. KIND = 2 is default.\n% \n% See also CHEBPTS and CHEBPTS2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( nargin > 3 ) \n % Third argument should be a domain. \n dom = dom(:).'; % make a row vector. \n if ( ~all(size(dom) == [1 6]) )\n error('CHEBFUN:chebpts3:domain', 'Unrecognised domain.');\n end\nelse % Default to the canoncial domain.\n dom = [-1, 1, -1, 1, -1, 1];\nend\n\nif ( nargin == 1 ) \n % Make it a square Chebyshev grid if only one input. \n ny = nx; \n nz = nx;\nend\nif ( nargin < 5 ) \n % default to Chebyshev points of the 2nd kind. \n kind = 2; \nend\n\n% Get points: \nx = chebpts(nx, dom(1:2), kind); \ny = chebpts(ny, dom(3:4), kind); \nz = chebpts(nz, dom(5:6), kind); \n\n% Tensor product. \n[xx, yy, zz] = ndgrid(x, y, z); \n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/chebpts3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7712376264426376}} {"text": "function quality=meshquality(node,elem,maxnode)\n%\n% quality=meshquality(node,elem)\n%\n% compute the Joe-Liu mesh quality measure of an N-D mesh (N<=3)\n%\n% author: Qianqian Fang, \n% date: 2011/02/26\n%\n% input:\n% node: node coordinates of the mesh (nn x 3)\n% elem: element table of an N-D mesh (ne x (N+1))\n%\n% output:\n% quality: a vector of the same length as size(elem,1), with \n% each element being the Joe-Liu mesh quality metric (0-1) of \n% the corresponding element. A value close to 1 represents\n% higher mesh quality (1 means equilateral tetrahedron); \n% a value close to 0 means nearly degenerated element.\n%\n% reference:\n% A. Liu, B. Joe, Relationship between tetrahedron shape measures, \n% BIT 34 (2) (1994) 268-287.\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nif(nargin<3)\n maxnode=4;\nend\nif(size(elem,2)>maxnode)\n elem=elem(:,1:maxnode);\nend\nenum=size(elem,1);\nvol=elemvolume(node,elem);\nedges=meshedge(elem);\ned=node(edges(:,1),:)-node(edges(:,2),:);\ned=sum((ed.*ed)');\ned=sum(reshape(ed,[enum length(ed)/enum])')';\ndim=size(elem,2)-1;\n\ncoeff=10/9; % for tetrahedral\nif(dim==2)\n coeff=1;\nend\nquality=coeff*dim*2^(2*(1-1./dim))*3^((dim-1)/2)*vol.^(2/dim)./ed;\nmaxquality=max(quality);\nif(maxquality>1)\n quality=quality./maxquality;\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/iso2mesh/meshquality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7712045739768378}} {"text": "function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)\n%GRADIENTDESCENT Performs gradient descent to learn theta\n% theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by \n% taking num_iters gradient steps with learning rate alpha\n\n% Initialize some useful values\nm = length(y); % number of training examples\nJ_history = zeros(num_iters, 1);\n\nfor iter = 1:num_iters\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCost) and gradient here.\n %\n \n delta = (1/m)*sum(X.*repmat((X*theta - y), 1, size(X,2)));\n \n \n theta = (theta' - (alpha * delta))';\n\n\n\n\n\n % ============================================================\n\n % Save the cost J in every iteration \n J_history(iter) = computeCost(X, y, theta);\n\nend\n\nend\n", "meta": {"author": "Borye", "repo": "machine-learning-coursera-1", "sha": "033fdc2e6da393eeb1179a09aafe92362021effb", "save_path": "github-repos/MATLAB/Borye-machine-learning-coursera-1", "path": "github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 2 Assignments/Linear Regression with Multiple Variables/mlclass-ex1/gradientDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7712045722695183}} {"text": "%% Ellipsoid parameters\n%\n% Silson et al. have a very different set of ellipses, far more oriented\n% than anyone else. This was pointed out by a few of us at Stanford, and\n% in discussing with Reynolds (the AFNI guy) it turned out that they solved\n% the ellipse using\n%\n% ax^2 + bxy + cy^2\n%\n% That's the wrong equation. The correction equation is\n%\n% ax^2 + 2bxy + cy^2\n%\n% So when the true value is b, they calculate a value of 2b. This script\n% analyses what we expect to find in terms of the ratios of major and minor\n% axes if we solve erroneously, as per the AFNI calculation published by\n% Silson et al.\n%\n% The formulae for the ellipsoid calculations are taken from Wolfram in\n%\n% http://mathworld.wolfram.com/Ellipse.html\n%\n% The calculation shows that in many cases the ratio of the lengths of the\n% major and minor axes differs quite significantly when one makes the AFNI\n% error.\n%\n% The significance of this calculation is that Silson et al. deny that\n% there is a significant difference. Hence, there is a dispute based on\n% mathematics. Let's check this code and see who is right.\n%\n% Wandell, September 24, 2018\n\n%% General quadratic notes\n%\n% ax^2 + 2bxy + cy^2 + 2dx + 2fy + g=0\n%\n% For the centered ellipse we have d = f = 0.\n% We set g = -1 for this case so\n%\n% ax^2 + 2bxy + cy^2 = 1\n%\n% J = det([ a b; b c]) > 0 and\n% D = det([ a b 0; b c 0; 0 0 1])\n% I = a + c\n% We require D .n.e. 0, J > 0 and D/I < 0\n%\n\n%% Set parameters\n\n% These are the three parameters that can be changed\na = 4;\nb = 1; originalB = b;\nc = 3;\n\n%{\na = 2; b = 2; c = 3; % 3.225 and 1.618\n%}\ng = -1; % We fix g to -1 because we can always scale a,b and c to make it so\n\n%% The formulae for the axis lengths from the Wolfram web-page\n%\n% a' = sqrt((2(af^2+cd^2+gb^2-2bdf-acg))/((b^2-ac)[sqrt((a-c)^2+4b^2)-(a+c)]))\n% b' = sqrt((2(af^2+cd^2+gb^2-2bdf-acg))/((b^2-ac)[-sqrt((a-c)^2+4b^2)-(a+c)])).\n%\n% The formulae below simplify because d=f=0 and g = -1;\n\nb = originalB;\nif ellipseValidate(a,b,c,g)\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(sqrt((a - c)^2 + 4*b^2) - (a + c));\n aLength = sqrt(top / bottom);\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(-1*sqrt((a - c)^2 + 4*b^2) - (a + c));\n bLength = sqrt(top / bottom);\n \n mx = max(aLength, bLength);\n mn = min(aLength, bLength);\n fprintf('Ratio 1: %f (b = %.2f)\\n',mx/mn,b);\nelse\n fprintf('Not an ellipse when b = %f\\n',b);\nend\n\n\n%% If we incorrectly solve using b2 = 2b\n%\n% It doesn't really matter whether we use b2 = 2b or b2 = b/2\n% The b values are related by a factor of 2 and one is right and the other\n% is wrong. Reynolds says that this has no impact on the ratio of the\n% lengths of the two axes. That is bogus, as running most cases show, such\n% as the ones above\n\nb = originalB/2;\nif ellipseValidate(a,b,c,g)\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(sqrt((a - c)^2 + 4*b^2) - (a + c));\n aLength = sqrt(top / bottom);\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(-1*sqrt((a - c)^2 + 4*b^2) - (a + c));\n bLength = sqrt(top / bottom);\n \n mx = max(aLength, bLength);\n mn = min(aLength, bLength);\n fprintf('Ratio 2: %f (b = %.2f)\\n',mx/mn,b);\nelse\n fprintf('Not an ellipse when b = %f\\n',b);\nend\n\n\n%% Or if we divide by 2\n\nb = originalB*2;\nif ellipseValidate(a,b,c,g)\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(sqrt((a - c)^2 + 4*b^2) - (a + c));\n aLength = sqrt(top / bottom);\n \n top = (2*(g*b^2 - a*c*g));\n bottom = (b^2 - a*c)*(-1*sqrt((a - c)^2 + 4*b^2) - (a + c));\n bLength = sqrt(top / bottom);\n \n mx = max(aLength, bLength);\n mn = min(aLength, bLength);\n fprintf('Ratio 3: %f (b = %.2f)\\n',mx/mn,b);\nelse\n fprintf('Not an ellipse when b = %f\\n',b);\nend\n\n\n%%\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/tutorials/diffusion/afniError/ellipseParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109604427853, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7712045552477108}} {"text": "%% Histogram Comparison\n%\n% In this demo, we show how to:\n%\n% * Use the function |cv.compareHist| to get a numerical parameter that\n% express how well two histograms match with each other\n% * Use different metrics to compare histograms\n%\n% Sources:\n%\n% * \n% * \n%\n\n%% Theory\n%\n% To compare two histograms ($H_{1}$ and $H_{2}$), first we have to choose a\n% _metric_ ($d(H_{1}, H_{2})$) to express how well both histograms match.\n%\n% OpenCV implements the function |cv.compareHist| to perform a comparison. It\n% also offers 4 different metrics to compute the matching:\n%\n% * *Correlation*:\n%\n% $$d(H_1,H_2) = \\frac{\\sum_I (H_1(I) - \\bar{H_1}) (H_2(I) - \\bar{H_2})}\n% {\\sqrt{\\sum_I(H_1(I) - \\bar{H_1})^2\n% \\sum_I(H_2(I) - \\bar{H_2})^2}}$$\n%\n% where\n%\n% $$\\bar{H_k} = \\frac{1}{N} \\sum _J H_k(J)$$\n%\n% and $N$ is the total number of histogram bins.\n%\n% * *Chi-Square*:\n%\n% $$d(H_1,H_2) = \\sum _I \\frac{\\left(H_1(I)-H_2(I)\\right)^2}{H_1(I)}$$\n%\n% * *Intersection*:\n%\n% $$d(H_1,H_2) = \\sum _I \\min (H_1(I), H_2(I))$$\n%\n% * *Bhattacharyya*:\n%\n% $$d(H_1,H_2) = \\sqrt{1 - \\frac{1}{\\sqrt{\\bar{H_1} \\bar{H_2} N^2}}\n% \\sum_I \\sqrt{H_1(I) \\cdot H_2(I)}}$$\n%\n\n%% Code\n%\n% This program:\n%\n% * Loads a _base image_ and 2 _test images_ to be compared with it.\n% * Generate 1 image that is the lower half of the _base image_\n% * Convert the images to HSV format\n% * Calculate the H-S histogram for all the images and normalize them in order\n% to compare them.\n% * Compare the histogram of the _base image_ with respect to the 2 test\n% histograms, the histogram of the lower half base image and with the same\n% base image histogram.\n% * Display the numerical matching parameters obtained.\n%\n\n%%\n% Load source images (base image and the two other images to compare)\nim = {\n 'https://docs.opencv.org/3.3.1/Histogram_Comparison_Source_0.jpg'\n 'https://docs.opencv.org/3.3.1/Histogram_Comparison_Source_1.jpg'\n 'https://docs.opencv.org/3.3.1/Histogram_Comparison_Source_2.jpg'\n};\nsrc = cell(3,1);\nfor i=1:3\n [~,name,ext] = fileparts(im{i});\n fname = fullfile(mexopencv.root(), 'test', [name ext]);\n if exist(fname, 'file') ~= 2\n disp('Downloading image...')\n urlwrite(im{i}, fname);\n end\n src{i} = cv.imread(fname, 'Color',true);\nend\n\n%%\n% also create an image of half the base image\nsrc{4} = src{1}(end/2:end,:,:);\nsrc = src([1 4 2 3]);\n\n%%\n% show images\nnames = {'Base', 'Half', 'Test1', 'Test2'};\nfor i=1:numel(src)\n subplot(2,2,i), imshow(src{i}), title(names{i})\nend\n\n%%\n% convert images to HSV color space\nhsv = cell(size(src));\nfor i=1:numel(src)\n hsv{i} = cv.cvtColor(src{i}, 'RGB2HSV');\nend\n\n%%\n% calculate H-S 2D histograms\n%ranges = {linspace(0,180,50+1), linspace(0,256,60+1)};\nranges = {[0 180], [0 256]};\nhsizes = [50, 60];\nhisto = cell(size(hsv));\nfor i=1:numel(hsv)\n histo{i} = cv.calcHist(hsv{i}(:,:,1:2), ranges, 'HistSize',hsizes, 'Uniform',true);\n histo{i} = cv.normalize(histo{i}, 'NormType','MinMax', 'Alpha',0, 'Beta',1);\nend\n\n%%\n% compare histogram of the base image against the other histograms\n% using four different metrics\nalgs = {'Correlation', 'ChiSquare', 'Intersection', 'Bhattacharyya'};\nD = zeros(numel(algs),numel(histo));\nfor j=1:numel(histo)\n for i=1:numel(algs)\n D(i,j) = cv.compareHist(histo{1}, histo{j}, 'Method',algs{i});\n end\nend\n\n%%\n% The first image is the base (to be compared to the others), the other 2 are\n% the test images. We also compare the first image with respect to itself and\n% with respect of half the base image.\n%\n% We should expect a perfect match when we compare the base image histogram\n% with itself. Also, compared with the histogram of half the base image, it\n% should present a high match since both are from the same source. For the\n% other two test images, we can observe that they have very different lighting\n% conditions, so the matching should not be very good.\n%\n\n%%\n% Here are the numeric results\nif ~mexopencv.isOctave()\n t = array2table(D, 'VariableNames',names, 'RowNames',algs);\n disp(t);\nelse\n %HACK: use cell array instead of table\n t = [{''}, names; algs(:), arrayfun(@num2str,D,'UniformOutput',false)];\n t = t';\n fprintf('%13s %9s %9s %9s %9s\\n',t{:});\nend\n\n%%\n% For the _Correlation_ and _Intersection_ methods, the higher the metric, the\n% more accurate the match. As we can see, the match _base-base_ is the highest\n% of all as expected. Also we can observe that the match _base-half_ is the\n% second best match (as we predicted). For the other two metrics, the less the\n% result, the better the match. We can observe that the matches between the\n% test 1 and test 2 with respect to the base are worse, which again, was\n% expected.\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/histogram_comparison_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.7711893518738663}} {"text": "function value = legendre_determinant ( n )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_DETERMINANT returns the determinant of the LEGENDRE matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real VALUE, the determinant.\n%\n value = 1.0;\n t = 1.0;\n\n for i = 3 : n\n t = t * ( 2 * i - 3 ) / ( i - 1 );\n value = value * t;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/legendre_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.7711893401383854}} {"text": "%% Basic Data Structure representing a Mesh\n%\n%% Data structure: node and elem\n%\n% Two matrices |node(1:N,1:d)| and |elem(1:NT,1:d+1)| are used to represent\n% a d-dimensional triangulation embedded in $\\mathbf R^d$, where |N| is the number\n% of vertices and |NT| is the number of elements. \n% \n% |node(k,1)| and |node(k,2)| are the x- and y-coordinates of the k-th node\n% for points in 2-D. In 3-D, |node(k,3)| gives the additional z-coordinates\n% of the k-th node. \n%\n% |elem(t,1:3)| are indices of 3 vertices of triangle t. |elem(t,1:4)| are\n% indices of 4 vertices of tetrahedron t. By convention, the vertices are\n% ordered such that the signed area/volume is positive. Therefore in 2-D,\n% three vertices of a triangle is ordered counterclockwise and in 3-D, the\n% four vertices of a tetrahedron follows the right-hand rule.\n\nclear all; close all;\n%% Example: L-shape domain in 2-D\nnode = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % coordinates\nelem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % connectivity\nshowmesh(node,elem) \naxis on\nfindnode(node) % plot indices of all vertices\nfindelem(node,elem) % plot indices of all triangles\n%%\n% Apply uniform refinement three times to obtain a fine mesh.\nfor i = 1:3\n [node,elem] = uniformrefine(node,elem);\nend\nshowmesh(node,elem)\n\n%% Example: Cube in 3-D\nnode = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \nelem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];\nclf; showmesh3(node,elem,[],'FaceAlpha',0.25);\nview([-53,8]);\naxis on\nfindnode3(node)\nfindelem3(node,elem)\n%%\n% Apply uniform refinement twice to obtain a fine mesh.\nfor i = 1:2\n [node,elem] = uniformrefine3(node,elem);\nend\nshowmesh3(node,elem,[],'FaceAlpha',0.25); view([-24 10]);\n\n%% Example: Sphere in 3-D\n% a simple triangular mesh in the space\nnode = [1,0,0; 0,1,0; -1,0,0; 0,-1,0; 0,0,1; 0,0,-1];\nelem = [6,1,2; 6,2,3; 6,3,4; 6,4,1; 5,1,4; 5,3,4; 5,3,2; 5,2,1];\nshowmesh(node,elem,'FaceAlpha',0.5);\naxis on;\nfindnode3(node);\n%%\n% uniformly refined mesh\nfor i = 1:3\n [node,elem] = uniformrefine(node,elem);\nend\nshowmesh(node,elem) \n%%\n% project vertices onto the unit sphere\nr = sqrt(node(:,1).^2 + node(:,2).^2 + node(:,3).^2);\nnode = node./[r r r];\nshowmesh(node,elem)\n\n%% Order of vertices: orientation\n% Any permutation of vertices of an element will represent the same\n% abstract simplex. By convention, the vertices of a simplex is ordered\n% such that the signed volume is positive. Therefore in 2-D, three vertices\n% of a triangle is ordered counterclockwise and in 3-D, the ordering of\n% vertices follows the right-hand rule. The function |fixorientation| will\n% compute the signed area or volume and permute vertices if necessary.\n\nnode = [1,0; 1,1; 0,1];\nelem = [1 3 2];\nfigure(4);\nsubplot(1,2,1)\nshowmesh(node,elem)\nfindnode(node,elem)\ndisplay('Clockwise'); display(elem)\nelem = fixorientation(node,elem); \ndisplay('Counter-Clockwise'); display(elem)\n\n%% Order of vertices: longest edge \n% An even permutation of vertices is still allowed to represent the same\n% simplex with the same orientation.\n%\n% * The function |label| will permute the vertices such that |elem(t,2:3)|\n% is the longest edge of |t|. \n% * The function |label3| will permute the vertices such that |elem(t,1:2)|\n% is the longest edge of |t|. \n%\n% These functions are important for bisection methods of triangulations.\n\nnode = [1,0; 1,1; 0,1];\nelem = [1 2 3];\nsubplot(1,2,1)\nshowmesh(node,elem)\nfindnode(node,elem)\ndisplay('Before labeling'); display(elem)\nelem = label(node,elem);\ndisplay('After labeling'); display(elem)\ndisplay('elem(t,2:3) is the longest edge')\n\n%%\nnode = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \nelem = [1,2,3,7; 1,6,2,7; 1,5,6,7];\nfigure(2)\nshowmesh3(node,elem,[],'FaceAlpha',0.25); view([-53,8]);\nfindnode3(node,[1 2 3 5 6 7]);\nfindelem3(node,elem);\ndisplay('Before labeling'); display(elem)\nelem = label3(node,elem);\ndisplay('After labeling'); display(elem)\ndisplay('elem(t,1:2)=[1 7] is the longest edge')", "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/meshbasicdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.771189336812452}} {"text": "\nfunction [cov_ewma,corr_ewma,vola_ewma] = ewma_covariance(data,lambda)\n\n% calculates the RiskMetrics \"Technical Document\" (1996) exponentially \n% weighted covariance matrix (p.179), correlation and volatilities.\n% \n% Input:\n% data - needs to be in format T x k with T = # observations, k = # assets\n% lambda = decay factor\n\n[r,c] = size(data);\ndata_mwb = data-repmat(mean(data,1),r,1);\nlambdavec = lambda.^(0:1:r-1)';\ndata_tilde = repmat(sqrt(lambdavec),1,c).*data_mwb;\n\ncov_ewma = 1/sum(lambdavec)*(data_tilde'*data_tilde);\ncorr_ewma = zeros(c);\nvola_ewma = zeros(c,1);\n\nfor i = 1:c\n for j = 1:c\n corr_ewma(i,j) = cov_ewma(i,j)/sqrt(cov_ewma(i,i)*cov_ewma(j,j));\n end\n vola_ewma(i) = sqrt(cov_ewma(i,i));\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/34569-exponentially-weighted-covariance-matrix/ewma_covariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7709682742092212}} {"text": "function dist = line_par_point_dist_3d ( f, g, h, x0, y0, z0, p )\n\n%*****************************************************************************80\n%\n%% LINE_PAR_POINT_DIST_3D: distance ( parametric line, point ) in 3D.\n%\n% Discussion:\n%\n% The parametric form of a line in 3D is:\n%\n% X = X0 + F * T\n% Y = Y0 + G * T\n% Z = Z0 + H * T\n%\n% We normalize by choosing F*F+G*G+H*H=1 and 0 <= F.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983.\n%\n% Parameters:\n%\n% Input, real F, G, H, X0, Y0, Z0, the parametric line\n% parameters.\n%\n% Input, real P(3,1), the point whose distance from the line is\n% to be measured.\n%\n% Output, real DIST, the distance from the point to the line.\n%\n dx = g * ( f * ( p(2,1) - y0 ) - g * ( p(1,1) - x0 ) ) ...\n + h * ( f * ( p(3,1) - z0 ) - h * ( p(1,1) - x0 ) );\n\n dy = h * ( g * ( p(3,1) - z0 ) - h * ( p(2,1) - y0 ) ) ...\n - f * ( f * ( p(2,1) - y0 ) - g * ( p(1,1) - x0 ) );\n\n dz = - f * ( f * ( p(3,1) - z0 ) - h * ( p(1,1) - x0 ) ) ...\n - g * ( g * ( p(3,1) - z0 ) - h * ( p(2,1) - y0 ) );\n\n dist = sqrt ( dx * dx + dy * dy + dz * dz ) ...\n / ( f * f + g * g + h * 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/theodolite/line_par_point_dist_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7707715587677311}} {"text": "function [Y] = LaplacianScore(X, W)\n%\tUsage:\n%\t[Y] = LaplacianScore(X, W)\n%\n%\tX: Rows of vectors of data points\n%\tW: The affinity matrix.\n%\tY: Vector of (1-LaplacianScore) for each feature.\n% The features with larger y are more important.\n%\n% Examples:\n%\n% fea = rand(50,70);\n% options = [];\n% options.Metric = 'Cosine';\n% options.NeighborMode = 'KNN';\n% options.k = 5;\n% options.WeightMode = 'Cosine';\n% W = constructW(fea,options);\n%\n% LaplacianScore = LaplacianScore(fea,W);\n% [junk, index] = sort(-LaplacianScore);\n% \n% newfea = fea(:,index);\n% %the features in newfea will be sorted based on their importance.\n%\n%\tType \"LaplacianScore\" for a self-demo.\n%\n% See also constructW\n%\n%Reference:\n%\n% Xiaofei He, Deng Cai and Partha Niyogi, \"Laplacian Score for Feature Selection\".\n% Advances in Neural Information Processing Systems 18 (NIPS 2005),\n% Vancouver, Canada, 2005. \n%\n% Deng Cai, 2004/08\n\n\nif nargin == 0, selfdemo; return; end\n\n[nSmp,nFea] = size(X);\n\nif size(W,1) ~= nSmp\n error('W is error');\nend\n\nD = full(sum(W,2));\nL = W;\n\nallone = ones(nSmp,1);\n\n\ntmp1 = D'*X;\n\nD = sparse(1:nSmp,1:nSmp,D,nSmp,nSmp);\n\nDPrime = sum((X'*D)'.*X)-tmp1.*tmp1/sum(diag(D));\nLPrime = sum((X'*L)'.*X)-tmp1.*tmp1/sum(diag(D));\n\nDPrime(find(DPrime < 1e-12)) = 10000;\n\nY = LPrime./DPrime;\nY = Y';\nY = full(Y);\n\n\n\n \n%---------------------------------------------------\nfunction selfdemo\n% ====== Self demo using IRIS dataset\n% ====== 1. Plot IRIS data after LDA for dimension reduction to 2D\nload iris.dat\n\nfeaNorm = mynorm(iris(:,1:4),2);\nfea = iris(:,1:4) ./ repmat(max(1e-10,feaNorm),1,4);\n\noptions = [];\noptions.Metric = 'Cosine';\noptions.NeighborMode = 'KNN';\noptions.WeightMode = 'Cosine';\noptions.k = 3;\n\nW = constructW(fea,options);\n\n[LaplacianScore] = feval(mfilename,iris(:,1:4),W);\n[junk, index] = sort(-LaplacianScore);\n\nindex1 = find(iris(:,5)==1);\nindex2 = find(iris(:,5)==2);\nindex3 = find(iris(:,5)==3);\nfigure;\nplot(iris(index1, index(1)), iris(index1, index(2)), '*', ...\n iris(index2, index(1)), iris(index2, index(2)), 'o', ...\n iris(index3, index(1)), iris(index3, index(2)), 'x');\nlegend('Class 1', 'Class 2', 'Class 3');\ntitle('IRIS data onto the first and second feature (Laplacian Score)');\naxis equal; axis tight;\n\nfigure;\nplot(iris(index1, index(3)), iris(index1, index(4)), '*', ...\n iris(index2, index(3)), iris(index2, index(4)), 'o', ...\n iris(index3, index(3)), iris(index3, index(4)), 'x');\nlegend('Class 1', 'Class 2', 'Class 3');\ntitle('IRIS data onto the third and fourth feature (Laplacian Score)');\naxis equal; axis tight;\n\ndisp('Laplacian Score:');\nfor i = 1:length(LaplacianScore)\n disp(num2str(LaplacianScore(i)));\nend\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/FeatureSelection/LaplacianScore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.770771541584104}} {"text": "function Y = spherharm(theta,phi,l,m);\n% function Y = spherharm(theta,phi,l,m);\n\nmp = abs(m);\t\t\t% positive m\n\nY = sqrt((2*l + 1)/(4*pi) * (prod(1:(l-mp))/prod(1:(l+mp)))) * ...\n legendrex(cos(theta),mp,l) .* exp(sqrt(-1)*mp*phi);\n\nif(m < 0),\n Y = (-1)^mp * conj(Y);\nend\nreturn\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/mosher/spherharm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7707238283541668}} {"text": "function [V,F,Q] = torus(n,m,r,varargin)\n % TORUS Construct a triangle mesh of a unit torus.\n % \n % [V,F] = torus(n,m,r)\n % [V,F] = torus(n,m,r,'ParameterName',ParameterValue, ...)\n %\n % Inputs:\n % n number of vertices around inner ring\n % m number of vertices around outer ring\n % r radius of the inner ring\n % Optional:\n % 'R' followed by outer ring radius {1}\n % Outputs:\n % V #V by 3 list of mesh vertex positions\n % F #F by 3 list of triangle mesh indices\n %\n % Example:\n % % Roughly even shaped triangles\n % n = 40;\n % r = 0.4;\n % [V,F] = torus(n,round(r*n),r);\n R = 1;\n params_to_variables = containers.Map( ...\n {'R'},{'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 [V,F] = create_regular_grid(n,m,true,true);\n\n V = V*2*pi;\n th = V(:,2);\n phi = V(:,1);\n V = [cos(phi).*(R+r*cos(th)) sin(phi).*(R+r*cos(th)) r*sin(th)];\n Q = [F(1:2:end-1,[1 2]) F(2:2:end,[2 3])];\n\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/torus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7707195659620737}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all\nclose all\nclc\n% E: modulus of elasticity\n% A: area of cross section\n% L: length of bar\nE=8; L=4;\nu_exact=@(x) (56-8*(x-2)-24*heaviside(x-5))/2/x;\nhold on;\nezplot(u_exact,[2 6])\ntitle('Exact solution v.s. FEM','interpreter','latex');\nxlabel('x','interpreter','latex');\nylabel('Axial stress, $\\it{\\sigma}_{x}$','interpreter','latex');\nfor i=1:4 %For NEL = 1, 2, 4, 8 \nfprintf( '\\nNumber of elements:%d\\n\\n',2^(i-1) );\n% numberElements: number of elements\nnumberElements=2^(i-1); \n% numberNodes: number of nodes\nNNOD = 2;\nnumberNodes=numberElements+1;\n% generation of coordinates and connectivities \nelementNodes=[1:numberNodes-1;2:numberNodes]'; \nnodeCoordinates=linspace(2,L+2,numberNodes);\n%Generate element length vector\nLe=ones(1,numberElements)*L/numberElements;\nA=(nodeCoordinates(1:end-1)+Le./2)*2;\n%Evaluate area for each cross-section at the center of each element by A=2x; \n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:);\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n ngp = 2;\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(end)));\n [w,xi]=gauss1d(ngp);\n if(nodeCoordinates(elementDof(1))==5)\n x=(5-xc)/detJacobian;\n [s,n]=shapeFunctionL2(x);\n force(elementDof)= force(elementDof)+...\n 24*s';\n elseif(nodeCoordinates(elementDof(1))<5&&...\n nodeCoordinates(elementDof(end))>5)\n x=(5-xc)/detJacobian;\n [s,n]=shapeFunctionL2(x);\n force(elementDof)= force(elementDof)+...\n 24*s';\n end\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL2(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A(e);\n force(elementDof)=force(elementDof)+...\n 8*shape'*detJacobian*w(ip);\n end\nend \n\n% boundary conditions and solution\n% prescribed dofs\nprescribedDof=[1];\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactionsPretty(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\n%stress/strain recover\nfprintf('Axial stress\\n')\nfprintf('element\\tgauss point\\taxial stress\\n')\nngp = 2;\nelementNodeCoor=zeros(numberElements*NNOD,1);\nelementNodeStr=zeros(numberElements*NNOD,1);\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n % Nodal coordiantes in natural coordinate\n xi=[-1 1];\n for ip=1:NNOD\n [shape,naturalDerivatives]=shapeFunctionL2(xi(ip)); \n B=naturalDerivatives*invJacobian;\n elementNodeStr(ip+(e-1)*NNOD,1)=E*B*displacements(elementDof,1); \n fprintf('%2.0f\\t%2.0fth ip\\t%10.4e\\n', e, ip,...\n elementNodeStr(ip+(e-1)*NNOD,1))\n end\n elementNodeCoor(1+(e-1)*ngp:2+(e-1)*ngp)=[nodeCoordinates(elementDof(1))...\n nodeCoordinates(elementDof(2))]; \nend \n\n%post process\nswitch numberElements\n case 1\n str='r*--';\n case 2\n str='g*--';\n case 4\n str='k*--';\n case 8\n str='m*--';\nend\n\nplot(elementNodeCoor,elementNodeStr,str)\nhold on;\nend\nlegend('Exact solution','NEL=1','NEL=2','NEL=4','NEL=8','interpreter','latex');\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/FEM/BarSimple_solution/Prob_4/Linear/ex4_linear_stress_direct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7706287015113289}} {"text": "function [ grid_level, grid_order, grid_point ] = cc_levels_minmax ( ...\n dim_num, level_min, level_max, grid_num, point_num )\n\n%*****************************************************************************80\n%\n%% CC_LEVELS_MINMAX computes CC grids with LEVEL_MIN <= LEVEL <= LEVEL_MAX.\n%\n% Discussion:\n%\n% The CC grids are required to have an order that is 2**LEVEL + 1.\n%\n% The necessary dimensions of GRID_LEVEL, GRID_ORDER and GRID_POINT can be\n% determined by calling CC_LEVELS_MINMAX first.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MIN, LEVEL_MAX, the minimum and maximum values of\n% LEVEL.\n%\n% Input, integer GRID_NUM, the number of Clenshaw Curtis\n% grids whose LEVEL value is between LEVEL_MIN and LEVEL_MAX.\n%\n% Input, integer POINT_NUM, the total number of points in the grids.\n%\n% Output, integer GRID_LEVEL(DIM_NUM,GRID_NUM), contains, for each\n% grid, the level of the Clenshaw-Curtis rule in each dimension.\n%\n% Output, integer GRID_ORDER(DIM_NUM,GRID_NUM), contains, for each\n% grid, the order of the Clenshaw-Curtis rule in each dimension.\n%\n% Output, real GRID_POINT(DIM_NUM,POINT_NUM), contains\n% a list of all the abscissas of all the rules, listed one grid at\n% a time. If a point occurs in several grids, it will be listed\n% several times.\n%\n\n%\n% Outer loop generates LEVEL's from LEVEL_MIN to LEVEL_MAX.\n%\n point_num = 0;\n grid_num = 0;\n\n for level = level_min : level_max\n%\n% Middle loop generates next partition that adds up to LEVEL.\n%\n level_1d = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n%\n% Inner (hidden) loop generates all CC points corresponding to given grid.\n%\n order_1d = cc_level_to_order ( dim_num, level_1d );\n\n order_nd = prod ( order_1d(1:dim_num) );\n\n grid_point(1:dim_num,point_num+1:point_num+order_nd) = cc_grid ( ...\n dim_num, order_1d, order_nd );\n\n point_num = point_num + order_nd;\n\n grid_num = grid_num + 1;\n grid_level(1:dim_num,grid_num) = level_1d(1:dim_num);\n grid_order(1:dim_num,grid_num) = order_1d(1:dim_num);\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cc_display/cc_levels_minmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8670357512127873, "lm_q1q2_score": 0.7705856532720653}} {"text": "function vObjRef=relVecAdd(vObsFrame,vObjInFrame)\n%%RELVECADD Special relativistic addition of velocity vectors. In the\n% inertial reference coordinate system, an observer moves with\n% constant velocity vObsFrame. In the coordinate system of the\n% observer, an object moves with constant velocity vObjInFrame.\n% This computes the velocity of the observed object in the\n% inertial reference frame. Under special relativity, it is not\n% just vObsFrame+vObjInFrame as it is in Newtonian mechanics.\n%\n%INPUTS: vObsFrame The 3XN set of N velocity vectors in meters per second\n% of the observer with respect to the inertial reference\n% coordinate system. The magnitude of the velocity must\n% be less than the speed of light.\n% vObjInFrame The 3XN set of N velocity vectors in meters per second\n% of the object with respect to the observer's coordinate\n% system. The magnitude of the velocity must be less than\n% or equal to the speed of light.\n%\n%OUTPUTS: vObjRef The 3XN set of velocity vectors in vObjInFrame\n% transformed into the inertial reference coordinate\n% system.\n%\n%The formulae for special relativistic velocity addition is derived in\n%Chapter 1.4 of [1]. The magnitudes of vObsFrame and vObjInFrame must both\n%be less than the speed of light (Constants.speedOfLight).\n%\n%REFERENCES:\n%[1] G. Ludyk, Einstein in Matrix Form: Exact Derivation of the Theory of\n% Special and General Relativity without Tensors. Heidelberg: Springer,\n% 2013.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nc=Constants.speedOfLight;\n\nv=vObsFrame;\nu=vObjInFrame;\n\n%The magnitudes of all of the v vectors.\nvMag=sqrt(sum(v.*v,1));\n\ngamma=1./sqrt(1-vMag.^2/c^2);\n\n%v^T*u for each of the velocity vectors.\nuv=sum(v.*u,1);\n\nNum=v+u+bsxfun(@times,(1./gamma-1),(u-bsxfun(@times,(uv./vMag.^2),v)));\nDenom=1+uv/c^2;\n\nvObjRef=bsxfun(@rdivide,Num,Denom);\n\n%If vMag=0 for any of the vectors, then NaNs will appear. In such an\n%instance, the correct solution is vObjInFrame, because the frame is not\n%moving.\ncolSel=any(~isfinite(vObjRef),1);\nvObjRef(:,colSel)=u(:,colSel);\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/Relativity/relVecAdd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7705694381194033}} {"text": "function [a,d]=dualdiag(w,b)\n%DUALDIAG Simultaneous diagonalisation of two hermitian matrices [A,D]=(W,B)\n% Given two hermitian matrices W and B with W positive definite, this routine\n% calculates A such that A'*W*A=I and A'*B*A=diag(D). The D will be in descending order.\n%\n% Suppose we have several N-dimensional data row-vectors arising from each of C different classes of data.\n% for each class, c, we can form the mean data vector m(c) and the within-class covariance matrix W(c)\n% We can then form the between class covariance matrix B by taking the covariance of the mean vectors m(1), m(2), ...\n% and also the averaged within-class covariance matrix W by averaging W(1), W(2), ...\n% If we then take A=dualdiag(W,B) and postmultiply all our original data vectors by A, we obtain new\n% data vectors for which the average within-class covariance matrix is the identity and for which\n% the first few components contain most of the information that is useful in discriminating between classes.\n\n% An alternative algorithm that is 20% faster but slightly less accurate is:\n% n=size(w,1);\n% [v,l]=eig(w\\b);\n% [s,i]=sort(-diag(l));\n% s=-s;\n% d=l(i*(n+1)-n);\n% q=sqrt(diag(v'*w*v))'.^(-1);\n% a=v(:,i).*q(ones(n,1),i);\n\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: dualdiag.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[y,l]=eig(w+w');\nz=y*diag(sqrt(diag(l*0.5)).^(-1));\n[u,s,v]=svd(z'*(b+b')*z);\nd=diag(s)*0.5;\na=z*u;\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/dualdiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.770564530382486}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all; %close all; clc;\n\n%% Physical parameters\n% E: modulus of elasticity\n% A: area of cross section\n% L: length of bar\nE=2e11; A=12.5e-4; L=[0.75,0.75]; \n\n%% Build Elements\n% numberElements: number of elements\nnumberElements=2; \n% numberNodes: number of nodes\nnumberNodes=3;\n% generation of coordinates and connectivities\nelementNodes=[1 2;2 3];\nnodeCoordinates=[0 0.75 1.5];\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=L(e)/2;\n invJacobian=1/detJacobian;\n ngp = 2;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(2)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL2(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A;\n force(elementDof) = force(elementDof)+...\n 60000*shape'*detJacobian*w(ip);\n end\nend \n \n%% BCs and solution\n% prescribed dofs\nprescribedDof = [1];\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactions(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\n\n%% Stress\nstress = zeros(numberElements,1);\nfor e=1:numberElements; \n stress(elementNodes(e,:)) = E*B*displacements(elementNodes(e,:));\nend\n\n%% Exact solutions\nx = 0:0.1:1.5;\ndisplacements_exact=(90000*x-30000*x.^2)/(E*A);\nstress_exact=-((60000*x)-90000)/A;\n\n%% plot figures\nfigure(1)\n\n% Displacements\nsubplot(1,2,1); hold on;\nplot(nodeCoordinates,displacements,'-.sb')\nplot(x,displacements_exact,'-r'); hold off;\nxlabel('x'); ylabel('displacement, u'); \nlegend('FEM','Exact Solution',2);\n\n% Stress\nsubplot(1,2,2); hold on;\nstairs(nodeCoordinates,stress,'-.sb')\nplot(x,stress_exact,'-r'); hold off;\nxlabel('x'); ylabel('stress, \\sigma'); \nlegend('FEM','Exact Solution',1);\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/FEM/BarIsoParametric/HWproblem1adIso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.770564525941811}} {"text": "function sphere = makeSphere(Nx, Ny, Nz, radius, plot_sphere, binary)\n%MAKESPHERE Create a binary map of a sphere within a 3D grid.\n%\n% DESCRIPTION:\n% makeSphere creates a binary map of a spherical shell (using an\n% extension of the midpoint circle algorithm) within a\n% three-dimensional grid. The sphere position is denoted by 1's in\n% the matrix with 0's elsewhere. If the Boolean input parameter\n% \"binary\" is set to false (the default), the sphere map is returned\n% as a double precision matrix. If it is set to true, the map is\n% returned as a logical matrix.\n%\n% USAGE:\n% sphere = makeSphere(Nx, Ny, Nz, radius)\n% sphere = makeSphere(Nx, Ny, Nz, radius, plot_sphere)\n% sphere = makeSphere(Nx, Ny, Nz, radius, plot_sphere, binary)\n% sphere = makeSphere(Nx, Ny, Nz, radius, [], binary)\n%\n% INPUTS:\n% Nx, Ny, Nz - size of the 3D grid [grid points]\n% radius - sphere radius [grid points]\n%\n% OPTIONAL INPUTS:\n% plot_sphere - Boolean controlling whether the sphere is\n% plotted using voxelPlot (default = false)\n% binary - Boolean controlling whether the sphere map is\n% returned as a double precision matrix (false) or\n% a logical matrix (true) (default = false)\n%\n% OUTPUTS:\n% sphere - 3D binary map of a sphere\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 16th June 2009\n% last update - 20th 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 makeBall, makeCartSphere, makeCircle, makeSphericalSection\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n% check for plot_sphere input\nif nargin < 5 || isempty(plot_sphere)\n plot_sphere = false;\nend\n\n% check for binary input\nif nargin < 6 || isempty(binary)\n binary = false;\nend\n\n% enforce a centered sphere\ncx = floor(Nx/2)+1;\ncy = floor(Ny/2)+1;\ncz = floor(Nz/2)+1;\n\n% preallocate the storage variable\nif binary\n sphere = false(Nx, Ny, Nz);\nelse\n sphere = zeros(Nx, Ny, Nz);\nend\n\n% create a guide circle from which the individal radii can be extracted\nguide_circle = makeCircle(Ny, Nx, cy, cx, radius);\n\n% step through the guide circle points and create partially filled discs\ncenterpoints = (cx - radius):cx;\nreflection_offset = length(centerpoints):-1:2;\nfor centerpoint_index = 1:length(centerpoints)\n \n % extract the current row from the guide circle\n row_data = guide_circle(:, centerpoints(centerpoint_index));\n\n % add an index to the grid points in the current row\n row_index = row_data.*(1:length(row_data)).';\n \n % calculate the radius \n swept_radius = (max(row_index) - min(row_index(row_index ~= 0)))/2;\n \n % create a circle to add to the sphere\n circle = makeCircle(Ny, Nz, cy, cz, swept_radius);\n\n % make an empty fill matrix\n if binary\n circle_fill = false(Ny, Nz);\n else\n circle_fill = zeros(Ny, Nz);\n end\n \n % fill in the circle line by line\n fill_centerpoints = (cz - swept_radius):(cz + swept_radius);\n for fill_centerpoint_index = 1:length(fill_centerpoints)\n \n % extract the first row\n row_data = circle(:, fill_centerpoints(fill_centerpoint_index));\n \n % add an index to the grid points in the current row\n row_index = row_data.*(1:length(row_data)).';\n \n % calculate the diameter\n start_index = min(row_index(row_index ~= 0));\n stop_index = max(row_index);\n \n % count how many points on the line\n num_points = sum(row_data);\n \n % fill in the line\n if start_index ~= stop_index && (stop_index - start_index) >= num_points\n circle_fill(start_index + num_points/2:stop_index - num_points /2, fill_centerpoints(fill_centerpoint_index)) = 1;\n end\n end\n \n % remove points from the filled circle that existed in the previous\n % layer\n if centerpoint_index == 1\n sphere(centerpoints(centerpoint_index), :, :) = circle + circle_fill;\n prev_circle = circle + circle_fill;\n else\n prev_circle_alt = circle + circle_fill;\n circle_fill = circle_fill - prev_circle;\n circle_fill(circle_fill < 0) = 0;\n sphere(centerpoints(centerpoint_index), :, :) = circle + circle_fill;\n prev_circle = prev_circle_alt;\n end\n \n % create the other half of the sphere at the same time\n if centerpoint_index ~= length(centerpoints)\n sphere(cx + reflection_offset(centerpoint_index) - 1, :, :) = sphere(centerpoints(centerpoint_index), :, :);\n end\nend\n\n% plot results\nif plot_sphere\n voxelPlot(double(sphere));\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/makeSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7704786879319014}} {"text": "%% CUBEMAXWELLSADDLE solves Maxwell type equations in a cube using linear order element.\n% This is a special case of div u = g being nozero.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear; close all;\n\n%% Defacult setting\n[node,elem] = cubemesh([-1,1,-1,1,-1,1],1);\n%%\npde.J = @(p) [sin(p(:,1)).*cos(p(:,2)).*sin(p(:,3)), ...\n cos(p(:,1)).*sin(p(:,2)).*sin(p(:,3)), ...\n 2*cos(p(:,1)).*cos(p(:,2)).*cos(p(:,3))];\npde.exactu = @(p)[0*p(:,1), 0*p(:,2), ...\n cos(p(:,1)).*cos(p(:,2)).*cos(p(:,3))];\npde.g_D = pde.exactu;\npde.curlu = @(p) [-cos(p(:,1)).*sin(p(:,2)).*cos(p(:,3)), ...\n sin(p(:,1)).*cos(p(:,2)).*cos(p(:,3)), 0*p(:,3)];\npde.g = @(p) -cos(p(:,1)).*cos(p(:,2)).*sin(p(:,3));\npde.mu = 1;\n\n%%\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.printlevel = 0;\n% option.solver = 'direct';\noption.solver = 'mg';\noption.solver = 'diag';\n\n%% Parameters\nmaxIt = 3; \nN = zeros(maxIt,1); \nh = zeros(maxIt,1);\nenergyErr = zeros(maxIt,1);\nL2Err = zeros(maxIt,1);\nuIuhErr = zeros(maxIt,1);\n\n%% Finite Element Method \nfor k = 1:maxIt \n [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag); \n [soln,eqn,info] = Maxwell1saddle(node,elem,bdFlag,pde,option); \n u = soln.u;\n fprintf('\\n\\n # of DoFs = %d \\n',length(u));\n % compute error\n uI = edgeinterpolate1(pde.exactu,node,eqn.edge);\n energyErr(k) = getHcurlerror3ND1(node,elem,pde.curlu,u);\n L2Err(k) = getL2error3ND1(node,elem,pde.exactu,u);\n uIuhErr(k) = sqrt((u-uI)'*(eqn.A)*(u-uI)); \n% L2Err(k) = sqrt((u-uI)'*(eqn.M)*(u-uI)); \n fprintf('\\n ||curl(u-u_h)|| is %g \\n',energyErr(k))\n N(k) = length(u);\n h(k) = 1./(size(node,1)^(1/3)-1); \nend\n\n%% Plot convergence rates\nfigure(1);\nshowrateh3(h,energyErr,1,'k-+','|| curl (u-u_h) ||',...\n h,uIuhErr,1,'r-+','|| curl (u_I-u_h) ||',...\n h,L2Err,1,'b-+','|| u-u_h||');", "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/cubeMaxwellSaddle1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7704786735964908}} {"text": "function [ n_data, a, x, fx ] = chi_square_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CHI_SQUARE_CDF_VALUES returns some values of the Chi-Square CDF.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`ContinuousDistributions`\"]\n% dist = ChiSquareDistribution [ df ]\n% CDF [ dist, x ]\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% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer A, 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 = 21;\n\n a_vec = [ ...\n 1, 2, 1, 2, ...\n 1, 2, 3, 4, ...\n 1, 2, 3, 4, ...\n 5, 3, 3, 3, ...\n 3, 3, 10, 10, ...\n 10 ];\n\n fx_vec = [ ...\n 0.7965567455405796E-01, ...\n 0.4987520807317687E-02, ... \n 0.1124629160182849E+00, ...\n 0.9950166250831946E-02, ...\n 0.4729107431344619E+00, ... \n 0.1812692469220181E+00, ... \n 0.5975750516063926E-01, ... \n 0.1752309630642177E-01, ... \n 0.6826894921370859E+00, ... \n 0.3934693402873666E+00, ... \n 0.1987480430987992E+00, ... \n 0.9020401043104986E-01, ... \n 0.3743422675270363E-01, ... \n 0.4275932955291202E+00, ... \n 0.6083748237289110E+00, ... \n 0.7385358700508894E+00, ... \n 0.8282028557032669E+00, ... \n 0.8883897749052874E+00, ... \n 0.1721156299558408E-03, ... \n 0.3659846827343712E-02, ... \n 0.1857593622214067E-01 ];\n\n x_vec = [ ...\n 0.01E+00, ... \n 0.01E+00, ... \n 0.02E+00, ... \n 0.02E+00, ... \n 0.40E+00, ... \n 0.40E+00, ... \n 0.40E+00, ... \n 0.40E+00, ... \n 1.00E+00, ... \n 1.00E+00, ... \n 1.00E+00, ... \n 1.00E+00, ... \n 1.00E+00, ... \n 2.00E+00, ... \n 3.00E+00, ... \n 4.00E+00, ... \n 5.00E+00, ... \n 6.00E+00, ... \n 1.00E+00, ... \n 2.00E+00, ... \n 3.00E+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;\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/asa091/chi_square_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7704786728908215}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1 \n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the \n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\n\nt = zeros(1, K);\nfor i = 1:length(idx)\n for j = 1:K\n temp = centroids(j, :) - X(i, :);\n t(j) = temp * temp';\n end\n [~, index] = min(t);\n idx(i) = index;\nend\n\n% =============================================================\n\nend\n\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-ex7/ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8962513793687401, "lm_q1q2_score": 0.7704748221878174}} {"text": "% DEMO -- Chebyshev Polynomial Interpolation Order vs Accuracy\n% UPDATED -- October 28, 2013\n% Written by Matthew Kelly, Cornell University\n%\n%\n% This script demonstrates how the accuracy of a chebyshev approximation is\n% dependant on the order of the underlying polynomial.\n%\n% RESULTS:\n% The accuracy is very bad if the order is too small, but then rapidly\n% improves until it reaches machine precision. The accuracy of the\n% derivative will get slowly worse for very large order apprimations due\n% to the compounding of rounding errors in the matrix multiplication.\n%\n\n\n%% General Settings\nclear; clc;\n\n%What order should the approximation be?\norderRange = [2,1000];\norderNum = 20;\norderList = unique(round(logspace(...\n log10(orderRange(1)),...\n log10(orderRange(2)),...\n orderNum))); \n\n%How many points should be used for error calculations and plotting?\nnTime = 1000;\n\n%What domain should we be looking at?\nd = [-2,1];\n\n%Time for use in plots\ntime = linspace(d(1),d(2),nTime);\n\n%Set up the input/output struct:\nIO.domain = d;\nIO.userFunc = @testFunction;\n\n%Set up the data logging:\nN = length(orderList);\ncpuTime = zeros(N,1);\nmaxError = zeros(N,2);\nmeanError = zeros(N,2);\n\n%Run the calculations:\nfor i=1:N\n disp(['Order: ' num2str(orderList(i))])\n tic;\n f = chebyshevFit(IO, orderList(i)); \n [y, Dy] = chebyshevInterpolate(f,time,d);\n cpuTime(i) = toc;\n [g,Dg] = testFunction(time);\n e = abs(g-y);\n De = abs(Dg-Dy);\n maxError(i,:) = [max(e),max(De)];\n meanError(i,:) = [mean(e),mean(De)];\nend\n\n%Make nice plots:\n figure(403); clf;\n subplot(3,2,1)\n loglog(orderList,cpuTime)\n title('CPU Time')\n xlabel('Order of Chebyshev Polynomial')\n ylabel('Time (s)')\n subplot(3,2,2)\n plot(time,testFunction(time))\n title('Function')\n xlabel('Input')\n ylabel('Output')\n subplot(3,2,3)\n loglog(orderList,maxError(:,1))\n title('Max Error in Function')\n xlabel('Order of Chebyshev Polynomial')\n subplot(3,2,5)\n loglog(orderList,meanError(:,1))\n title('Mean Error in Function')\n xlabel('Order of Chebyshev Polynomial')\n subplot(3,2,4)\n loglog(orderList,maxError(:,2))\n title('Max Error in Derivative')\n xlabel('Order of Chebyshev Polynomial')\n subplot(3,2,6)\n loglog(orderList,meanError(:,2))\n title('Mean Error in Derivative')\n xlabel('Order of Chebyshev Polynomial')\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/chebyshevPolynomials/DEMO_4_Order_vs_Accuracy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7704748088407791}} {"text": "function [tfr,t,f] = tfrpmh(x,t,N,h,trace);\n%TFRPMH Pseudo Margenau-Hill time-frequency distribution.\n% [TFR,T,F]=TFRPMH(X,T,N,H,TRACE) computes the Pseudo Margenau-Hill \n% distribution of a discrete-time signal X, or the\n% cross Pseudo Margenau-Hill representation between two signals. \n% \n% X : signal if auto-PMH, or [X1,X2] if cross-PMH.\n% T : time instant(s) (default : 1:length(X)).\n% N : number of frequency bins (default : length(X)).\n% H : frequency smoothing window, H(0) being forced to 1\n% (default : Hamming(N/4)). \n% TRACE : if nonzero, the progression of the algorithm is shown\n% (default : 0).\n% TFR : time-frequency representation. When called without \n% output arguments, TFRPMH runs TFRQVIEW.\n% F : vector of normalized frequencies.\n%\n% Example :\n% sig=fmlin(128,0.1,0.4); t=1:128; \n% h=tftb_window(63,'Kaiser'); tfrpmh(sig,t,128,h,1);\n% \n% See also all the time-frequency representations listed in\n% the file CONTENTS (TFR*)\n\n% F. Auger, May-August 1994, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n[xrow,xcol] = size(x);\nif (nargin < 1),\n error('At least 1 parameter is required');\nelseif nargin<=2,\n N=xrow;\nend;\n\nhlength=floor(N/4);\nhlength=hlength+1-rem(hlength,2);\n\nif (nargin == 1),\n t=1:xrow; h = tftb_window(hlength); trace=0;\nelseif (nargin == 2 | nargin == 3),\n h = tftb_window(hlength); trace = 0;\nelseif (nargin == 4),\n trace = 0;\nend;\n\nif (N<0),\n error('N must be greater than zero');\nend;\n[trow,tcol] = size(t);\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nelseif (trow~=1),\n error('T must only have one row'); \nelseif (2^nextpow2(N)~=N), %(rem(log(N)/log(2),1)~=0),\n fprintf('For a faster computation, N should be a power of two\\n');\nend; \n\n[hrow,hcol]=size(h); Lh=(hrow-1)/2; h=h/h(Lh+1);\nif (hcol~=1)|(rem(hrow,2)==0),\n error('H must be a smoothing window with odd length');\nend;\n\ntfr= zeros (N,tcol) ; \nif trace, disp('Pseudo Margenau-Hill distribution'); end;\nfor icol=1:tcol,\n ti= t(icol); tau=-min([round(N/2)-1,Lh,xrow-ti]):min([round(N/2)-1,Lh,ti-1]);\n indices= rem(N+tau,N)+1;\n if trace, disprog(icol,tcol,10); end;\n tfr(indices,icol)=h(Lh+1+tau).*x(ti,1).*conj(x(ti-tau,xcol));\nend; \nif trace, fprintf('\\n'); end;\ntfr= real(fft(tfr)); \n\nif (nargout==0),\n tfrqview(tfr,x,t,'tfrpmh',h);\nelseif (nargout==3),\n if rem(N,2)==0, \n f=[0:N/2-1 -N/2:-1]'/N;\n else\n f=[0:(N-1)/2 -(N-1)/2:-1]'/N; \n end;\nend;\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrpmh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7704492256026744}} {"text": "function mappedX = diffusion_maps(X, no_dims, t, sigma)\n%DIFFUSION_MAPS Runs the diffusion map algorithm\n%\n% mappedX = diffusion_maps(X, no_dims, t, sigma)\n%\n% The functions runs the diffusion map algorithm on dataset X to reduce it \n% to dimensionality no_dims. The variable sigma is the variance of the Gaussian\n% used in the affinity computation (default = 1). The variable alpha\n% determines the operator that is applied on the graph (default = 1).\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 % Give memory warning\n if size(X, 1) > 3000\n warning(['Due to the large number of instances (' num2str(size(X, 1)) '), diffusion maps may run out of memory.']);\n end\n \n % Normalize data\n X = double(X);\n X = X - min(X(:));\n X = X / max(X(:));\n\n % Compute Gaussian kernel matrix\n disp(['Compute Markov forward transition probability matrix with ' num2str(t) ' timesteps...']);\n sumX = sum(X .^ 2, 2);\n K = exp(-bsxfun(@plus, sumX, bsxfun(@plus, sumX', -2 * (X * X'))) ./ (2 .* sigma ^ 2));\n \n % Compute Markov probability matrix with t timesteps\n p = sum(K, 1)';\n K = K ./ ((p * p') .^ t);\n p = sqrt(sum(K, 1))';\n K = K ./ (p * p');\n \n % Perform economy-size SVD\n disp('Perform eigendecomposition...');\n [U, S, V] = svd(K, 0);\n U = bsxfun(@rdivide, U, U(:,1)); \n mappedX = U(:,2:no_dims + 1);\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/drtoolbox/techniques/diffusion_maps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7704492210860324}} {"text": "function tq = gettrimeshquan( p, t)\n% tq.ds - edge length connecting node\n% 2-3, 3-1, and 1-2 respectively\n% tq.J - 0.5*element area\n% tq.vang - angle assocaited with node 1, 2, 3 respectively\n% \n \nedge = [2 3 1\n 3 1 2] ;\n\nne = size( t, 1) ;\n\np1 = p(t(:, edge(1,:))',:) ;\np2 = p(t(:, edge(2,:))',:) ;\n\n%\nds = reshape(sqrt(sum((p1 - p2).^2,2)), 3, ne )' ;\n\nidxcm = [ 1 2 3\n 2 3 1\n 3 1 2 ] ;\n\n% Internal angle \ntq.vang = zeros(ne,3) ;\nfor i = 1: 3\n tq.vang(:,i) = acos((-ds(:,idxcm(i,1)).^2 + ds(:,idxcm(i,2)).^2 + ...\n ds(:,idxcm(i,3)).^2)./(2*ds(:,idxcm(i,2)).*ds(:,idxcm(i,3)))) ;\nend\n%\n\n% Length \ntq.ds = ds ;\n\n% Jacobian\nxr = 0.5*(p(t(:,2),:) - p(t(:,1),:)) ;\nxs = 0.5*(p(t(:,3),:) - p(t(:,1),:)) ; \n\ntq.J = (xr(:,1).*xs(:,2) - xs(:,1).*xr(:,2)) ;\n\n% idxtb = find( vang' < 25*pi/180 ) ;\n% ietb = unique(ceil(idxtb/3)) ;\n\n%\n% Bank, Randolph E., \n% PLTMG: A Software Package for Solving Elliptic Partial Differential Equations, \n% User's Guide 6.0, Society for Industrial and Applied Mathematics, Philadelphia, PA, 1990.\ntq.qm = 4*sqrt(3)*(2*tq.J)./(sum(tq.ds.^2,2)) ; ", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/gettrimeshquan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030094, "lm_q2_score": 0.8152324826183821, "lm_q1q2_score": 0.770390389937328}} {"text": "\n\nfunction call_price=american_call_perpetual(S, K, r, q, sigma)\n\n\n%--------------------------------------------------------------------------\n%\n% DESCRIPTION:\n%\n% Price for an american perpetual call option\n%\n%\n% Reference:\n%\n% John Hull, \"Options, Futures and other Derivative Securities\",\n% Prentice-Hall, second edition, 1993.\n% \n%--------------------------------------------------------------------------\n%\n% INPUTS:\n%\n% S: spot price\n% K: exercice price\n% r: interest rate\n% q: dividend yield \n% sigma: volatility\n%\n%--------------------------------------------------------------------------\n%\n% OUTPUT:\n%\n% call_price: price of a call option\n%\n%--------------------------------------------------------------------------\n%\n% Author: Paolo Z., February 2012\n%\n%--------------------------------------------------------------------------\n\n\nsigma_sqr=(sigma^2);\nh1 = 0.5 - ((r-q)/sigma_sqr);\nh1 = h1 + sqrt( (((r-q)/sigma_sqr-0.5)^2)+2.0*r/sigma_sqr );\n\ncall_price=(K/(h1-1.0))*( (((h1-1.0)/h1)*(S/K))^h1 );\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35351-option-pricing-package/american_call_perpetual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7703675944229154}} {"text": "function Y=runMLP(X,Wx,Wy)\n% The matrix implementation of the two-layer Multilayer Perceptron (MLP) neural networks.\n%\n% Author: Marcelo Augusto Costa Fernandes\n% DCA - CT - UFRN\n% mfernandes@dca.ufrn.br\n%\n% Input parameters:\n% X: Input neural network. X is a (p x K) dimensional matrix, where p is a number of the inputs and K >= 1.\n% Wx: Hidden layer weight matrix. Wx is a (H x p+1) dimensional matrix.\n% Wy: Output layer weight matrix. Wy is a (m x H+1) dimensional matrix.\n%\n% Output parameters:\n% Y: Outpuy neural network. Y is a (m x K) dimensional matrix, where m is a number of the output neurons and K >= 1.\n\n[p1 N] = size (X);\n\nbias = -1;\n\nX = [bias*ones(1,N) ; X];\n\nV = Wx*X;\nZ = 1./(1+exp(-V));\n\nS = [bias*ones(1,N);Z];\nG = Wy*S;\n\nY = 1./(1+exp(-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/36253-the-matrix-implementation-of-the-two-layer-multilayer-perceptron-mlp-neural-networks/runMLP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7703675825718519}} {"text": "function [ x, w ] = hermite_ek_compute ( n )\n\n%*****************************************************************************80\n%\n%% HERMITE_EK_COMPUTE computes a Gauss-Hermite quadrature rule.\n%\n% Discussion:\n%\n% The code uses an algorithm by Elhay and Kautsky.\n%\n% The abscissas are the zeros of the N-th order Hermite polynomial.\n%\n% The integral:\n%\n% integral ( -oo < x < +oo ) exp ( - x * x ) * 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% 19 April 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the number of abscissas.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = gamma ( 0.5 );\n%\n% Define the Jacobi matrix.\n%\n bj = zeros ( n, 1 );\n for i = 1 : n\n bj(i) = i / 2.0;\n end\n bj(1:n) = sqrt ( bj(1:n) );\n\n x = zeros ( n, 1 );\n\n w = zeros ( n, 1 );\n w(1) = sqrt ( zemu );\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\n\n w(1:n) = w(1:n).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/burgers_solution/hermite_ek_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7703109525260688}} {"text": "function [ x, seed ] = normal_truncated_ab_sample ( mu, s, a, b, seed )\n\n%*****************************************************************************80\n%\n%% NORMAL_TRUNCATED_AB_SAMPLE samples the truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real MU, S, the mean and standard deviation of the\n% parent Normal distribution.\n%\n% Input, real A, B, the lower and upper truncation limits.\n%\n% Input/output, integer SEED, a seed for the random number\n% generator.\n%\n% Output, real X, a sample of the PDF.\n%\n alpha = ( a - mu ) / s;\n beta = ( b - mu ) / s;\n\n alpha_cdf = normal_01_cdf ( alpha );\n beta_cdf = normal_01_cdf ( beta );\n\n [ u, seed ] = r8_uniform_01 ( seed );\n xi_cdf = alpha_cdf + u * ( beta_cdf - alpha_cdf );\n xi = normal_01_cdf_inv ( xi_cdf );\n\n x = mu + s * xi;\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/normal_truncated_ab_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7703109506239592}} {"text": "function r=ksrmv(x,y,hx,z)\n% KSRMV Multivariate kernel smoothing regression\n%\n% r=ksrmv(x,y) returns the Gaussian kernel regression in structure r such that\n% r.f(r.x) = y(x) + e\n% The bandwidth and number of samples are also stored in r.h and r.n\n% respectively.\n%\n% r=ksrmv(x,y,h) performs the regression using the specified bandwidth, h.\n%\n% r=ksrmv(x,y,h,z) calculates the regression at location z (default z=x).\n%\n% Algorithm\n% The kernel regression is a non-parametric approach to estimate the\n% conditional expectation of a random variable:\n%\n% E(Y|X) = f(X)\n%\n% where f is a non-parametric function. Based on the kernel density\n% estimation, this code implements the Nadaraya-Watson kernel regression\n% using the Gaussian kernel as follows:\n%\n% f(x) = sum(kerf((x-X)/h).*Y)/sum(kerf((x-X)/h))\n%\n% See also gkde, ksdensity, ksr\n\n% Example 1: smoothing a noised logo\n%{\nL = 40*membrane(1,25)+randn(51);\n[x,y]=meshgrid(0:50);\nr=ksrmv([x(:) y(:)],L(:));\nLr=L;\nLr(:)=r.f;\nsubplot(121), surf(x,y,L)\nsubplot(122), surf(x,y,Lr)\n%}\n% Example 2: smoothing noised peaks with 20% missing data\n%{\nL = 10*peaks(50)+randn(50);\nI = ceil(rand(500,1)*2500);\nL(I) = NaN;\n[x,y]=meshgrid(1:50);\nr=ksrmv([x(:) y(:)],L(:));\nLr=L;\nLr(:)=r.f;\nsubplot(121), surf(x,y,L)\nsubplot(122), surf(x,y,Lr)\n%}\n\n% By Yi Cao at Cranfield University on 20 March 2008.\n%\n\n% Check input and output\nerror(nargchk(2,4,nargin));\nerror(nargoutchk(0,1,nargout));\ny=y(:);\nif size(x,1)~=size(y,1)\n error('x and y have different rows.');\nend\nd=size(x,2);\n\n% Default parameters\nif nargin<4\n z=x;\nelseif size(z,2)~=d\n error('z must have the same number of columns as x.')\nend\nr.x=z;\nN=size(z,1);\n\n% clean missing or invalid data points\ninv=(y~=y);\nx(inv,:)=[];\ny(inv)=[];\nr.n=numel(y);\n\nif nargin<3\n % optimal bandwidth suggested by Bowman and Azzalini (1997) p.31\n hy=median(abs(y-median(y)))/0.6745*(4/(d+2)/r.n)^(1/(d+4));\n hx=median(abs(x-repmat(median(x),r.n,1)))/0.6745*(4/(d+2)/r.n)^(1/(d+4));\n hx=sqrt(hy*hx);\nelseif size(hx,2)~=d\n error('h must be a scalar.')\nend\nr.h=hx;\n% \n% % Vectorization, Not suitable for large data set\n% % Firstly, diagnal matrix for bandwidth\n% H=diag(1./hx);\n% \n% % Then scale X by the bendwidth\n% X=r.x*H;\n% \n% % Square of X\n% X2=sum(X.*X,2)/2;\n% \n% % Scale Xi\n% C=H*x';\n% \n% % Square of Xi\n% C2=sum(C.*C)/2;\n% \n% % D = ((X - Xi) / H)^T ((X - Xi) / H)\n% D=C2(ones(N,1),:)+X2(:,ones(1,r.n))-X*C;\n% \n% % only elements whos values < 12 need to evaluated since exp(-12) = 6.1e-6\n% idx=D<12;\n% \n% % prepare local variable\n% Z=zeros(N,r.n);\n% \n% % Z = exp(-D)\n% Z(idx)=exp(-D(idx));\n% \n% % f(x) = sum Z*Yi / sum Z\n% r.f=sum(Z.*y(:,ones(1,N))',2)./sum(Z,2);\n\n% Improved efficient code\n\n% Scaling first\nH=diag(1./hx);\nx=x*H;\nx1=r.x*H;\n\n% Gaussian kernel function\nkerf=@(z)exp(-sum(z.*z,2)/2);\n\n% allocate memory\nr.f=zeros(N,1);\n\n% Loop through each regression point\nfor k=1:N\n % scaled deference from regression point\n xx=abs(x-x1(k+zeros(r.n,1),:));\n % select neighbours using exp(-5^2/2)<5e-6\n idx=all(xx<5,2);\n % kernel function\n z=kerf(xx(idx,:));\n % regression\n r.f(k)=sum(z.*y(idx))/sum(z);\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/19279-multivariant-kernel-regression-and-smoothing/ksrmv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7703109487983014}} {"text": "function [PBarVals,dPBarValsdTheta,d2PBarValsdTheta2]=LegendreCos(theta,M,scalFactor)\n%%LEGENDRECOS Evaluate the fully associated Legendre functions of\n% cos(theta) of degree n and order m for all n from 0 to M and\n% for each n, m goes from 0 to n. Such a function is typically\n% written as \\bar{P}_{nm}(cos(theta)). Also evaluate\n% D{\\bar{P}_{nm}(cos(theta))} and D2{\\bar{P}_{nm}(cos(theta))},\n% where D{} is the first derivative with respect to theta and\n% D2{} is the second derivative with respect to theta. All of the\n% values can be scaled by a factor of scalFac, if desired, to\n% help prevent overflows with high degrees and orders.\n%\n%INPUTS: theta An angle in radians.\n% maxDeg The maximum degree and order of the output. This must be\n% >=0.\n% scalFactor A scale factor to help prevent overflow of the results. If\n% this parameter is omitted or an empty matrix is passed, the\n% default of 1 is used.\n%\n%OUTPUTS: PBarUVals An instance of the CountingClusterSet class such that\n% PBarVals(n+1,m+1)=scalFac*\\bar{P}_{nm}(cos(theta)).\n% To extract all coefficients as a vector just call\n% PBarUVals(:).\n% dPBarValsdTheta An instance of the CountingClusterSet class such that\n% dPBarValsdTheta(n+1,m+1)=scalFac*D{\\bar{P}_{nm}(cos(theta))}\n% d2PBarValsdTheta2 An instance of the CountingClusterSet class such that\n% d2PBarValsdTheta2(n+1,m+1)=scalFac*D2{\\bar{P}_{nm}(cos(theta))}\n%\n%The definition of associated Legendre polynomial underlying this function\n%is\n% P_(nm)(x)=(1-x^2)^(m/2)*Dm{P(n,x)}\n%where Dm{} represents the mth-order derivative and P(n,x) is the Legendre\n%polynomial having the form\n%P(n,x)=(1/2^n)*sum_{k=0}^n binomial(n,n)*(x-1)^(n-k)*(x+k)^k\n%This definition lacks the Condon-Shortley phase. Adding the phase is the\n%same as multiplying P_(nm)(x) by (-1)^m. The polynomials are fully\n%normalized, meaning that each one is multiplied by\n%N(n,m)=sqrt((2*n+1)*(2-KDelta(m))*factorial(n-m)/factorial(n+m))\n%This is normalization 0 in the changeSpherHarmonicNorm function.\n%\n%Fully normalized associated Legendre polynomials often arise when\n%computing spherical harmonic expansions. When simply evaluating an\n%expansion, one will typically use fully normalized Legendre functions that\n%have been divided by abs(sin(theta))^m as in [1]. However, when fitting\n%coefficients for such an expansion, one will typically need the function\n%values directly, which is what this function provides.\n%\n%This function just calls the function NALegendreCosRat and then multiplies\n%out the denominators.\n%\n%EXAMPLE:\n%One can see that this function returns the same values as the legendre\n%function of cos(theta) when the proper normalization is selected. However,\n%this function returns more values than legendre, as Matlab's legendre\n%function just returns a vector for a single value of n.\n% M=3;\n% theta=-0.5;\n% PBarVecMatLab=legendre(M,cos(theta));\n% PBarVals=LegendreCos(theta,M);\n% arePolyVals=true;\n% origNormType=0;\n% normType=8;\n% PBarVals=changeSpherHarmonicNorm(PBarVals,origNormType,normType,arePolyVals);\n% PBarVec=PBarVals(M+1,:);\n% ratioCompare=PBarVecMatLab./PBarVec\n%One will see that the ratio is essentially all ones.\n%\n%REFERENCES:\n%[1] S. A. Holmes and W. E. Featherstone, \"A unified approach to the\n% Clenshaw summation and the recursive computation of very high degree\n% and order normalised associated Legendre functions,\" Journal of\n% Geodesy, vol. 76, no. 5, pp. 279-299, May 2002.\n%\n%June 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(scalFactor))\n scalFactor=1; \nend\n\nu=abs(sin(theta));\n\nif(nargin<2)\n PBarVals=NALegendreCosRat(theta,M,scalFactor);\n for n=1:M\n um=u;\n for m=1:n\n PBarVals(n+1,m+1)=PBarVals(n+1,m+1)*um;\n um=um*u;\n end\n end\nelseif(nargout==2)\n [PBarVals,dPBarValsdTheta]=NALegendreCosRat(theta,M,scalFactor);\n for n=1:M\n um=u;\n for m=1:n\n PBarVals(n+1,m+1)=PBarVals(n+1,m+1)*um;\n dPBarValsdTheta(n+1,m+1)=dPBarValsdTheta(n+1,m+1)*um;\n um=um*u;\n end\n end\nelse%nargout==3\n [PBarVals,dPBarValsdTheta,d2PBarValsdTheta2]=NALegendreCosRat(theta,M,scalFactor);\n for n=1:M\n um=u;\n for m=1:n\n PBarVals(n+1,m+1)=PBarVals(n+1,m+1)*um;\n dPBarValsdTheta(n+1,m+1)=dPBarValsdTheta(n+1,m+1)*um;\n d2PBarValsdTheta2(n+1,m+1)=d2PBarValsdTheta2(n+1,m+1)*um;\n um=um*u;\n end\n end\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/LegendreCos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.770310935808454}} {"text": "function Chi2 = chistart (D,L,a,ncands,factor)\n%CHISTART: Computes the initial size of the search ellipsoid\n%\n% This routine computes or approximates the initial size of the search\n% ellipsoid. If the requested number of candidates is not more than the\n% dimension + 1, this is done by computing the squared distances of partially\n% conditionally rounded float vectors to the float vector in the metric of the\n% covariance matrix. Otherwise an approximation is used.\n%\n% Input arguments\n% L,D : LtDL-decomposition of the variance-covariance matrix of\n% the float ambiguities (preferably decorrelated)\n% a : float ambiguites (preferably decorrelated)\n% ncands: Requested number of candidates (default = 2)\n% factor: Multiplication factor for the volume of the resulting\n% search ellipsoid (default = 1.5)\n%\n% Output arguments:\n% Chi2 : Size of the search ellipsoid\n\n% ----------------------------------------------------------------------\n% File.....: chistart.m\n% Date.....: 19-MAY-1999\n% Modified.: 05-MAR-2001, by P. Joosten\n% Author...: Peter Joosten\n% Mathematical Geodesy and Positioning\n% Delft University of Technology\n% ----------------------------------------------------------------------\n\n% ------------------\n% --- Initialize ---\n% ------------------\n\nif nargin < 4; ncands = 2 ; end;\nif nargin < 5; factor = 1.5; end;\n\nn = max(size(a));\n\n% ----------------------------------------------------------------------\n% --- Computation depends on the number of candidates to be computed ---\n% ----------------------------------------------------------------------\n\nif ncands <= n+1;\n\n % --------------------------------------------------------\n % --- Computation based on the bootstrapping estimator ---\n % --------------------------------------------------------\n\n Chi = [];\n\n for k = n:-1:0;\n\n afloat = a;\n afixed = a;\n\n for i = n:-1:1;\n\n dw = 0;\n for j = n:-1:i;\n dw = dw + L(j,i) * (afloat(j) - afixed(j));\n end;\n\n afloat(i) = afloat(i) - dw;\n if (i ~= k);\n afixed(i) = round (afloat(i));\n else\n if isequal (afloat(i),afixed(i));\n afixed(i) = round(afixed(i) + 1);\n else\n afixed(i) = round (afloat(i) + sign (afloat(i) - afixed(i)));\n end;\n end;\n\n end;\n\n Chi = [Chi (a-afixed)' * (L'*diag(D)*L)^(-1) * (a-afixed)];\n\n end;\n\n % ---------------------------------------------------------------\n % --- Sort the results, and return the appropriate number ---\n % --- Add an \"eps\", to make sure there is no boundary problem ---\n % ---------------------------------------------------------------\n\n Chi = sort(Chi);\n Chi2 = Chi(ncands) + 1d-6;\n\nelse\n\n % -----------------------------------------------------\n % An approximation for the squared norm is computed ---\n % -----------------------------------------------------\n\n Linv = (L)^(-1);\n Dinv = 1./D;\n\n Vn = (2/n) * (pi ^ (n/2) / gamma(n/2));\n Chi2 = factor * (ncands / sqrt((prod(1 ./ Dinv)) * Vn)) ^ (2/n);\n\nend;\n\n% ----------------------------------------------------------------------\n% End of routine: chistart\n% ----------------------------------------------------------------------\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/positioning/lambda/lambda_v2/chistart_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7703103021417421}} {"text": "function varargout = sph2cart2d(theta, phi, rho)\n%SPH2CART2D Convert spherical coordinates to cartesian coordinates in degrees\n%\n% C = SPH2CART2(THETA, PHI, RHO)\n% C = SPH2CART2(THETA, PHI) (assume rho = 1)\n% C = SPH2CART2(S)\n% [X, Y, Z] = SPH2CART2(THETA, PHI, RHO);\n%\n% S = [phi theta rho] (spherical coordinate).\n% C = [X Y Z] (cartesian coordinate)\n%\n% The following convention is used:\n% THETA is the colatitude, in degrees, 0 for north pole, +180 degrees for\n% south pole, +90 degrees for points with z=0. \n% PHI is the azimuth, in degrees, defined as matlab cart2sph: angle from\n% Ox axis, counted counter-clockwise.\n% RHO is the distance of the point to the origin.\n% Discussion on choice for convention can be found at:\n% http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf\n%\n% See also:\n% angles3d, cart2sph2d, sph2cart2\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\n% Process input arguments\nif nargin == 1\n phi = theta(:, 2);\n if size(theta, 2) > 2\n rho = theta(:, 3);\n else\n rho = ones(size(phi));\n end\n theta = theta(:, 1);\n \nelseif nargin == 2\n rho = ones(size(theta));\n \nend\n\n% conversion\nrz = rho .* sind(theta);\nx = rz .* cosd(phi);\ny = rz .* sind(phi);\nz = rho .* cosd(theta);\n\n% Process output arguments\nif nargout == 1 || nargout == 0\n varargout{1} = [x, y, z];\n \nelse\n varargout{1} = x;\n varargout{2} = y;\n varargout{3} = z;\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/sph2cart2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.770304006171134}} {"text": "function p = bspeval(d,c,k,u) \n% \n% Function Name: \n% \n% bspeval - Evaluate a univariate B-Spline. \n% \n% Calling Sequence: \n% \n% p = bspeval(d,c,k,u) \n% \n% Parameters: \n% \n% d\t: Degree of the B-Spline. \n% \n% c\t: Control Points, matrix of size (dim,nc). \n% \n% k\t: Knot sequence, row vector of size nk. \n% \n% u\t: Parametric evaluation points, row vector of size nu. \n% \n% p\t: Evaluated points, matrix of size (dim,nu) \n% \n% Description: \n% \n% Evaluate a univariate B-Spline. This function provides an interface to \n% a toolbox 'C' routine. \nnu = numel(u); \n[mc,nc] = size(c); \n % int bspeval(int d, double *c, int mc, int nc, double *k, int nk, double *u,int nu, double *p){ \n % int ierr = 0; \n % int i, s, tmp1, row, col; \n % double tmp2; \n % \n % // Construct the control points \n % double **ctrl = vec2mat(c,mc,nc); \n % \n % // Contruct the evaluated points \np = zeros(mc,nu); % double **pnt = vec2mat(p,mc,nu); \n % \n % // space for the basis functions \nN = zeros(d+1,1); % double *N = (double*) mxMalloc((d+1)*sizeof(double)); \n % \n % // for each parametric point i \nfor col=1:nu % for (col = 0; col < nu; col++) { \n % // find the span of u[col] \n s = findspan(nc-1, d, u(col), k); % s = findspan(nc-1, d, u[col], k); \n N = basisfun(s,u(col),d,k); % basisfun(s, u[col], d, k, N); \n % \n tmp1 = s - d + 1; % tmp1 = s - d; \n for row=1:mc % for (row = 0; row < mc; row++) { \n tmp2 = 0; % tmp2 = 0.0; \n for i=0:d % for (i = 0; i <= d; i++) \n tmp2 = tmp2 + N(i+1)*c(row,tmp1+i); % \ttmp2 += N[i] * ctrl[tmp1+i][row]; \n end % \n p(row,col) = tmp2; % pnt[col][row] = tmp2; \n end % } \nend % } \n % \n % mxFree(N); \n % freevec2mat(pnt); \n % freevec2mat(ctrl); \n % \n % return ierr; \n % } \n", "meta": {"author": "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/bspeval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7702902036709153}} {"text": "% StackExchange Mathematics Q3892375\n% https://math.stackexchange.com/questions/3892375\n% Solve Linear Least Squares with L1 Norm Regularization with Linear\n% Equality and Non Negativity Constraints.\n% References:\n% 1. \n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 27/12/2020\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 0;2165;42; % 500, Very Good!\n% cvx_solver('Gurobi');\n\nhRunTime = tic();\n\ncvx_begin('quiet')\n% cvx_begin()\n % cvx_precision('best');\n variable vX(numCols, 1);\n minimize( 0.5 * sum_square(mA * vX - vB) + (paramLambda * norm(mC * vX, 1)) );\n subject to\n mD * vX == 0;\n vX >= 0;\ncvx_end\n\nrunTime = toc(hRunTime);\n\n% vX = mX(:);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The ', solverString, ' Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\nsCvxSol.vXCvx = vX;\nsCvxSol.cvxOptVal = hObjFun(vX);\n\n\n%% Solution by Projected Gradient Descent\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Method'];\n\nhRunTime = tic();\n\n[vX, mX] = ProjectedGd(zeros(numCols, 1), hG, hP, numIterations, stepSizeGd);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with Momentum\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with Momentum'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdMomentum(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd, stepSizeMomentum);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with Nesterov Acceleration\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with Nesterov Acceleration'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdAccel(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd, stepSizeAccel);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Solution by Projected Gradient Descent with FISTA\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Descent with FISTA Acceleration'];\n\nhRunTime = tic();\n\n[vX, ~, mX] = ProjectedGdFista(zeros(numCols, 1), zeros(numCols, 1), hG, hP, numIterations, stepSizeGd);\n% [vX, mX] = SolveLsFista(zeros(numCols, 1), mA, vB, paramLambda, numIterations, stepSizeGd);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Display Results\n\nfigureIdx = figureIdx + 1;\n\nhFigure = figure('Position', figPosLarge);\n\nhAxes = subplot(2, 1, 1);\nhLineSeries = plot(1:numIterations, 10 * log10(mObjFunValMse));\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nset(get(hAxes, 'Title'), 'String', ['Objective Function Value vs. Optimal Value (CVX)'], ...\n 'FontSize', fontSizeTitle);\nset(get(hAxes, 'XLabel'), 'String', 'Iteration Number', ...\n 'FontSize', fontSizeAxis);\nset(get(hAxes, 'YLabel'), 'String', '$ 10 \\log_{10} {\\left( \\left| f \\left( x \\right) - f \\left( {x}_{CVX} \\right) \\right| \\right)}^{2} $', ...\n 'FontSize', fontSizeAxis, 'Interpreter', 'latex');\nset(hAxes, 'XLim', [1, numIterations]);\nhLegend = ClickableLegend(cLegendString);\n\nhAxes = subplot(2, 1, 2);\nhLineSeries = plot(1:numIterations, 10 * log10(mSolMse));\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nset(get(hAxes, 'Title'), 'String', ['Solution Error Norm'], ...\n 'FontSize', fontSizeTitle);\nset(get(hAxes, 'XLabel'), 'String', 'Iteration Number', ...\n 'FontSize', fontSizeAxis);\nset(get(hAxes, 'YLabel'), 'String', '$ 10 \\log_{10} \\left( {\\left\\| x - {x}_{CVX} \\right\\|}_{2}^{2} \\right) $', ...\n 'FontSize', fontSizeAxis, 'Interpreter', 'latex');\nset(hAxes, 'XLim', [1, numIterations]);\nhLegend = ClickableLegend(cLegendString);\n\nif(generateFigures == ON)\n % saveas(hFigure,['Figure', num2str(figureIdx, figureCounterSpec), '.png']);\n print(hFigure, ['Figure', num2str(figureIdx, figureCounterSpec), '.png'], '-dpng', '-r0'); %1\n cx = var(1);\n cy = var(2);\n varargin(1) = [];\n else\n cx = var;\n cy = varargin{2};\n varargin(1:2) = [];\n end\nelse\n s = sum(img(:));\n cx = imMoment(img, 1, 0)/s;\n cy = imMoment(img, 0, 1)/s;\nend\n\nif ~isempty(varargin)\n m00 = varargin{1};\nelse\n m00 = sum(img(:));\nend\n\n\n% image dimension\ndim = size(img);\nDy = dim(1);\nDx = dim(2);\n\n% compute x and y for each pixel\nIx = repmat((1:Dx), [Dy 1])-cx;\nIy = repmat((1:Dy)', [1 Dx])-cy;\n\n% compute moment\nmu = zeros(size(p));\nfor i = 1:length(p(:))\n d = (p(i)+q(i)) / 2 + 1;\n mu(i) = sum(Ix(:).^p(i) .* Iy(:).^q(i) .* img(:)) / m00^d;\nend\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imCSMoment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.770187090699345}} {"text": "function variance = chi_square_variance ( a )\n\n%*****************************************************************************80\n%\n%% CHI_SQUARE_VARIANCE returns the variance of the central Chi squared PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the parameter of the distribution.\n% 1 <= A.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = 2.0 * a;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/chi_square_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7701615655408643}} {"text": "function [P, lam] = pswf(N, c, dom, output_type)\n%PSWF Prolate spheroidal wave functions.\n% P = PSWF(N, C) returns a CHEBFUN P representing the Nth prolate spheroidal\n% wave function with bandwidth C on the interval [-1,1], i.e., the Nth\n% eigenfunction of the differential eigenvalue problem\n%\n% [(1-x^2)*P(x)')' + (LAM - C^2*x^2)*P(x) = 0,\n%\n% with N = 0,1,2,.... C must be a positive scalar but N may be a vector of\n% non-negative integers, in which case the output is an array-valued CHEBFUN\n% with LENGTH(N) columns. P is scaled so that P'*P = 2/(2N+1), with the sign\n% such that sign(P(0)) = (-1)^(N/2) if N is even and sign(P'(0)) =\n% (-1)^((N-1)/2) if N is odd (see [3], eq. (30.4.1)).\n%\n% [P, LAM] = PSWF(N, C) also returns the eigenvalue(s).\n%\n% Examples:\n% f = pswf(2,pi); f(0.3)\n% plot(pswf(0:2:6, 100))\n%\n% [1] H. Xiao, V. Rokhlin and N. Yarvin, Prolate spheroidal wavefunctions,\n% quadrature and interpolation, Inverse Problems, 17 (2001), 805-838.\n%\n% [2] https://reference.wolfram.com/language/ref/SpheroidalPS.html\n% \n% [3] https://dlmf.nist.gov/30.4\n%\n% See also PSWFPTS, LEGPOLY.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Developer note: The approach is to compute the (approximate) normalised\n% Legendre coefficients of the PSWFs by solving an eigenvalue problem [1].\n% The Legendre coefficients are then converted to Chebyshev via LEG2CHEB,\n% and a Chebfun constructed.\n%\n% There is functionality for scaling the domain, but this is currently\n% undocumented, since we are not sure at present whether this choice\n% is the right one.\n%\n% Copyright 2020 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Defaults:\nif ( nargin < 3 )\n dom = [-1 1];\n output_type = 'chebfun';\nend\nif ( nargin == 3 )\n if ( isnumeric(dom) ) \n output_type = 'chebfun';\n else\n output_type = dom;\n dom = [-1 1];\n end\nend\n\n% Parse inputs:\nassert( nargin >= 2, 'PSWF requires at least two input arguments.')\nassert( all(round(N)==N) && all(N>=0) && isvector(N), ...\n 'Input N must be vector of non-negative integers.');\nassert( (numel(c)==1) && (c>0) , ...\n 'Input C must be a positive scalar.');\nassert( numel(dom)==2 && all(isfinite(dom)) , ...\n 'Domain must be a finite two-vector.');\n\n% Set discretisation size. Heuristic estimates for initialisation.\nM = max(ceil([2*sqrt(c)*N, 2*c, 20]));\n\n% Increase discretisation size until the trailing Legendre coefficients are\n% sufficiently small:\nishappy = 0;\ntol = eps;\ncount = 0;\n\nwhile ( ~ishappy )\n\n % Construct the matrix (see Xiao et al):\n j = (0:M).';\n Asub = c^2*j.*(j-1)./((2*j-1).*sqrt((2*j-3).*(2*j+1)));\n Adia = j.*(j+1) + c^2*(2*j.*(j+1)-1)./((2*j+3).*(2*j-1));\n Asup = c^2*(j+2).*(j+1)./((2*j+3).*sqrt((2*j+5).*(2*j+1)));\n A = diag(Asub(3:end), -2) + diag(Adia, 0) + diag(Asup(1:end-2), 2);\n \n % Split in to even and odd parts for efficiency/accuracy. \n Ae = A(1:2:end,1:2:end);\n Ao = A(2:2:end,2:2:end);\n \n % Compute (sorted) eigenvectors:\n [Ve, De] = eig(Ae);\n [lame, idx] = sort(diag(De), 'ascend');\n Ve = Ve(:,idx);\n [Vo, Do] = eig(Ao);\n [lamo, idx] = sort(diag(Do), 'ascend');\n Vo = Vo(:,idx);\n \n % Reassemble full V and eigenvalues:\n V = zeros(M+1,M+1);\n V(1:2:end,1:2:end) = Ve;\n V(2:2:end,2:2:end) = Vo;\n lam = zeros(M+1,1);\n lam(1:2:end) = lame;\n lam(2:2:end) = lamo;\n \n % Check discretisation size was large enough;\n ishappy = sum(abs(V(end-3:end,N+1)))/(2*length(N)) < tol;\n if ( ~ishappy )\n M = 2*M;\n end\n \n % Failsafe:\n count = count + 1;\n if ( count > 10 )\n break\n end\n \nend\n\n% Extract required columns and unnormalise the Legendre coeffients:\nV = bsxfun(@times, V(:,N+1), sqrt((0:M)'+1/2) );\nlam = lam(N+1);\n\n% Trim trailing coefficients that are below machine precision:\nM = max(abs(V), [], 2);\nidx = find(M > eps, 1, 'last');\nV = V(1:idx,:);\n\n% Scale as per Wolfram Alpha definition [1]:\nV = (1./sqrt(N+0.5)).*V;\n\n%%\n\n% Enforce P_N(0) > 0 for N even and P'_N(0) > 0 for N odd.\nm = 0:(idx-1)/2; idx = ~mod(N,2);\nif ( any(idx) )\n L0 = (-1).^m./(beta(m,.5).*m); L0(1) = 1;\n V0 = L0*V(1:2:end,idx);\n currentSign = sign(V0);\n desiredSign = 1 - mod(N(idx),4);\n scl = currentSign.*desiredSign;\n V(:,idx) = scl.*V(:,idx);\nend\nif ( ~all(idx) )\n Lp0 = 2*(-1).^m./beta(m+1,.5); Lp0 = Lp0(1:length(V(2:2:end,1)));\n Vp0 = Lp0*V(2:2:end,~idx);\n currentSign = sign(Vp0);\n desiredSign = 1 - mod(N(~idx)-1,4);\n scl = currentSign.*desiredSign;\n V(:,~idx) = scl.*V(:,~idx);\nend\n\n% Quit now if only coefficients are required:\nif ( strcmpi(output_type, 'coeffs') )\n P = V;\n return\nend\n\n% Convert Legendre coeffs to Chebyshev coeffs:\nW = leg2cheb(V);\n\n% Enforce even/oddness (which is lost in leg2cheb):\nidx = logical(mod(N,2));\nW(1:2:end,idx) = 0;\nW(2:2:end,~idx) = 0;\n\n% Create a Chebfun from the Chebyshev coefficients:\nP = chebfun(W, dom, 'coeffs');\n\n% The coefficients are trimmed in V, so simplifying should not be necessary.\n% P = simplify(P); \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/pswf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7701615633370513}} {"text": "function [x, y, z] = torus (a, n, r, kpi)\n% TORUS Generate a torus.\n% torus (r, n, a, kpi) generates a plot of a\n% torus with central radius a and\n% lateral radius r.\n% n controls the number of facets\n% on the surface.\n% kpi makes it possible to draw a whole torus,\n% or e.g. half of it.\n%\n% This script is a modification of a \n% program from:\n\n% MATLAB Primer, 6th Edition\n% Kermit Sigmon and Timothy A. Davis\n% Section 11.5, page 65.\n\ntheta = -pi * (0:2:kpi*n)/n ;\nphi = 2*pi* (0:2:n)'/n ;\nx = (a + r*cos(phi)) * cos(theta) ;\ny = (a + r*cos(phi)) * sin(theta) ;\nz = r * sin(phi) * ones(size(theta)) ;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28309-animated-spinning-top-with-cardan-mounting/torus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7700950930455417}} {"text": "function corr_coef = RegreesionLIVE(objectiveValues,mos)\n%this script is used to calculate the pearson linear correlation\n%coefficient and root mean sqaured error after regression\n\n%get the objective scores computed by the IQA metric and the subjective\n%scores provided by the dataset\n% matData = load('VSIOnLIVE.mat');\n% VSIOnLIVE = matData.VSIOnLIVE;\n% objectiveValues = VSIOnLIVE(:,1);\n% mos = VSIOnLIVE(:,2);\n\n%plot objective-subjective score pairs\n% p = plot(objectiveValues,mos,'+');\n% set(p,'Color','blue','LineWidth',1);\n\n%initialize the parameters used by the nonlinear fitting function\nbeta(1) = max(mos);\nbeta(2) = min(mos);\nbeta(3) = mean(objectiveValues);\nbeta(4) = 0.1;\nbeta(5) = 40;\n\n%fitting a curve using the data\n[bayta ehat,J] = nlinfit(objectiveValues,mos,@logistic,beta);\n%given a ssim value, predict the correspoing mos (ypre) using the fitted curve\n[ypre junk] = nlpredci(@logistic,objectiveValues,bayta,ehat,J);\n\nRMSE = sqrt(sum((ypre - mos).^2) / length(mos));%root meas squared error\ncorr_coef = corr(mos, ypre, 'type','Pearson'); %pearson linear coefficient\n\n%draw the fitted curve\n% t = min(objectiveValues):0.01:max(objectiveValues);\n% [ypre junk] = nlpredci(@logistic,t,bayta,ehat,J);\n% hold on;\n% p = plot(t,ypre);\n% set(p,'Color','black','LineWidth',2);\n% legend('Images in LIVE','Curve fitted with logistic function', 'Location','NorthEast');\n% xlabel('Objective score by VSI');\n% ylabel('MOS');\n", "meta": {"author": "HuiZeng", "repo": "BIQA_Toolbox", "sha": "39d606574f0cbfde82ecbc3c208b353d9fa9a450", "save_path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox", "path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox/BIQA_Toolbox-39d606574f0cbfde82ecbc3c208b353d9fa9a450/tools/NonlinearFitting/RegressionLIVE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7700950898266572}} {"text": "function [ result, seed ] = sphere01_quad_mc ( f, h, seed, n )\n\n%*****************************************************************************80\n%\n%% SPHERE01_QUAD_MC uses the Monte Carlo rule for sphere quadrature.\n%\n% Discussion:\n%\n% A number of points N are chosen at random on the sphere, with N\n% being determined so that, if the points were laid out on a regular\n% grid, the average spacing would be no more than H.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, function v = F ( n, x ), evaluates the integrand.\n%\n% Input, real H, the maximum length of a side of the spherical\n% quadrilaterals.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Input, integer N, the number of points to use.\n%\n% Output, real RESULT, the approximate integral.\n%\n sphere_area = 4.0 * pi;\n\n [ x, seed ] = sphere01_sample_3d ( n, seed );\n\n v = f ( n, x )\n\n result = sphere_area * sum ( v(1:n) ) / n;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_quad/sphere01_quad_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7700652362082185}} {"text": "function [ T, W ] = rd_lin_spline ( w0, t_array, n, c_array )\n\n%*****************************************************************************80\n%\n%% RD_LIN_SPLINE discretizes and solves a 1D reaction diffusion problem.\n%\n% Discussion:\n%\n% The problem includes homogeneous Neumann boundary conditions at both ends.\n%\n% The dynamics are given by the following reaction/diffusion equation\n% for the function W(T,X):\n%\n% W_t = W_xx + NL(W,c),\n%\n% where NL(W,c) is a polynomial in W:\n%\n% NL(W,c) = c(1) + c(2) * W + c(3) * W^2 + c(4) * W^3\n%\n% with Neumann boundary conditions at X = 0.0 and X = 1.0:\n%\n% W_x(T,0.0) = 0.0\n% W_x(T,1.0) = 0.0\n%\n% and initial condition at T = 0.0:\n%\n% W(0,X) = sin ( pi * X ).\n%\n% The problem is to be solved for 0.0 <= T <= 4.0, 0.0 <= X <= 1.0.\n%\n% We use a finite element approximation with piecewise linear \"hat\" \n% functions. The resulting ODE model is:\n%\n% M * w-dot(t) = - K * w(t) + NL(w, c)\n%\n% where M is the mass matrix, K the stiffness matrix, and NL the nonlinear\n% term.\n%\n% NL(w, c_array)=c_array(1)+ c_array(2)*w + c_array(3)*w^2 + c_array(4)*w^3\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 April 2011\n%\n% Author:\n%\n% Eugene Cliff\n%\n% Reference:\n%\n% Jeffrey Borggaard, John Burkardt, John Burns, Eugene Cliff,\n% Working Notes on a Reaction Diffusion Model: a Finite Element Formulation.\n%\n% Parameters:\n%\n% w0 - handle to initial function (on [0, 1])\n%\n% t_array- array of times for output\n%\n% n - grid parameter ( > 2)\n%\n% c_array- coefficients in nonlinear term\n%\n\n%\n% Assemble the mass matrix.\n%\n M = spdiags([ones(n+1,1) [2;4*ones(n-1,1);2] ones(n+1,1)], ...\n [-1 0 1], n+1, n+1)/(6*n);\n%\n% Assemble the stiff matrix.\n%\n K = n*spdiags([-ones(n+1,1) [1;2*ones(n-1,1);1] -ones(n+1,1)], ...\n [-1 0 1], n+1, n+1);\n%\n% Set the initial condition.\n%\n wr = zeros(n+1,1);\n h_wr = @(x) w0(x).*basic_hat(n*x );\n wr(1) = quad(h_wr, 0, 1/n); % < w_0, \\phi_1 >\n h_wr = @(x) w0(x).*basic_hat(n*x - n);\n wr(n+1) = quad(h_wr, (n-1)/n, 1); % < w_0, \\phi_n+1 >\n for jj=2:n\n h_wr = @(x) w0(x).*basic_hat(n*x + 1 - jj);\n wr(jj) = quad(h_wr, (jj-2)/n, jj/n); % < w_0, \\phi_i >\n end\n \n w_0 = M \\ wr;\n \n ODE_opt = odeset('Mass', M); % constant mass matrix\n h_rhs = @(t, w) -K*w + NL(w, c_array, n, M); % handle for rhs function\n \n [T, W] = ode15s(h_rhs, t_array, w_0, ODE_opt);% invoke ODE solver\n\n return\nend\nfunction val = NL (w, c, n, M )\n\n%*****************************************************************************80\n%\n%% NL evaluates the nonlinear term in the reaction-diffusion equation.\n%\n val = (c(1)/n)* [1; 2*ones(n-1,1); 1] ... % constant\n + c(2) * M * w ... % linear\n + c(3) * Nq(w, n) ... % quadratic\n + c(4) * Nc(w, n) ; % cubic\n\n return\nend\nfunction val = Nq(w, n)\n\n%*****************************************************************************80\n%\n%% NQ evaluates a quadratic nonlinear finite element function.\n%\n w2 = w(:).^2; wx = (w(1:end-1,1)+ w(2:end,1)).^2;\n \n val = [2*w2(1)+wx(1); wx(1:end-1)+4*w2(2:end-1)+wx(2:end) ; ...\n wx(end)+2*w2(end)]/(12*n);\n\n return\nend \nfunction val = Nc(w, n) \n\n%*****************************************************************************80\n%\n%% NC evaluates a cubiic nonlinear finite element function.\n%\n w2 = w(:).*w(:); w3 = w(:).*w2(:); wx = (w(1:end-1,1)+w(2:end,1)).^3;\n \n val = [3*w3(1)+wx(1)-w(1)*w(2)^2; \n wx(1:end-1)+6*w3(2:end-1)+wx(2:end)-w(2:end-1).*(w2(1:end-2)+w2(3:end)); \n wx(end)+3*w3(end)-w(end)*w(end-1)^2]/(20*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/fem_neumann/rd_lin_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7700510342798234}} {"text": "function trans = createTranslation(varargin)\n%CREATETRANSLATION Create the 3*3 matrix of a translation.\n%\n% TRANS = createTranslation(DX, DY);\n% Returns the translation corresponding to DX and DY.\n% The returned matrix has the form :\n% [1 0 TX]\n% [0 1 TY]\n% [0 0 1]\n%\n% TRANS = createTranslation(VECTOR);\n% Returns the matrix corresponding to a translation by the vector [x y].\n%\n%\n% See also \n% transforms2d, transformPoint, createRotation, createScaling\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2004-04-06\n% Copyright 2004-2022 INRA - TPV URPOI - BIA IMASTE\n\n% process input arguments\nif isempty(varargin)\n tx = 0;\n ty = 0;\nelseif length(varargin)==1\n var = varargin{1};\n tx = var(1);\n ty = var(2);\nelse\n tx = varargin{1};\n ty = varargin{2};\nend\n\n% create the matrix representing the translation\ntrans = [1 0 tx ; 0 1 ty ; 0 0 1];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/createTranslation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7700143897699876}} {"text": "function [] = draw_crystal_lattice\n% File: draw_crystal_lattice.m\n% Author: Ioannis Filippidis, jfilippidis@gmail.com\n% Date: 2011.01.30 - \n% Language: MATLAB R2012a\n% Purpose: draw crystal lattices\n% Copyright: Ioannis Filippidis, 2011-\n\nselection = 'diamond'; % 'diamond', 'copper'\n\na = 1;\nc = a /4;\n\nr_diamond_cubic = c *[0, 0, 0;\n 2, 0, 0;\n 0, 2, 0;\n 2, 2, 0;\n 1, 1, 0; %\n 1, 0, 1;\n 0, 1, 1;\n 1, 2, 1;\n 2, 1, 1; %\n 0, 0, 2;\n 2, 0, 2;\n 0, 2, 2;\n 2, 2, 2;\n 1, 1, 2; %\n 0.5, 0.5, 0.5;\n 1.5, 1.5, 0.5;\n 0.5, 1.5, 1.5;\n 1.5, 0.5, 1.5]';\n\nr_fcc = c *[0, 0, 0;\n 2, 0, 0;\n 0, 2, 0;\n 2, 2, 0;\n 1, 1, 0; %\n 1, 0, 1;\n 0, 1, 1;\n 1, 2, 1;\n 2, 1, 1; %\n 0, 0, 2;\n 2, 0, 2;\n 0, 2, 2;\n 2, 2, 2;\n 1, 1, 2]'; %\n\ni_diamond_cubic =[15, 1;\n 15, 5;\n 15, 6;\n 15, 7; %\n 16, 5;\n 16, 4;\n 16, 8;\n 16, 9; %\n 17, 7;\n 17, 12;\n 17, 14;\n 17, 8; %\n 18, 6;\n 18, 9;\n 18, 14;\n 18, 11];\n%\n\ni_fcc = [1, 2;\n 2, 4;\n 2, 3;\n 1, 3;\n 1, 4;\n 3, 4; %\n 1, 10;\n 2, 10;\n 2, 11;\n 1, 11;\n 10, 11; %\n 3, 12;\n 4, 13;\n 12, 13;\n 4, 12;\n 3, 13; %\n 10, 12;\n 10, 13;\n 13, 11;\n 12, 11;\n 1, 12;\n 3, 10; %\n 2, 13;\n 4, 11];\n\nswitch selection\n case 'diamond'\n r = r_diamond_cubic;\n i1 = i_diamond_cubic;\n case 'copper'\n r = r_fcc;\n i1 = i_fcc;\n otherwise\n disp('Unknown material selection.')\nend\n\nax = newax;\nhold(ax, 'on')\nfor i=1:size(r, 2)\n h = drawSphere(r(:, i), 0.05);\n set(h, 'FaceColor', 'r')\nend\ngrid(ax, 'on')\nbox(ax, 'on')\naxis(ax, 'equal')\naxis(ax, 'tight')\nview(ax, 3)\n%maximize(get(ax, 'Parent') )\n\nfor i=1:size(i1, 1)\n a = i1(i, 1);\n b = i1(i, 2);\n drawCylinder([r(:, a)', r(:, b)', 0.01] )\nend\n\nfname = selection;\nfig2u3d(gca, fname, '-pdf');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37640-export-figure-to-3d-interactive-pdf/fig2u3d/examples/draw_crystal_lattice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7700003920180429}} {"text": "function a_cum = r8vec_cum0 ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_CUM0 computes the cumulutive sums of an R8VEC.\n%\n% Example:\n%\n% Input:\n%\n% A = (/ 1.0, 2.0, 3.0, 4.0 /)\n%\n% Output:\n%\n% A_CUM = (/ 0.0, 1.0, 3.0, 6.0, 10.0 /)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A(N), the vector to be summed.\n%\n% Output, real A_CUM(1:N+1), the cumulative sums.\n%\n a_cum(1) = 0.0;\n\n for i = 1 : n\n a_cum(i+1) = a_cum(i) + a(i);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_cum0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7699821671282329}} {"text": "function Y=tensor2Mat(X,param2,C)\n%%TENSOR2MAT Unfold a (real or complex) tensor into a matrix. This can\n% either be done as an n-way matricization using a standard\n% ordering of the modes, or one can explicitly specify the\n% ordering of the modes. The tensor is just a hypermatrix. The\n% unfolding produces a 2D matrix as the output. The\n% transformation of tensors into matrices plays a role in\n% numerous multilinear algorithms, such as the multilinear\n% singular value decomposition.\n%\n%INPUTS: X The hypermatrix (tensor) that is to be unfolded. This should\n% have 2 or more modes. For example, a 4-mode hyper matrix would\n% be addressable as X(i1,i2,i3,i4). The matrix can be real or\n% complex.\n% param2, C If the algorithm is called with only two parameters, then\n% param2=n is the number n of the mode of the unfolding and an\n% n-mode matricization is performed. The mode number ranges\n% from 1 through N --the number of modes of the matrix X (the\n% number of indices needed to address an element in X). The\n% permutation of the modes to the columns is as in [1], which is\n% [1:1:(n-1),(n+1):1:N] and the number of rows of the matrix Y\n% returned is equal to the number of elements in the nth way. On\n% the other hand, some authors, such as in [2], use a different\n% permutation. In such an instance, the explicit ordering can be\n% specified using param2=R and also providing C as in [3]. R\n% contains the indices of the modes that are to be mapped to rows\n% and C contains the indices of modes that are to be mapped to\n% columns. For example, for a 4-mode matrix one might use R=[2;3],\n% C=[4;1], which makes the dimensionality of the rows of the\n% output equal to the sum of the dimensionalities of\n% modes 2 and 3. \n% \n%OUTPUT: Y A 2D matrix containing the elements of the hypermatrix X\n% arranged according to the inputs.\n%\n%The algorithm can be called as\n%Y=tensor2Mat(X,n);\n%for a standard n-mode matricization or as\n%Y=tensor2Mat(X,R,C);\n%for general ordering to be used. The standard n-mode matricization is\n%consistent with the orderings used in the nModeProd function.\n%\n%As an example, consider the 3X2X3 hypermatrix\n% A=zeros(3,2,3);\n% A(1,1,1)=1;\n% A(1,1,2)=1;\n% A(2,1,1)=1;\n% A(2,1,2)=-1;\n% A(2,1,3)=2;\n% A(3,1,1)=2;\n% A(3,1,3)=2;\n% A(1,2,1)=2;\n% A(1,2,2)=2;\n% A(2,2,1)=2;\n% A(2,2,2)=-2;\n% A(2,2,3)=4;\n% A(3,2,1)=4;\n% A(3,2,3)=4;\n% %A standard 1-mode matrix unfolding is \n% Y=tensor2Mat(A,1)\n%Providing the result\n% Y=[1 2 1 2 0 0;\n% 1 2 -1 -2 2 4;\n% 2 4 0 0 2 4];\n%On the other hand, the example in [2] gives a different answer, because\n%they use a different ordering. That is, they rearrange, the columns in the\n%unfolding differently. Here, one can get the same answer using\n% Y=tensor2Mat(A,1,[3,2])\n%which returns\n% Y=[1 1 0 2 2 0;\n% 1 -1 2 2 -2 4;\n% 2 0 2 4 0 4];\n%\n%Introductions to tensor operations are in [3] and [4].\n%\n%REFERENCES:\n%[1] J. Salmi, A. Richter, and V. Koivunen, \"Sequential unfolding SVD for\n% tensors with applications in array signal processing,\" IEEE\n% Transactions on Signal Processing, vol. 57, no. 12, pp. 4719-4733,\n% Dec. 2009.\n%[2] L. de Lathauwer, B. de Moore, and J. Vandewalle, \"A multilinear\n% singular value decomposition,\" SIAM Journal on Matrix Analysis and\n% Applications, vol. 21, no. 4, pp. 1253-1278, 2000.\n%[3] T. G. Kolda, \"Multilinear operators for higher-order decompositions,\"\n% Sandia National Laboratories, Tech. Rep. SAND2006-2081, Apr. 2006.\n% [Online]. Available: http://www.sandia.gov/~tgkolda/pubs/pubfiles/SAND2006-2081.pdf\n%[4] R. G. Kolda and B. W. Bader, \"Tensor decompositions and applications,\"\n% SIAM Review, vol. 51, no. 3, pp. 455-500, 2009.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nI=size(X);%The dimensionality of each way of X.\n\n%If a standard n-mode matricization is being performed\nif(nargin<3)\n d=length(I);\n C=[1:1:(param2-1),(param2+1):1:d];\nend\n\nR=param2;\nJ=prod(I(R));\nK=prod(I(C));\nY=reshape(permute(X,[R(:);C(:)]),J,K);%Convert X to the matrix Y.\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/Tensors/tensor2Mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.7699453153288564}} {"text": "function ypp = fppcube ( x )\n\n%*****************************************************************************80\n%\n%% FPPCUBE sets the value of the second derivative of the cubic function.\n%\n% Discussion:\n%\n% Y(X) = ( ( X + 2 ) * X + 3 ) * X + 4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real YPP, the value of the second derivative of the cubic function.\n%\n ypp = 6.0E+00 * x + 4.0E+00;\n\n return\nend\n", "meta": {"author": "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/fppcube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8791467690927439, "lm_q1q2_score": 0.7699453098211687}} {"text": "function [PBarUVals,dPBarUValsdTheta,d2PBarUValsdTheta2]=NALegendreCosRat(theta,M,scalFactor)\n%NALEGENDRECOSRAT Evaluate \\bar{P}_{nm}(cos(theta))/u^m for all n from\n% 0 to M and for each n for all m from 0 to n, where\n% u=abs(sin(theta)). \\bar{P}_{nm}(x) is the fully\n% normalized associated Legendre function of x of degree n\n% and order m. Also evaluate\n% D{\\bar{P}_{nm}(cos(theta))}/u^m and\n% D2{\\bar{P}_{nm}(cos(theta))}/u^m where D{} is the first\n% derivative operator with respect to theta and D2{} is the\n% second derivative operator with respect to theta. All of\n% the values can be scaled by a factor of scalFac, if\n% desired, to help prevent overflows with high degrees and\n% orders.\n%\n%INPUTS: theta An angle in radians.\n% maxDeg The maximum degree and order of the output. This must be\n% >=0.\n% scalFactor A scale factor to help prevent overflow of the results. In\n% [1], discussed below, a value of 10^(-280) is used.\n%\n%OUTPUTS: PBarUVals An instance of the CountingClusterSet class such that\n% PBarUVals(n+1,m+1)=scalFac*\\bar{P}_{nm}(cos(theta))/u^m.\n% dPBarUValsdTheta An instance of the CountingClusterSet class such that\n% dPBarUValsdTheta(n+1,m+1)=scalFac*D{\\bar{P}_{nm}(cos(theta))}/u^m\n% d2PBarUValsdTheta2 An instance of the CountingClusterSet class such that\n% d2PBarUValsdTheta2(n+1,m+1)=scalFac*D2{\\bar{P}_{nm}(cos(theta))}/u^m\n%\n%The modified forward row (MFR) algorithm of [1] is used to compute\n%PBarUVals and dPBarUValsdTheta. For d2PBarUValsdTheta2, the algorithm of\n%[2] is used. However, the paper contains a typo. The first term of the\n%first unnumbered equation should be multiplied by an additional (1/u).\n%This function uses the correct formulation, which is also described in\n%Appendix F of [3].\n%\n%With the notation P^m_n(x) for an associated Legendre function of degree n\n%and order m evaluated at the point x, one generally means \n%P^m_n(x)=(-1)^m*(1-x^)^(m/2)*D_m{P_n(x)}\n%where P_n(x) is a Legendre polynomial of degree n evaluated at x and\n%D_m{P_n(x)} is the mth derivative of the polynomial. These associated\n%Legendre functions are the same as those used in the International\n%Geomagnetic Reference Field. On the other hand, with the notation\n%P_{nm}(x), one generally means (-1)^mP^m_n(x). This notation is also\n%called an associated Legendre function. Matlab's built-in function\n%legendre(n,x) returns all P^m_n(x) for m=0 to m=n. On the other hand, the\n%notation \\bar{P}_{nm}(x), refers to a fully normalized associated Legendre\n%function. Multiple definitions of what is normalized exist. In this\n%function, the normalization is such that\n%\\bar{P}_{nm}(x)=P_{nm}(x)*sqrt(k*(2*n+1)*factorial(n-m)/factorial(n+m))\n%where k=1 if m=0 and k=2 otherwise. This differs from the normalization\n%constant that Matlab uses in the normalized version of its built-in\n%associated Legendre function. It is the same as the normalization \n%constant the NGA uses in its coefficients for the EGM96 and the\n%EGM2008 gravitation models.\n%\n%The fully normalized associated Legendre function ratios that this\n%function computes can be used in the synthesis of spherical harmonic\n%coefficients.\n%\n%REFERENCES:\n%[1] S. A. Holmes and W. E. Featherstone, \"A unified approach to the\n% Clenshaw summation and the recursive computation of very high degree\n% and order normalised associated Legendre functions,\" Journal of\n% Geodesy, vol. 76, no. 5, pp. 279-299, May 2002.\n%[2] S. A. Holmes and W. E. Featherstone, \"Short note: Extending simplified\n% high-degree synthesis methods to second latitude derivatives of\n% geopotential,\" Journal of Geodesy, vol. 76, no. 8, pp. 447-450, Nov.\n% 2002.\n%[3] D. F. Crouse, \"An overview of major terrestrial, celestial, and\n% temporal coordinate systems for target tracking,\" Naval Research\n% Laboratory, Washington, DC, Tech. Rep. NRL/FR/5344-16-10,279, 10 Aug.\n% 2016.\n%\n%December 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(M<0)\n error('M must be >=0.') \n end\n\n u=sin(theta);\n t=cos(theta);\n\n %Allocate space for the return variables. n ranges from 0 to M and m\n %ranges from 0 to n. Thus, the number of elements for each n ranges\n %from 1 to M+1. This means that a total of\n %(M+1)*(M+2)/2 elements are necessary.\n numPBarU=(M+1)*(M+2)/2;\n totalP=zeros(numPBarU,1);\n PBarUVals=CountingClusterSet(totalP);\n \n %The value of PBar_{0,0}(cos(theta)) is independent of theta and is\n %one. \n PBarUVals(0+1,0+1)=1*scalFactor;\n\n if(M>0)\n %Set the seed value for PBar_{1,1}(cos(theta))/u from which the\n %other values will be computed.\n PBarUVals(1+1,1+1)=sqrt(3)*scalFactor;\n \n jTerm=1/sqrt(2);\n %First, deal with the case where n=1, m=0;\n n=1;\n m=0;\n %g is given in Equation 18 of the first Holmes and Featherstone paper.\n g=2*(m+1)/sqrt((n-m)*(n+m+1));\n PBarUVals(n+1,m+1)=jTerm*g*t*PBarUVals(n+1,m+1+1);\n\n %Compute the values along the main diagonal, where m=n\n %starting from m=n=2. This implements equation 28 in the first\n %Holmes and Featherstone paper for the normalized associated\n %Legendre function ratio.\n for m=2:M\n PBarUVals(m+1,m+1)=sqrt((2*m+1)/(2*m))*PBarUVals(m-1+1,m-1+1);\n end\n\n %Recursively compute the values using Equation 27 from the\n %first Holmes and Featherstone paper, taking into account the\n %fact that the first element of the recursion only has one term.\n\n %Next, evaluate the values for all other valid n and m.\n for n=2:M\n %Deal with the first element of the recursion,which is\n %where m=n-1.\n m=n-1;\n g=2*(m+1)/sqrt((n-m)*(n+m+1));\n PBarUVals(n+1,m+1)=g*t*PBarUVals(n+1,m+1+1);\n\n %Recursively compute the values of the rest of the m terms.\n for m=(n-2):-1:1\n g=2*(m+1)/sqrt((n-m)*(n+m+1));\n %h is given in Equation 19 of the first Holmes and\n %Featherstone paper.\n h=sqrt((n+m+2)*(n-m-1)/((n-m)*(n+m+1)));\n PBarUVals(n+1,m+1)=g*t*PBarUVals(n+1,m+1+1)-h*u^2*PBarUVals(n+1,m+2+1);\n end\n\n %Deal with the special m=0 case.\n m=0;\n g=2*(m+1)/sqrt((n-m)*(n+m+1));\n h=sqrt((n+m+2)*(n-m-1)/((n-m)*(n+m+1)));\n PBarUVals(n+1,m+1)=jTerm*(g*t*PBarUVals(n+1,m+1+1)-h*u^2*PBarUVals(n+1,m+2+1));\n end\n end\n \n %If the first derivative is desired.\n if(nargout>1)\n %Allocate space.\n dPBarUValsdTheta=CountingClusterSet(totalP);\n %The first derivative of PBar_{0,0}(cos(theta)) is just zero.\n dPBarUValsdTheta(1,1)=0;\n \n if(M>0)\n m=1;\n n=1;\n %From Equation 30 in the first Holmes and Featherstone paper. This\n %is the seed value from which other values will be computed.\n dPBarUValsdTheta(1+1,1+1)=m*(t/u)*PBarUVals(1+1,1+1);\n\n n=1;\n m=0;\n %e is given in Equation 22 of the first Holmes and Featherstone\n %paper.\n e=sqrt((n+m+1)*(n-m)/2);\n %This is Equation 30 of the first Holmes and Featherstone paper for\n %m=0.\n dPBarUValsdTheta(n+1,m+1)=-e*u*PBarUVals(n+1,m+1+1);\n\n %Compute the values along the main diagonal, where m=n starting \n %from m=n=2. This implements Equation 30 in the frist Holmes and\n %Featherstone paper for the ratio of the first derivative. \n for m=2:M\n dPBarUValsdTheta(m+1,m+1)=m*(t/u)*PBarUVals(m+1,m+1);\n end\n\n %Next, evaluate the values for all other valid n and m.\n for n=2:M\n %Recursively compute the values of the m terms for m>0.\n for m=(n-1):-1:1\n e=sqrt((n+m+1)*(n-m));\n dPBarUValsdTheta(n+1,m+1)=m*(t/u)*PBarUVals(n+1,m+1)-e*u*PBarUVals(n+1,m+1+1);\n end\n %Deal with the special m=0 case.\n m=0;\n e=sqrt((n+m+1)*(n-m)/2);\n dPBarUValsdTheta(n+1,m+1)=-e*u*PBarUVals(n+1,m+1+1);\n end\n end\n end\n \n %If the second derivative is desired\n if(nargout>2)\n %Allocate space\n d2PBarUValsdTheta2=CountingClusterSet(totalP);\n \n for n=0:M\n for m=0:n\n %From the first (un-numbered) equation in the second Holmes\n %and Featherstone paper AFTER correction.\n d2PBarUValsdTheta2(n+1,m+1)=(m^2/u^2-n*(n+1))*PBarUVals(n+1,m+1)-(t/u)*dPBarUValsdTheta(n+1,m+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/Mathematical_Functions/Polynomials/NALegendreCosRat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7699001852027793}} {"text": "function q = ik (K)\n% Anthropomorphic arm with 3 DOF\n% It calculates the Inverse Kinematic of an Anthropomorphic arm with 3 DOF.\n% 'q' is the solutions in radiant and K is the direct Kinematic matrix.\n% \n% K = [ n s a p;\n% 0 0 0 1]\n% where n, s, a are three vectors fo 3 elements that represents the\n% end-effector's orientation, and p is the desired end-effector position.\n\n% Denavit-Hartenberg's Parameters\na1=0; % [m]\na2=0.2; % [m]\na3=0.2; % [m]\nalfa1=pi/2; % [rad]\nalfa2=0; % [rad]\nalfa3=0; % [rad]\n\ndk=K; % Direct kinematics matrix\n\n% Inverse Kinematic\npw_x=dk(1,4); % Vector's components that representes the end-effector position\npw_y=dk(2,4);\npw_z=dk(3,4);\n\nc3=(pw_x^2+pw_y^2+pw_z^2-a2^2-a3^2)/(2*a2*a3); % cos(teta3)\ns3=-sqrt(1-c3^2); % sin(teta3)\nteta3=atan2(s3,c3);\n\nc2=(sqrt(pw_x^2+pw_y^2)*(a2+a3*c3)+pw_z*a3*s3)/(a2^2+a3^2+2*a2*a3*c3); % cos(teta2)\ns2=(pw_z*(a2+a3*c3)-sqrt(pw_x^2+pw_y^2)*a3*s3)/(a2^2+a3^2+2*a2*a3*c3); % sin(teta2)\nteta2=atan2((a2+a3*c3)*pw_z-a3*s3*sqrt(pw_x^2+pw_y^2),(a2+a3*c3)*sqrt(pw_x^2+pw_y^2)+a3*s3*pw_z);\n\nteta1=atan2(pw_y,pw_x);\n\nq=[teta1 teta2 teta3]'; % Solutions in radiant", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30078-inverse-kinematic-algorithm/ik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7698924247014179}} {"text": "%FITELLIPSE Fits an ellipse around a set of 2D points\n%\n% rct = cv.fitEllipse(points)\n% rct = cv.fitEllipse(points, 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __points__ Input 2D point set, stored in numeric array\n% (Nx2/Nx1x2/1xNx2) or cell array of 2-element vectors (`{[x,y], ...}`).\n% There should be at least 5 points to fit the ellipse.\n%\n% ## Output\n% * __rct__ Output rotated rectangle struct with the following fields:\n% * __center__ The rectangle mass center `[x,y]`.\n% * __size__ Width and height of the rectangle `[w,h]`.\n% * __angle__ The rotation angle in a clockwise direction. When the angle is\n% 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.\n%\n% ## Options\n% * __Method__ One of:\n% * __Linear__ Linear (LIN) conic fitting method. This is the default.\n% * __Direct__ Direct least square (DLS) method.\n% * __AMS__ Approximate mean square (AMS) method.\n%\n% ### Method = Linear\n%\n% The function calculates the ellipse that fits (in a least-squares sense) a\n% set of 2D points best of all. It returns the rotated rectangle in which the\n% ellipse is inscribed. The first algorithm described by [Fitzgibbon95] is\n% used. Developer should keep in mind that it is possible that the returned\n% ellipse/rotatedRect data contains negative indices, due to the data points\n% being close to the border of the containing Mat element.\n%\n% ### Method = Direct\n%\n% The function calculates the ellipse that fits a set of 2D points.\n% It returns the rotated rectangle in which the ellipse is inscribed.\n% The Direct least square (Direct) method by [Fitzgibbon1999] is used.\n%\n% For an ellipse, this basis set is `chi = (x^2, x*y, y^2, x, y, 1)`, which is\n% a set of six free coefficients `A^T = {A_xx, A_xy, A_yy, A_x, A_y, A_0}`.\n% However, to specify an ellipse, all that is needed is five numbers; the\n% major and minor axes lengths `(a,b)`, the position `(x_0,y_0)`, and the\n% orientation `theta`. This is because the basis set includes lines,\n% quadratics, parabolic and hyperbolic functions as well as elliptical\n% functions as possible fits.\n%\n% The Direct method confines the fit to ellipses by ensuring that\n% `4*A_xx*A_yy - A_xy^2 > 0`. The condition imposed is that\n% `4*A_xx*A_yy - A_xy^2 = 1` which satisfies the inequality and as the\n% coefficients can be arbitrarily scaled is not overly restrictive.\n%\n% epsilon^2 = A^T * D^T * D * A\n% with A^T * C * A = 1\n% and C = [0 0 2 0 0 0; 0 -1 0 0 0 0; 2 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0]\n%\n% The minimum cost is found by solving the generalized eigenvalue problem.\n%\n% D^T * D * A = lambda * (C) * A\n%\n% The system produces only one positive eigenvalue `lambda` which is chosen as\n% the solution with its eigenvector `u`. These are used to find the\n% coefficients:\n%\n% A = sqrt(1 / (u^T * C * u)) * u\n%\n% The scaling factor guarantees that `A^T * C * A = 1`.\n%\n% Note: If the determinant of `A` is too small, the method fallsback to\n% 'Linear'.\n%\n% ### Method = AMS\n%\n% The function calculates the ellipse that fits a set of 2D points.\n% It returns the rotated rectangle in which the ellipse is inscribed.\n% The Approximate Mean Square (AMS) proposed by [Taubin1991] is used.\n%\n% For an ellipse, this basis set is `chi = (x^2, x*y, y^2, x, y, 1)`, which is\n% a set of six free coefficients `A^T = {A_xx, A_xy, A_yy, A_x, A_y, A_0}`.\n% However, to specify an ellipse, all that is needed is five numbers; the\n% major and minor axes lengths `(a,b)`, the position `(x_0,y_0)`, and the\n% orientation `theta`. This is because the basis set includes lines,\n% quadratics, parabolic and hyperbolic functions as well as elliptical\n% functions as possible fits.\n%\n% If the fit is found to be a parabolic or hyperbolic function then the\n% 'Direct' method is used. The AMS method restricts the fit to parabolic,\n% hyperbolic and elliptical curves by imposing the condition that\n% `A^T * (D_x^T * D_x + D_y^T * D_y) * A = 1` where the matrices `Dx` and `Dy`\n% are the partial derivatives of the design matrix `D` with respect to x and y.\n% The matrices are formed row by row applying the following to each of the\n% points in the set:\n%\n% D(i,:) = {x_i^2, x_i y_i, y_i^2, x_i, y_i, 1}\n% D_x(i,:) = {2*x_i, y_i, 0, 1, 0, 0}\n% D_y(i,:) = {0, x_i, 2*y_i, 0, 1, 0}\n%\n% The AMS method minimizes the cost function\n%\n% epsilon^2 = (A^T * D^T * D * A) / (A^T * (D_x^T * D_x + D_y^T * D_y) * A^T)\n%\n% The minimum cost is found by solving the generalized eigenvalue problem.\n%\n% D^T * D * A = lambda * (D_x^T * D_x + D_y^T * D_y) * A\n%\n% Note: If the determinant of `A` is too small, the method fallsback to\n% 'Linear'.\n%\n% ## References\n% [Fitzgibbon95]:\n% > Andrew W Fitzgibbon and Robert B Fisher.\n% > \"A buyer's guide to conic fitting\". In Proceedings of the 6th British\n% > conference on Machine vision (Vol. 2), pages 513-522. BMVA Press, 1995.\n% > [PDF](http://www.bmva.org/bmvc/1995/bmvc-95-050.pdf)\n%\n% [Fitzgibbon1999]:\n% > Andrew Fitzgibbon, Maurizio Pilu, and Robert B. Fisher.\n% > \"Direct least square fitting of ellipses\". IEEE Transactions on Pattern\n% > Analysis and Machine Intelligence, 21(5):476-480, 1999.\n% > [PDF](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/ellipse-pami.pdf)\n%\n% [Taubin1991]:\n% > Gabriel Taubin. \"Estimation of planar curves, surfaces, and nonplanar\n% > space curves defined by implicit equations with applications to edge and\n% > range image segmentation\". IEEE Transactions on Pattern Analysis and\n% > Machine Intelligence, 13(11):1115-1138, 1991.\n%\n% See also: cv.minAreaRect\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/fitEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7698909041943618}} {"text": "function lagrange_nd_test09 ( )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_ND_TEST09 tests LAGRANGE_PARTIAL in 3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_ND_TEST09\\n' );\n fprintf ( 1, ' LAGRANGE_PARTIAL determines\\n' );\n fprintf ( 1, ' the Lagrange interpolating polynomials L(x)\\n' );\n fprintf ( 1, ' for ND points in D dimensions, assuming that\\n' );\n fprintf ( 1, ' the number of points is less than or equal to\\n' );\n fprintf ( 1, ' R = Pi(D,N), the number of monomials of degree N or less\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the data points are the same as those\\n' );\n fprintf ( 1, ' used by the level 2 Clenshaw Curtis sparse grid in 3D.\\n' );\n\n sq2h = sqrt ( 2.0 ) / 2.0;\n\n d = 3;\n n = 4;\n r = mono_upto_enum ( d, n );\n nd = 25;\n xd = [ ...\n 0.0, 0.0, 0.0; ...\n -1.0, 0.0, 0.0; ...\n 1.0, 0.0, 0.0; ...\n 0.0, -1.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, -1.0; ...\n 0.0, 0.0, 1.0; ...\n -sq2h, 0.0, 0.0; ...\n sq2h, 0.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 1.0, 1.0, 0.0; ...\n 0.0, -sq2h, 0.0; ...\n 0.0, sq2h, 0.0; ...\n -1.0, 0.0, -1.0; ...\n 1.0, 0.0, -1.0; ...\n -1.0, 0.0, 1.0; ...\n 1.0, 0.0, 1.0; ...\n 0.0, -1.0, -1.0; ...\n 0.0, 1.0, -1.0; ...\n 0.0, -1.0, 1.0; ...\n 0.0, 1.0, 1.0; ...\n 0.0, 0.0, -sq2h; ...\n 0.0, 0.0, sq2h ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension D = %d\\n', d );\n fprintf ( 1, ' Maximum degree N = %d\\n', n );\n fprintf ( 1, ' Number of monomials R = %d\\n', r );\n fprintf ( 1, ' Number of data points ND = %d\\n', nd );\n\n r8mat_transpose_print ( d, nd, xd, ' Data points XD:' );\n\n [ po, pc, pe ] = lagrange_partial ( d, n, r, nd, xd );\n%\n% Print the polynomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Lagrange polynomials for XD data points:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : nd\n o = po(i);\n label = sprintf ( ' P(%d)(x) =', i );\n polynomial_print ( d, o, pc(i,1:o), pe(i,1:o), label );\n end\n%\n% Evaluate the polynomials at XD.\n%\n value = zeros ( nd, nd );\n\n for j = 1 : nd\n o = po(j);\n label = sprintf ( ' P(%d)(x) =', j );\n value(1:nd,j) = polynomial_value ( d, o, pc(j,1:o), pe(j,1:o), nd, xd ); \n end\n\n err = r8mat_is_identity ( nd, value );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of Lagrange matrix error = %g\\n', err );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/lagrange_nd/lagrange_nd_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7698846929775589}} {"text": "function value = p02_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P02_F evaluates the integrand for problem 02.\n%\n% Dimension:\n%\n% DIM_NUM arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integrand:\n%\n% ( sum ( 2 * x(1:dim_num) - 1 ) )**4\n%\n% Exact Integral:\n%\n% DIM_NUM * (5*DIM_NUM-2) / 15\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n value(point) = ( sum ( 2.0 * x(1:dim_num,point) - 1.0 ) )^4;\n end\n\n p02_i4 ( 'I', '#', point_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p02_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.7698846688817693}} {"text": "function [rx,sx,tx,ry,sy,ty,rz,sz,tz,J] = GeometricFactors3D(x,y,z,Dr,Ds,Dt)\n\n% function [rx,sx,tx,ry,sy,ty,rz,sz,tz,J] = GeometricFactors3D(x,y,z,Dr,Ds,Dt)\n% Purpose : Compute the metric elements for the local mappings of the elements\n\n% calculate geometric factors\nxr = Dr*x; xs = Ds*x; xt = Dt*x;\nyr = Dr*y; ys = Ds*y; yt = Dt*y;\nzr = Dr*z; zs = Ds*z; zt = Dt*z;\n\nJ = xr.*(ys.*zt-zs.*yt) - yr.*(xs.*zt-zs.*xt) + zr.*(xs.*yt-ys.*xt);\nrx = (ys.*zt - zs.*yt)./J; ry = -(xs.*zt - zs.*xt)./J; rz = (xs.*yt - ys.*xt)./J;\nsx = -(yr.*zt - zr.*yt)./J; sy = (xr.*zt - zr.*xt)./J; sz = -(xr.*yt - yr.*xt)./J;\ntx = (yr.*zs - zr.*ys)./J; ty = -(xr.*zs - zr.*xs)./J; tz = (xr.*ys - yr.*xs)./J;\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/GeometricFactors3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7698724025164898}} {"text": "function plane = medianPlane(p1, p2)\n%MEDIANPLANE Create a plane in the middle of 2 points\n%\n% PLANE = medianPlane(P1, P2)\n% Creates a plane in the middle of 2 points.\n% PLANE is perpendicular to line (P1 P2) and contains the midpoint of P1\n% and P2.\n% The direction of the normal of PLANE is the same as the vector from P1\n% to P2.\n%\n% See also:\n% planes3d, createPlane\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 18/02/2005.\n%\n\n% HISTORY\n% 28/06/2007: add doc, and manage multiple inputs\n\n% unify data dimension\nif size(p1, 1)==1\n p1 = repmat(p1, [size(p2, 1) 1]);\nelseif size(p2, 1)==1\n p2 = repmat(p2, [size(p1, 1) 1]);\nelseif size(p1, 1)~=size(p2, 1) \n error('data should have same length, or one data should have length 1');\nend\n\n% middle point\np0 = (p1 + p2)/2;\n\n% normal to plane\nn = p2-p1;\n\n% create plane from point and normal\nplane = createPlane(p0, 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/medianPlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7697289574799914}} {"text": "function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)\n%GRADIENTDESCENT Performs gradient descent to learn theta\n% theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by \n% taking num_iters gradient steps with learning rate alpha\n\n% Initialize some useful values\nm = length(y); % number of training examples\nJ_history = zeros(num_iters, 1);\n\nfor iter = 1:num_iters\n theta1=theta(1,1)-alpha/m*sum(X*theta-y);\n theta2=theta(2,1)-alpha/m*sum((X*theta-y) .* X(:,2));\n theta(1,1)=theta1;\n theta(2,1)=theta2;\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Perform a single gradient step on the parameter vector\n % theta. \n %\n % Hint: While debugging, it can be useful to print out the values\n % of the cost function (computeCost) and gradient here.\n %\n\n\n\n\n\n\n\n % ============================================================\n\n % Save the cost J in every iteration \n J_history(iter) = computeCost(X, y, theta);\n\nend\n\nend\n", "meta": {"author": "loserChen", "repo": "Coursera-MachineLearning", "sha": "ce2360516c36805e8bd4fb3c796d7820f320cc78", "save_path": "github-repos/MATLAB/loserChen-Coursera-MachineLearning", "path": "github-repos/MATLAB/loserChen-Coursera-MachineLearning/Coursera-MachineLearning-ce2360516c36805e8bd4fb3c796d7820f320cc78/machine-learning-ex1/ex1/gradientDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7697289563123519}} {"text": "function drawArcEllipse(x,y,a,b,theta0,theta1,color)\n%(x,y):= coordinates of the center\n% r: = radius of the circle\nangle = theta0+0.01:0.01:theta1;\nxp = x+ a*cos(angle);\nyp = y+ b*sin(angle);\nplot(xp,yp,color);\n\n% plot the symetric arc\nangle = theta0+pi+0.01:0.01:theta1+pi;\nxp = x+ a*cos(angle);\nyp = y+ b*sin(angle);\nplot(xp,yp,color);", "meta": {"author": "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/drawArcEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7696869926253858}} {"text": "function Pvalue=myfisher23(x)\n%P=MYFISHER23(X)- Fisher's Exact Probability Test on 2x3 matrix.\n%Fisher's exact test of 2x3 contingency tables permits calculation of\n%precise probabilities in situation where, as a consequence of small cell\n%frequencies, the much more rapid normal approximation and chi-square\n%calculations are liable to be inaccurate. The Fisher's exact test involves\n%the computations of several factorials to obtain the probability of the\n%observed and each of the more extreme tables. Factorials growth quickly,\n%so it's necessary use logarithms of factorials. This computations is very\n%easy in Matlab because x!=gamma(x+1) and log(x!)=gammaln(x+1). This\n%function is now fully vectorized to speed up the computation.\n%\n% Syntax: \tmyfisher23(x)\n% \n% Inputs:\n% X - 2x3 data matrix \n% Outputs:\n% - Three p-values\n%\n% Example:\n%\n% A B C\n% -------------------\n% X 0 3 2\n% ------------------- \n% Y 6 5 1\n% -------------------\n% \n%\n% x=[0 3 2; 6 5 1];\n%\n% Calling on Matlab the function: \n% myfisher23(x)\n%\n% Answer is:\n%\n% 2x3 matrix Fisher's exact test: 18 tables were evaluated\n% -----------------------------------------------------------------\n% \t\t p-value (2-tails): 0.0882352941\n% -----------------------------------------------------------------\n%\n% Created by Giuseppe Cardillo\n% giuseppe.cardillo-edta@poste.it\n%\n% To cite this file, this would be an appropriate format:\n% Cardillo G. (2007) MyFisher23: a very compact routine for Fisher's exact\n% test on 2x3 matrix\n% http://www.mathworks.com/matlabcentral/fileexchange/15399\n\n%Input Error handling\nif ~isequal(size(x),[2 3])\n if isequal(size(x),[3 2])\n x=x';\n else\n error('Input matrix must be a 2x3 matrix')\n end\nend\nif ~all(isfinite(x(:))) || ~all(isnumeric(x(:)))\n error('Warning: all X values must be numeric and finite')\nend\nif ~isequal(x(:),round(x(:)))\n error('Warning: X data matrix values must be whole numbers')\nend\n\nRs=sum(x,2); %rows sum\nCs=sum(x); %columns sum\nN=sum(Rs); %Total observations\n\n%If necessed, rearrange matrix\nif ~issorted(Cs)\n [Cs,ind]=sort(Cs);\n x=x(:,ind);\n clear ind\nend\nif ~issorted(Rs)\n [Rs,ind]=sort(Rs);\n x=x(ind,:);\n clear ind\nend\n\n%recall that Fisher's P=[Prod(Rs!)*Prod(Cs!)]/[N!*prod(X(i,j)!)]\n%Log(A*B)=Log(A)+Log(B) and Log(A/B)=Log(A)-Log(B)\n%Costruct all possible tables\n%A 2x3 matrix has 2 degrees of freedom...\nA=0:1:min(Rs(1),Cs(1)); %all possible values of X(1,1)\nB=min(Cs(2),Rs(1)-A); %max value of X(1,2) given X(1,1)\net=sum(B+ones(size(B))); %tables to evaluate\nTables=zeros(et,6); %Matrix preallocation\n%compute the index\nstop=cumsum(B+1);\nstart=[1 stop(1:end-1)+1];\n%In the first round of the for cycle, Column 1 assignment should be skipped\n%because it is already zero. So, modify the cycle...\nTables(start(1):stop(1),2)=0:1:B(1); %Put in the Column2 all the possible values of X(1,2) given X(1,1)\nfor I=2:length(A)\n Tables(start(I):stop(I),1)=A(I); %replicate the A(I) value for B(I)+1 times\n %Put in the Column2 all the possible values of X(1,2) given X(1,1)\n Tables(start(I):stop(I),2)=0:1:B(I); \nend\nclear A B start stop\n%The degrees of freedom are finished, so complete the table...\n%...Put all the possible values of X(1,3) given X(1,1) and X(1,2)\nTables(:,3)=Rs(1)-sum(Tables(:,1:2),2);\n%Complete the second row given the first row\nTables(:,4:6)=repmat(Cs,et,1)-Tables(:,1:3);\n\n%Compute log(x!) using the gammaln function\nzf=gammaln(Tables+1); %compute log(x!)\nK=sum(gammaln([Rs' Cs]+1))-gammaln(N+1); %The costant factor K=log(prod(Rs!)*prod(Cs!)/N!)\nnp=exp(K-sum(zf,2)); %compute the p-value of each possible matrix\n[tf,obt]=ismember(x(1,:),Tables(:,1:3),'rows'); %Find the observed table\nclear zf K tf\n%Finally compute the probability for 2-tailed test\nP=sum(np(np<=np(obt)));\n\n%display results\ntr=repmat('-',1,65); %Set up the divisor\ndisp(' ')\nfprintf('2x3 matrix Fisher''s exact test: %0.0f tables were evaluated\\n',et)\ndisp(tr)\nfprintf('\\t\\t p-value (2-tails): %0.10f\\n',P); \ndisp(tr)\nfprintf('Mid-p correction: %0.10f\\n',0.5*np(obt)+sum(np(np 0 & Y > 0,\n% REL_ENTR(X,Y) = { 0 if X == 0 & Y >= 0,\n% { +Inf otherwise.\n% X and Y must either be the same size, or one must be a scalar. If X and\n% Y are vectors, then SUM(REL_ENTR(X,Y)) returns their relative entropy.\n% If they are PDFs (that is, if X>=0, Y>=0, SUM(X)==1, SUM(Y)==1) then\n% this is equal to their Kullback-Liebler divergence SUM(KL_DIV(X,Y)).\n% -SUM(REL_ENTR(X,1)) returns the entropy of X.\n%\n% Disciplined convex programming information:\n% REL_ENTR(X,Y) is convex in both X and Y, nonmonotonic in X, and\n% nonincreasing in Y. Thus when used in CVX expressions, X must be\n% real and affine and Y must be concave. The use of REL_ENTR(X,Y) in\n% an objective or constraint will effectively constrain both X and Y \n% to be nonnegative, hence there is no need to add additional\n% constraints X >= 0 or Y >= 0 to enforce this.\n\nerror(nargchk(2,2,nargin));\nif ~isreal( x ) || ~isreal( y ),\n error( 'Arguments must be real.' );\nend\nt1 = x < 0 | y <= 0;\nt2 = x == 0 & y >= 0;\nx = max( x, realmin );\ny = max( y, realmin );\nz = x .* log( x ./ y );\nz( t1 ) = +Inf;\nz( t2 ) = 0;\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/rel_entr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7693715207399252}} {"text": "function [ n_data, n, c ] = moebius_values ( n_data )\n\n%*****************************************************************************80\n%\n%% MOEBIUS_VALUES returns some values of the Moebius function.\n%\n% Discussion:\n%\n% MU(N) is defined as follows:\n%\n% MU(N) = 1 if N = 1;\n% 0 if N is divisible by the square of a prime;\n% (-1)^K, if N is the product of K distinct primes.\n%\n% In Mathematica, the function can be evaluated by:\n%\n% MoebiusMu[n]\n%\n% First values:\n%\n% N MU(N)\n%\n% 1 1\n% 2 -1\n% 3 -1\n% 4 0\n% 5 -1\n% 6 1\n% 7 -1\n% 8 0\n% 9 0\n% 10 1\n% 11 -1\n% 12 0\n% 13 -1\n% 14 1\n% 15 1\n% 16 0\n% 17 -1\n% 18 0\n% 19 -1\n% 20 0\n%\n% As special cases, MU(N) is -1 if N is a prime, and MU(N) is 0\n% if N is a square, cube, etc.\n%\n% Formula:\n%\n% The Moebius function is related to Euler's totient function:\n%\n% PHI(N) = Sum ( D divides N ) MU(D) * ( N / D ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the argument of the Moebius function.\n%\n% Output, integer C, the value of the Moebius function.\n%\n n_max = 20;\n\n c_vec = [ ...\n 1, -1, -1, 0, -1, 1, -1, 0, 0, 1, ...\n -1, 0, -1, 1, 1, 0, -1, 0, -1, 0 ];\n\n n_vec = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data);\n c = c_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/moebius_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8479677641409289, "lm_q1q2_score": 0.7693715114744208}} {"text": "function value = r8_choose ( n, k )\n\n%*****************************************************************************80\n%\n%% R8_CHOOSE computes the combinatorial coefficient C(N,K).\n%\n% Discussion:\n%\n% Real arithmetic is used, and C(N,K) is computed directly, via\n% Gamma functions, rather than recursively.\n%\n% C(N,K) is the number of distinct combinations of K objects\n% chosen from a set of N distinct objects. A combination is\n% like a set, in that order does not matter.\n%\n% Example:\n%\n% The number of combinations of 2 things chosen from 5 is 10.\n%\n% C(5,2) = ( 5 * 4 * 3 * 2 * 1 ) / ( ( 3 * 2 * 1 ) * ( 2 * 1 ) ) = 10.\n%\n% The actual combinations may be represented as:\n%\n% (1,2), (1,3), (1,4), (1,5), (2,3),\n% (2,4), (2,5), (3,4), (3,5), (4,5).\n%\n% Formula:\n%\n% C(N,K) = N! / ( (N-K)! * K! )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 23 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the value of N.\n%\n% Input, integer K, the value of K.\n%\n% Output, real VALUE, the value of C(N,K)\n%\n n = floor ( n );\n k = floor ( k );\n\n if ( n < 0 )\n\n value = 0.0;\n\n elseif ( k == 0 )\n\n value = 1.0;\n\n elseif ( k == 1 )\n\n value = n;\n\n elseif ( 1 < k && k < n-1 )\n\n facn = gammaln ( n + 1 );\n fack = gammaln ( k + 1 );\n facnmk = gammaln ( n - k + 1 );\n\n value = round ( exp ( facn - fack - facnmk ) );\n\n elseif ( k == n-1 )\n\n value = n;\n\n elseif ( k == n )\n\n value = 1.0;\n\n else\n\n value = 0.0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/r8_choose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417881, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7693715076061995}} {"text": "function [coeffs,termMat]=polyFitMultiDim(varVals,funVals,degree)\n%%POLYFITMULTIDIM Obtain a least-squares multivariate polynomial fit of a\n% specified order to a given set of data.\n%\n%INPUTS: varVals This is a numDimXnumPoints set oif dtapoints where the\n% function was evaluated.\n% funVals This is a numPointsX1 or 1XnumPoints vector of the values\n% of the functions at the specified data points.\n% degree The degree of the desired interpolating polynomial. The\n% degree must be less than the total number of monomial\n% terms, which is\n% (1+degree)*binomial(degree+numDim,numDim-1)/numDim.\n%\n%OUTPUTS: coeffs A hypermatrix of the coefficients for the multivariate\n% polynomial that can be used in the polyValMultiDim\n% function. These are arranged such that\n% coeffs(a1,a2,a3...an) corresponds to the coefficient of an\n% x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1) term. Thus, the\n% number of indices coeffs takes is equal to the\n% dimensionality of x (not counting singleton dimensions at\n% the end of coeffs). Note that this ordering is the reverse\n% that used in the 1D polyval function that is built into\n% Matlab. The number of elements for each index in coeffs is\n% the maximum order of that dimension +1.\n% termMat An (n+1)XnumTerms matrix such that\n% termMat(:,i)=[c,a1,a2,...,an] is a monomial term where c is\n% the value of of the monomial coefficient and the monomial\n% is x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1).\n%\n%Multivariate polynomials consist of a sum of monomial terms of the form\n%c*x1^(a1)*x2^(a2)*x3^(a3)...xn^(an)\n%Here, the variables x are known as are the values z of the polynomial\n%evaluated at those points. Thus, the unknowns are the c terms, the\n%coefficients of the monomials. This function evaluates the monomial terms\n%and build a matrix with all of the monomial term values for all of the\n%equations. The solution to the coefficient values is thus the solution to\n%a linear system of equations. The \n%\n%EXAMPLE:\n%Here, we have a two-dimensional function evaluated at a number of random\n%points and we want to fit a polynomial to it. In this problem, we do not\n%add noise to the function.\n% points=linspace(-1,1,10);\n% [x,y]=meshgrid(points,points);\n% z=2*x.^3+2*x.*y-3*y.^3+4*x.^2.*y-5*y.^2.*x.^3;\n% varVals=[x(:)';y(:)'];\n% funVals=z(:);\n% degree=5;\n% [~,termMat]=polyFitMultiDim(varVals,funVals,degree);\n% %One will get coefficients that are almost exact. Given that we know that\n% %the coefficients are integers, we can eliminate all small coefficients by\n% %rounding.\n% termMat=round(termMat);\n% %Get rid of terms that are numerically zero.\n% sel=termMat(1,:)~=0;\n% termMat=termMat(:,sel);\n% terms2String(termMat,{'x','y'})\n%\n%November 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(varVals,1);\nnumEq=size(varVals,2);\n\n%The total number of monomial terms for the multivariate polynomial. This\n%is the sum of binomial(degCur+numDim-1,numDim-1) from degCur=0 to degree,\n%which is the number of compositions of the degree degCur into n parts.\ntotalNumMonomials=(1+degree)*binomial(degree+numDim,numDim-1)/numDim;\n\nif(totalNumMonomials>numEq)\n error('The total number of monomial coefficients to find is greater than the number of data points provided.') \nend\n\ntermMat=zeros(numDim+1,totalNumMonomials);\n\nV=zeros(numEq,totalNumMonomials);\n\n%x^0,y^0, etc. value.\nV(:,1)=1;\ncurTerm=2;\nfor curDegree=1:degree\n numMonomials=binomial(curDegree+numDim-1,numDim-1);\n \n for j=0:(numMonomials-1)\n curMonomial=unrankTComposition(j,numDim,curDegree+numDim,true)-1;\n termMat(2:end,curTerm)=curMonomial;\n for curEq=1:numEq\n V(curEq,curTerm)=prod(varVals(:,curEq).^curMonomial);\n end\n curTerm=curTerm+1;\n end\nend\n\ntermMat(1,:)=V\\funVals(:);\n%Get rid of terms that are numerically zero.\nsel=termMat(1,:)~=0;\ntermMat=termMat(:,sel);\ncoeffs=terms2MultiDimPolyMat(termMat);\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/Interpolation/polyFitMultiDim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7693715023772655}} {"text": "%%%%%%%VERSION 3\n%%ANOTHER DESCRIBTION OF GABOR FILTER\n\n%The Gabor filter is basically a Gaussian (with variances sx and sy along x and y-axes respectively)\n%modulated by a complex sinusoid (with centre frequencies U and V along x and y-axes respectively) \n%described by the following equation\n%%\n% 1 -1 x ^ y ^\n%%% Gi(x,y) = ---------- * exp ([----{(----) 2+(----) 2}])*Mi(x,y,f); \n% 2*pi*sx*sy 2 sx sy\n%%% i =1,2\n%%% M1(x,y,f) = cos[2*pi*f*sqrt(x^2+y^2)];\n%%% M2(x,y,f) = cos[2*pi*f*(x*cos(theta) + y*sin(theta)];\n\n%% Describtion :\n\n%% I : Input image\n%% Sx & Sy : Variances along x and y-axes respectively\n%% f : The frequency of the sinusoidal function\n%% theta : The orientation of Gabor filter\n\n%% G1 & G2 : The output filters as described above\n%% gabout1 & gabout2 : The output filtered images\n\n%% Author : Ahmad poursaberi e-mail : a.poursaberi@ece.ut.ac.ir\n%% Faulty of Engineering, Electrical&Computer Department,Tehran\n%% University,Iran,June 2004\n\nfunction [G1,G2,gabout1,gabout2] = gaborfilter(I,Sx,Sy,f,theta);\n\nif isa(I,'double')~=1 \n I = double(I);\nend\n\nfor x = -fix(Sx):fix(Sx)\n for y = -fix(Sy):fix(Sy)\n M1 = cos(2*pi*f*sqrt(x^2+y^2));\n M2 = cos(2*pi*f*(x*cos(theta)+y*sin(theta)));\n G1(fix(Sx)+x+1,fix(Sy)+y+1) = (1/(2*pi*Sx*Sy)) * exp(-.5*((x/Sx)^2+(y/Sy)^2))*M1;\n G2(fix(Sx)+x+1,fix(Sy)+y+1) = (1/(2*pi*Sx*Sy)) * exp(-.5*((x/Sx)^2+(y/Sy)^2))*M2;\n end\nend\n\nImgabout1 = conv2(I,double(imag(G1)),'same');\nRegabout1 = conv2(I,double(real(G1)),'same');\n\nImgabout2 = conv2(I,double(imag(G2)),'same');\nRegabout2 = conv2(I,double(real(G2)),'same');\n\ngabout1 = sqrt(Imgabout1.*Imgabout1 + Regabout1.*Regabout1);\ngabout2 = sqrt(Imgabout2.*Imgabout2 + Regabout2.*Regabout2);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/5237-2d-gabor-filterver123/gaborfilter2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828601, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7693700442079087}} {"text": "function [K, sK, n1] = dexpKernCompute(kern, x1, x2)\n\n% DEXPKERNCOMPUTE Compute the double exponential kernel,\n%\n% k(x_i, x_j) = 0.5 * sigma2 * theta * exp(-theta*abs(x_i - x_j)),\n%\n% given the parameters (theta and sigma), and t.\n%\n% FORMAT\n% DESC computes the kernel parameters for the double exponential kernel\n% given the input matrices associated with rows and columns.\n% ARG kern : the kernel structure for which the kernel matrix is computed.\n% ARG x1 : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN K : the kernel matrix computed at the given points.\n% RETURN sK: normalised kernel matrix (i.e. variance set to 1).\n% RETURN n1: L1 distance between each row of x1 and x2.\n%\n% FORMAT\n% DESC computes the kernel matrix for the double exponential kernel\n% given a matrix of inputs.\n% ARG kern : the kernel structure for which the kernel matrix is computed.\n% ARG x1 : the input matrix associated with the rows and the columns.\n% RETURN K : the kernel matrix computed at the given points.\n% RETURN sK: normalised kernel matrix (i.e. no multiplication by the decay\n% or variance of the exponential).\n% RETURN n1: L1 distance between each row of x1 and x2.\n%\n% SEEALSO : ouKernParamInit, kernCompute, kernCreate, ouKernDiagCompute,\n%\n% COPYRIGHT : David Luengo, 2009\n%\n% COPYRIGHT : Neil D. Lawrence, 2009\n\n% KERN\n\n\nif nargin < 3\n n1 = sqrt(dist2(x1, x1));\nelse\n n1 = sqrt(dist2(x1, x2));\nend\n\nsK = 0.5 * exp(-kern.decay * n1);\nK = sK * kern.decay * 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/dexpKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7693373883228064}} {"text": "function geometry_test039 ( )\n\n%*****************************************************************************80\n%\n%% TEST039 tests LINES_EXP_INT_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST039\\n' );\n fprintf ( 1, ' LINES_EXP_INT_2D finds intersections of\\n' );\n fprintf ( 1, ' two explicit lines in 2D.\\n' );\n fprintf ( 1, '\\n' );\n\n for itest = 1 : 3\n%\n% x + 2y - 4 = 0\n% x - y - 1 = 0\n%\n if ( itest == 1 )\n\n p1(1:2,1) = [ 0.0; 2.0 ];\n p2(1:2,1) = [ 4.0; 0.0 ];\n q1(1:2,1) = [ 0.0; -1.0 ];\n q2(1:2,1) = [ 1.0; 0.0 ];\n%\n% x + 2y - 4 = 0\n% 2x + 4y - 1 = 0\n%\n elseif ( itest == 2 )\n\n p1(1:2,1) = [ 0.00; 2.00 ];\n p2(1:2,1) = [ 4.00; 0.00 ];\n q1(1:2,1) = [ 0.00; 0.25 ];\n q2(1:2,1) = [ 0.50; 0.00 ];\n%\n% x + 2y - 4 = 0\n% -3x - 6y +12 = 0\n%\n elseif ( itest == 3 )\n\n p1(1:2,1) = [ 0.0; 2.0 ];\n p2(1:2,1) = [ 4.0; 0.0 ];\n q1(1:2,1) = [ 0.0; 2.0 ];\n q2(1:2,1) = [ 4.0; 0.0 ];\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' P1 %8f %8f\\n', p1(1:2,1) );\n fprintf ( 1, ' P2 %8f %8f\\n', p2(1:2,1) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Q1 %8f %8f\\n', q1(1:2,1) );\n fprintf ( 1, ' Q2 %8f %8f\\n', q2(1:2,1) );\n\n [ ival, p ] = lines_exp_int_2d ( p1, p2, q1, q2 );\n\n if ( ival == 1 )\n fprintf ( 1, ' Intersection at %8f %8f\\n', p(1:2,1) );\n elseif ( ival == 0 )\n fprintf ( 1, ' Lines are parallel, no intersection.\\n' );\n elseif ( ival == 2 )\n fprintf ( 1, ' Lines are coincident.\\n' );\n else\n fprintf ( 1, ' Unknown return value of IVAL = %d\\n', ival );\n end\n\n end\n\n return\nend\n", "meta": {"author": "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_test039.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7693046209995387}} {"text": "classdef GaussianMixtureD\n%%GAUSSIANMIXTURED Function to handle scalar or multivariate real Gaussian\n% mixture distributions.\n%Implemented methods are: mean, cov, PDF, PDFS, PDFI, rand, randS.\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \nmethods(Static)\nfunction meanVal=mean(w,mu)\n%%MEAN Obtain the mean of the Gaussiax mixture distribution.\n%\n%INPUTS: w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n%\n%OUTPUTS: meanVal The xDimX1 mean of the Gaussian mixture distribution.\n%\n%It is simple to show that the mean of the distribution is the weighted\n%sum of the means of the components.\n%\n%EXAMPLE:\n%In this example, \n% w=[0.4,0.6];\n% mu=[1,-0.5;\n% -1, 1];\n% Sigma=zeros(2,2,2);\n% Sigma(:,:,1)=[4/9, 14/45;\n% 14/45,4/9];\n% Sigma(:,:,2)=[4/9, 0;\n% 0, 4/9];\n% N=10000;\n% analyticMean=GaussianMixtureD.mean(w,mu);\n% sampMean=mean(GaussianMixtureD.rand(N,w,mu,Sigma),2);\n% RelErr=abs((sampMean-analyticMean)./analyticMean)\n%In this example, the relative error will typically be 3% or better.\n%Increasing the number of samples will typically decrease the relative\n%error, indicating that the analytic and sample means are converging.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\n meanVal=sum(bsxfun(@times,w(:).',mu),2);\nend\n\nfunction [covMat,meanVal]=cov(w,mu,Sigma)\n%%COV Obtain the covariance matrix of the Gaussian mixture distribution\n% (the variance if it is scalar).\n%\n%INPUTS: w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% Sigma The xDimXxDimXN set of covariance matrices of the\n% distribution components.\n%\n%OUTPUTS: covMat The xDimXxDim covariance matrix of the Gaussian\n% mixture.\n% meanVal The xDimX1 mean value of the distribution.\n%\n%The function calcMixtureMoments is called to find the covariance\n%matrix.\n%\n%EXAMPLE:\n% w=[0.4,0.6];\n% mu=[1,-0.5;\n% -1, 1];\n% Sigma=zeros(2,2,2);\n% Sigma(:,:,1)=[4/9, 14/45;\n% 14/45,4/9];\n% Sigma(:,:,2)=[4/9, 0;\n% 0, 4/9];\n% N=10000;\n% analyticCov=GaussianMixtureD.cov(w,mu,Sigma);\n% [~,sampleCov]=calcMixtureMoments(GaussianMixtureD.rand(N,w,mu,Sigma));\n% RelErr=abs((sampleCov-analyticCov)./analyticCov)\n%The relative error of each element will tend to be less than 1% and\n%will decrease as the number of samples increases\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\n [meanVal,covMat]=calcMixtureMoments(mu,w,Sigma);\nend\n\nfunction vals=PDF(z,w,mu,Sigma)\n%%PDF Evaluate the PDF of a scalar or multivariate Gaussian\n% distribution at specified points.\n%\n%INPUTS: z The xDimXnumPoints set of points at which the PDF should be\n% evaluated.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% Sigma The xDimXxDimXN set of covariance matrices of the\n% distribution components.\n%\n%OUTPUTS: vals The 1XN set of PDF values of the Gaussian mixture PDF\n% evaluated at the points in z.\n%\n%The PDF is the weighted sum of the PDFs of the individual components.\n%\n%EXAMPLE:\n%Here, we validate the PDF by generating random samples and comparing\n%the PDF plot with a histogram of the random samples.\n% w=[0.4,0.6];\n% mu=[1,-0.5];\n% sigma=zeros(1,1,2);\n% sigma(:,:,1)=4/9;\n% sigma(:,:,2)=5/9;\n% N=5000;\n% figure(1)\n% clf\n% histogram(GaussianMixtureD.randS(N,w,mu,sigma),'Normalization','pdf','BinLimits',[-3,3])\n% hold on\n% numPoints=1000;\n% x=linspace(-3,3,numPoints);\n% vals=GaussianMixtureD.PDF(x,w,mu,sigma.^2);\n% plot(x,vals,'linewidth',2)\n% axis([-3,3,0,0.45])\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n n=length(w);\n numMeas=size(z,2);\n\n vals=zeros(1,numMeas);\n for k=1:n\n vals=vals+w(k)*GaussianD.PDF(z,mu(:,k),Sigma(:,:,k));\n end\nend\n\nfunction vals=PDFS(z,w,mu,S)\n%%PDF Evaluate the PDF of a scalar or multivariate Gaussian\n% distribution at specified points given the weights, means and\n% lower-triangular covariance matrices of the individual\n% components.\n%\n%INPUTS: z The xDimXnumPoints set of points at which the PDF should be\n% evaluated.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% S The xDimXxDimXN set of lower-triangular square-root\n% covariance matrices of the distribution components.\n%\n%OUTPUTS: vals The 1XN set of PDF values of the Gaussian mixture PDF\n% evaluated at the points in z.\n%\n%The PDF is the weighted sum of the PDFs of the individual components.\n%\n%EXAMPLE:\n%Here, we validate the PDF by generating random samples and comparing\n%the PDF plot with a histogram of the random samples.\n% w=[0.4,0.6];\n% mu=[1,-0.5];\n% sigma=zeros(1,1,2);\n% sigma(:,:,1)=4/9;\n% sigma(:,:,2)=5/9;\n% N=5000;\n% figure(1)\n% clf\n% histogram(GaussianMixtureD.randS(N,w,mu,sigma),'Normalization','pdf','BinLimits',[-3,3])\n% hold on\n% numPoints=1000;\n% x=linspace(-3,3,numPoints);\n% vals=GaussianMixtureD.PDFS(x,w,mu,sigma);\n% plot(x,vals,'linewidth',2)\n% axis([-3,3,0,0.45])\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n n=length(w);\n numMeas=size(z,2);\n\n vals=zeros(1,numMeas);\n for k=1:n\n vals=vals+w(k)*GaussianD.PDFS(z,mu(:,k),S(:,:,k));\n end\nend\n\nfunction vals=PDFI(z,w,mu,SigmaInv,SigmaInvDet)\n%%PDFI Evaluate the PDF of a scalar or multivariate Gaussian\n% distribution at specified points given the weights, means and\n% the inverses of the covariance matrices of the individual\n% components.\n%\n%INPUTS: z The xDimXnumPoints set of points at which the PDF should be\n% evaluated.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% SigmaInv The xDimXxDimXN set of inverse of covariance matrices of the\n% distribution components.\n% SigmaInvDet Optionally, a length-N set of determinants of the matrices\n% in SigmaInv can be passed so as to speed up the computation. If\n% omitted or an empty matrix is passed, determinants will be taken\n% as needed.\n%\n%OUTPUTS: vals The 1XN set of PDF values of the Gaussian mixture PDF\n% evaluated at the points in z.\n%\n%The PDF is the weighted sum of the PDFs of the individual components.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n n=length(w);\n numMeas=size(z,2);\n\n vals=zeros(1,numMeas);\n if(nargin<5||isempty(SigmaInvDet))\n for k=1:n\n vals=vals+w(k)*GaussianD.PDFI(z,mu(:,k),SigmaInv(:,:,k));\n end\n else\n for k=1:n\n vals=vals+w(k)*GaussianD.PDFI(z,mu(:,k),SigmaInv(:,:,k),SigmaInvDet(k));\n end\n end\nend\n\nfunction vals=CDF(z,w,mu,varVals)\n%%CDF Evaluate the cumulative distribution function (CDF) of a scalar\n% Gaussian mixture at the specified points.\n%\n%INPUTS: z A matrix of the point(s) at which the CDF should be\n% evaluated.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The length N set of mean values of the distribution\n% components.\n% varVals The length-N set of variances of the distribution\n% components.\n%\n%OUTPUTS: val The scalar value(s) of the Gaussian mixture distribution\n% evaluated at the point(s) z.\n%\n%The CDF of the mixture is the weighted sum of the CDFs of the\n%individual Gaussian components.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\n n=length(w);\n\n vals=zeros(size(z));\n for k=1:n\n vals=vals+w(k)*GaussianD.CDF(z,mu(k),varVals(k));\n end\nend\n\nfunction vals=rand(N,w,mu,P)\n%%RAND Generate multivariate Gaussian mixture samples with given\n% weights, means and lower-triangular square root covariance\n% matrices.\n% \n%INPUTS: N The number of random variables to generate.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% P The xDimXxDimXN set of covariance matrices of the\n% distribution components. If all of them are the same, then a\n% single xDimXxDim matrix can be passed.\n%\n%OUTPUT: x An xDimXN matrix of random instances of the multivariate\n% Gaussian distribution.\n%\n%The distribution is sampled by sampling the empirical distribution of\n%weights, to determine which Gaussian component to sample, and then\n%sampling the chosen Gausian distribution. Lower-triangular square\n%roots of the componets must be found for sampling, so if these are\n%available, then the randS method will be faster.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %The number of components of the mixture.\n n=length(w);\n xDim=size(mu,1);\n\n if(size(P,3)==1)\n P=repmat(P,[1,1,n]); \n end\n \n vals=zeros(xDim,N);\n\n %Determine which components are to be sampled.\n idx=EmpiricalD.rand([N,1],1:n,w);\n\n %Sample the Gaussian components that were selected.\n S=zeros(xDim,xDim,n);\n componentUsed=false(n,1);\n for curSamp=1:N\n curComp=idx(curSamp);\n %Get the lower-triangular square roots only for the components\n %that are used.\n if(componentUsed(curComp)==false)\n S(:,:,curComp)=chol(P(:,:,curComp),'lower');\n componentUsed(curComp)=true;\n end\n\n vals(:,curSamp)=mu(:,curComp)+S(:,:,curComp)*randn(xDim,1);\n end\nend\n\nfunction vals=randS(N,w,mu,S)\n%%RANDS Generate multivariate Gaussian mixture samples with given\n% weights, means and lower-triangular square root covariance\n% matrices.\n%\n%INPUTS: N The number of random variables to generate.\n% w The 1XN or NX1 set of weights of the distribution components\n% such that all w>=0 and sum(w)=1.\n% mu The xDimXN set of mean values of the distribution\n% components.\n% S The xDimXxDimXN set of lower-triangular square-root\n% covariance matrices of the distribution components.\n%\n%OUTPUT: x An xDimXN matrix of random instances of the multivariate\n% Gaussian distribution.\n%\n%The distribution is sampled by sampling the empirical distribution of\n%weights, to determine which Gaussian component to sample, and then\n%sampling the chosen Gausian distribution.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %The number of components of the mixture.\n n=length(w);\n xDim=size(mu,1);\n\n if(size(S,3)==1)\n S=repmat(S,[1,1,n]); \n end\n \n vals=zeros(xDim,N);\n\n %Determine which components are to be sampled.\n idx=EmpiricalD.rand([N,1],1:n,w);\n\n %Sample the Gaussian components that were selected.\n for curSamp=1:N\n curComp=idx(curSamp);\n\n vals(:,curSamp)=mu(:,curComp)+S(:,:,curComp)*randn(xDim,1);\n end\nend\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/GaussianMixtureD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7693046134557797}} {"text": "function [minPoint,minValue,exitCode]=goldenSectionSearch(g,xSpan,XTol,maxIter)\n%%GOLDENSECTIONSEARCH Perform a golden section search to find the minimum\n% of a continuous, real, function that is unimodal in a\n% given interval. The golden section search linearly\n% decreases the search region. The algorithm is\n% considered more efficient than a ternary search.\n% Unlike Matlab's built-in fminbnd function, quadratic\n% interpolation is not used to try to speed up the\n% convergence rate.\n%\n%INPUTS: g The handle to a real function to minimize. The function takes a\n% scalar input and returns a real scalar output.\n% xSpan The 2X1 or 1X2 span of values in which the minimum is to be\n% found xSpan(1)gbBar)\n if(gbBar>=gAlphaBar)\n alpha=bBar;\n gAlpha=gbBar;\n \n b=alpha+tau*(alphaBar-alpha);\n gb=g(b);\n else\n alpha=b;\n gAlpha=gb;\n \n %Because of the use of the golden ratio for tau, only one\n %function evaluation is needed in this instance.\n b=bBar;\n gb=gbBar;\n end\n \n bBar=alphaBar-tau*(alphaBar-alpha);\n gbBar=g(bBar);\n else\n alpha=b;\n alphaBar=bBar;\n \n gAlpha=gb;\n gAlphaBar=gbBar;\n\n b=alpha+tau*(alphaBar-alpha);\n gb=g(b);\n bBar=alphaBar-tau*(alphaBar-alpha);\n gbBar=g(bBar);\n end\n \n %If the accuracy bound has been achieved. The second condition deals\n %with finite precision limitiations if XTol is very close to 0.\n if(abs(alphaBar-alpha)<=XTol||(alphaPrev==alpha&&alphaBarPrev==alphaBar))\n exitCode=0;\n break;\n end\nend\n\n%After the iterations, we have the function evaluated at alpha, b, bBar,\n%and alphaBar. We will just return the point/ value that is the smallest.\n\npoints=[alpha;b;bBar;alphaBar];\nvalues=[gAlpha;gb;gbBar;gAlphaBar];\n\n[values,idx]=sort(values,'ascend');\nminPoint=points(idx(1));\nminValue=values(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/Mathematical_Functions/Continuous_Optimization/goldenSectionSearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7692381187574998}} {"text": "function mb_bfgs\n\n% 2010 m.bangert@dkfz.de\n% fitting a gaussian distribution to data with a quasi newton method using\n% a bfgs or sr1 update for the hessian matrix\n%\n% example : mb_bfgs (function does not take any argument)\n\n% set options\nmode = 'BFGS'; % update rule for hessian: either 'SR1' or 'BFGS'\nvisLineSearch = 1;\nvisBool = 1;\n\nfprintf(['\\nFitting a gaussian distribution to data ...\\n' ...\n 'Using ' mode ' Hessian update\\n']);\n\n% sample data from a gaussian distribution\nrandn('seed',12345); % set the seed of the random number generator - if you do not want to do that comment...\nnumOfSamples = 250;\ndata(:,1) = linspace(-2,4,numOfSamples) + 6/numOfSamples*randn(1,numOfSamples);\ndata(:,2) = exp(-(linspace(-2,4,250)-1.5).^2) + .05*randn(1,250);\n\n% plot data\nif visBool\n close all\n figure\n hold on\n plot(data(:,1),data(:,2),'b+')\n xlabel('X')\n ylabel('Y')\n visHandle = [];\nend\n\n% specify input\nx = [1 1 1]'; % starting value for parameters\nH = eye(3); % initial hessian approximation\n \n% 1st calculation of objective function and gradient\nobjFunc = @(x) sum((x(3).*exp(-(data(:,1)-x(1)).^2./x(2))-data(:,2)).^2);\nobjFuncValue = objFunc(x);\noldObjFuncValue = objFuncValue + 1;\ndx = mb_numDiff(objFunc,x);\n\n% iterate\niter = 0;\nnumOfIter = 100;\nprec = 1e-5;\n\n% convergence if gradient smaller than prec, change in objective function\n% smaller than prec or maximum number of iteration reached...\nwhile iter < numOfIter && abs((oldObjFuncValue-objFuncValue)/objFuncValue)>prec && norm(dx)>prec\n \n % increment iteration counter\n iter = iter + 1;\n \n % remember odl objective function value\n oldObjFuncValue = objFuncValue;\n \n % implementation of BFGS according to\n % http://en.wikipedia.org/wiki/BFGS_method\n % numbers corresponds \n \n % 1 obtain search direction\n dir = -(H\\dx); % this is the efficient matlab notation for -inv(H)*dx\n \n % 2.1 linesearch to to find acceptable stepsize alpha\n %alpha = mb_backtrackingLineSearch(objFunc,objFuncValue,x,dx,dir);\n alpha = mb_nocLineSearch(objFunc,@(x) mb_numDiff(objFunc,x),x,dir,dir'*dx,objFuncValue);\n\n % 3\n p = alpha*dir;\n\n % visualize the line search (optional) used for debugging\n if visLineSearch\n figure\n hold on\n alphas = linspace(0,2*alpha,100);\n alphaVis = NaN*alphas;\n for i = 1:100\n alphaVis(i) = objFunc(x+alphas(i)*dir);\n end\n plot(alphas,alphaVis,'b') % function in direction of line search\n plot(alpha,objFunc(x+alpha*dir),'r.') % the steplength found\n plot(alphas,objFuncValue + 1e-1*alphas*(dir'*dx),'g') % constraint\n pause(.5)\n close\n end\n \n % 2.2 update x\n x = x + p;\n \n % update objective function (and remember old objective function to\n % check for convergence)\n objFuncValue = objFunc(x);\n \n % 4 calculate difference of gradients\n dx_old = dx;\n dx = mb_numDiff(objFunc,x);\n q = dx-dx_old;\n \n % update hessian\n if strcmp(mode,'BFGS')\n H = H + (q*q')/(q'*p) - ((H*p)*(H*p)')/(p'*H*p);\n elseif strcmp(mode,'SR1')\n H = H + ((q-H*p)*(q-H*p)')/((q-H*p)'*p);\n end\n \n % update function with new x and plot\n if visBool\n pause(0.5)\n fitFunc = @(t) x(3).*exp(-(t-x(1)).^2./x(2));\n delete(visHandle);\n visHandle = plot(data(:,1),fitFunc(data(:,1)),'r','LineWidth',4);\n drawnow;\n end\n \n fprintf(1,'Iteration %d: alpha_min=%f, OF=%f\\n',iter,alpha,objFuncValue);\n \nend\n\nfprintf(['\\n' num2str(iter) ' iteration(s) performed to converge\\n'])\n\nfprintf(1,'Final solution: x=(%f,%f,%f)\\n',x(1),x(2),x(3));\n\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34835-optimization-tutorial/mb_bfgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7691616233105271}} {"text": "% Minimize sidelobe level of an array with arbitrary 2-D geometry\n% \"Convex optimization examples\" lecture notes (EE364) by S. Boyd\n% \"Antenna array pattern synthesis via convex optimization\"\n% by H. Lebret and S. Boyd\n% (figures are generated)\n%\n% Designs an antenna array such that:\n% - it minimizes sidelobe level outside the beamwidth of the pattern\n% - it has a unit sensitivity at some target direction\n% - it has nulls (zero sensitivity) at specified direction(s) (optional)\n%\n% This is a convex problem (after sampling it can be formulated as an SOCP).\n%\n% minimize max |y(theta)| for theta outside the beam\n% s.t. y(theta_tar) = 1\n% y(theta_null) = 0 (optional)\n%\n% where y is the antenna array gain pattern (complex function) and\n% variables are w (antenna array weights or shading coefficients).\n% Gain pattern is a linear function of w: y(theta) = w'*a(theta)\n% for some a(theta) describing antenna array configuration and specs.\n%\n% Written for CVX by Almir Mutapcic 02/02/06\n\n% select array geometry\nARRAY_GEOMETRY = '2D_RANDOM';\n% ARRAY_GEOMETRY = '1D_UNIFORM_LINE';\n% ARRAY_GEOMETRY = '2D_UNIFORM_LATTICE';\n\n% select if the optimal array pattern should enforce nulls or not\nHAS_NULLS = 0; % HAS_NULLS = 1;\n\n%********************************************************************\n% problem specs\n%********************************************************************\nlambda = 1; % wavelength\ntheta_tar = 60; % target direction (should be an integer -- discretization)\nhalf_beamwidth = 10; % half beamwidth around the target direction\n\n% angles where we want nulls (optional)\nif HAS_NULLS\n theta_nulls = [95 110 120 140 225];\nend\n\n%********************************************************************\n% random array of n antenna elements\n%********************************************************************\nif strcmp( ARRAY_GEOMETRY, '2D_RANDOM' )\n % set random seed to repeat experiments\n rand('state',0);\n\n % (uniformly distributed on [0,L]-by-[0,L] square)\n n = 40;\n L = 5;\n loc = L*rand(n,2);\n angleRange = 360;\n\n%********************************************************************\n% uniform 1D array with n elements with inter-element spacing d\n%********************************************************************\nelseif strcmp( ARRAY_GEOMETRY, '1D_UNIFORM_LINE' )\n % (unifrom array on a line)\n n = 30;\n d = 0.45*lambda;\n loc = [d*(0:n-1)' zeros(n,1)];\n angleRange = 180;\n\n%********************************************************************\n% uniform 2D array with m-by-m element with d spacing\n%********************************************************************\nelseif strcmp( ARRAY_GEOMETRY, '2D_UNIFORM_LATTICE' )\n m = 6; n = m^2;\n d = 0.45*lambda;\n\n loc = zeros(n,2);\n for x = 0:m-1\n for y = 0:m-1\n loc(m*y+x+1,:) = [x y];\n end\n end\n loc = loc*d;\n angleRange = 360;\n\nelse\n error('Undefined array geometry')\nend\n\n%********************************************************************\n% construct optimization data\n%********************************************************************\n% build matrix A that relates w and y(theta), ie, y = A*w\ntheta = (1:angleRange)';\nA = kron(cos(pi*theta/180), loc(:,1)') + kron(sin(pi*theta/180), loc(:,2)');\nA = exp(2*pi*1i/lambda*A);\n\n% target constraint matrix\n[diff_closest, ind_closest] = min( abs(theta - theta_tar) );\nAtar = A(ind_closest,:);\n\n% nulls constraint matrix\nif HAS_NULLS\n Anull = []; ind_nulls = [];\n for k = 1:length(theta_nulls)\n [diff_closest, ind_closest] = min( abs(theta - theta_nulls(k)) );\n Anull = [Anull; A(ind_closest,:)]; %#ok\n ind_nulls = [ind_nulls ind_closest]; %#ok\n end\nend\n\n% stopband constraint matrix\nind = find(theta <= (theta_tar-half_beamwidth) | ...\n theta >= (theta_tar+half_beamwidth) );\nif HAS_NULLS, \n ind = setdiff(ind,ind_nulls);\nend;\nAs = A(ind,:);\n\n%********************************************************************\n% optimization problem\n%********************************************************************\ncvx_begin\n variable w(n) complex\n minimize( max( abs(As*w) ) )\n subject to\n Atar*w == 1; %#ok target constraint\n if HAS_NULLS % nulls constraints\n Anull*w == 0; %#ok\n end\ncvx_end\n\n% check if problem was successfully solved\ndisp(['Problem is ' cvx_status])\nif ~strfind(cvx_status,'Solved')\n return\nend\n\nmin_sidelobe_level = 20*log10( max(abs(As*w)) );\nfprintf(1,'The minimum sidelobe level is %3.2f dB.\\n\\n',...\n min_sidelobe_level );\n\n%********************************************************************\n% plots\n%********************************************************************\nfigure(1), clf\nplot(loc(:,1),loc(:,2),'o')\ntitle('Antenna locations')\n\n% plot array pattern\nif angleRange == 180,\n theta = (1:360)';\n A = [ A; -A ];\nend\ny = A*w;\nfigure(2), clf\nymin = floor(0.1*min_sidelobe_level)*10-10; ymax = 0;\nplot(1:360, 20*log10(abs(y)), ...\n [theta_tar theta_tar],[ymin ymax],'r--',...\n [theta_tar+half_beamwidth theta_tar+half_beamwidth],[ymin ymax],'g--',...\n [theta_tar-half_beamwidth theta_tar-half_beamwidth],[ymin ymax],'g--');\nif HAS_NULLS % add lines that represent null positions\n hold on;\n for k = 1:length(theta_nulls)\n plot([theta_nulls(k) theta_nulls(k)],[ymin ymax],'m--');\n end\n hold off;\nend\nxlabel('look angle'), ylabel('mag y(theta) in dB');\naxis([0 360 ymin ymax]);\n\n% polar plot\nfigure(3), clf\nzerodB = -ymin;\ndBY = 20*log10(abs(y)) + zerodB;\nind = find( dBY <= 0 ); dBY(ind) = 0;\nplot(dBY.*cos(pi*theta/180), dBY.*sin(pi*theta/180), '-');\naxis([-zerodB zerodB -zerodB zerodB]), axis('off'), axis('square')\nhold on\nplot(zerodB*cos(pi*theta/180),zerodB*sin(pi*theta/180),'k:') % 0 dB\nplot( (min_sidelobe_level + zerodB)*cos(pi*theta/180), ...\n (min_sidelobe_level + zerodB)*sin(pi*theta/180),'k:') % min level\ntext(-zerodB,0,'0 dB')\ntt = text(-(min_sidelobe_level + zerodB),0,sprintf('%0.1f dB',min_sidelobe_level));\nset(tt,'HorizontalAlignment','right');\ntheta_1 = theta_tar+half_beamwidth;\ntheta_2 = theta_tar-half_beamwidth;\nplot([0 55*cos(theta_tar*pi/180)], [0 55*sin(theta_tar*pi/180)], 'k:')\nplot([0 55*cos(theta_1*pi/180)], [0 55*sin(theta_1*pi/180)], 'k:')\nplot([0 55*cos(theta_2*pi/180)], [0 55*sin(theta_2*pi/180)], 'k:')\nif HAS_NULLS % add lines that represent null positions\n for k = 1:length(theta_nulls)\n plot([0 55*cos(theta_nulls(k)*pi/180)], ...\n [0 55*sin(theta_nulls(k)*pi/180)], 'k:')\n end\nend\nhold off\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/antenna_array_design/ant_array_min_sidelobe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7691616199544449}} {"text": "function result=hl(x)\n\n%HL computes the Hodges-Lehmann location estimate on the columns of x.\n% The Hodges-Lehmann estimator is defined as \n% hl(x)=med {(x_i + x_j)/2} with 1<=i The number of Rows of the input array\n%NColumns=> guess\n%Signal => the matrix with the time data in columns, for instance if you\n% are looking at the cross correlation of orthogonal codes, each code\n% stream would be a column, of course this is NRows by NColumns\n%\n%You can change this m-file to a function if you feel like it\n\nCircXCorrData=zeros(NRows,NColumns^2);%Preallocate space\nh = waitbar(0,'Please wait...');\nSignalFFT=fft(Signal);\nConjSignalFFT=conj(SignalFFT);\nfor index= 1 : NColumns : ( (NColumns-1)*NColumns+1 )\n waitbar(index/( (NColumns-1)*NColumns+1 ))\n CircXCorrData( :,index : index+(NColumns-1) )=ifft(SignalFFT.*ConjSignalFFT); \n ConjSignalFFT=circshift(ConjSignalFFT,[0,1]);\nend\nclose(h)\n\n%Comment the plot out if you want\nplot(max(abs(CircXCorrData)))\ngrid on", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/analyzingtool/CircXCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7690475852882103}} {"text": "function cdf = f_cdf ( x, m, n )\n\n%*****************************************************************************80\n%\n%% F_CDF evaluates the F central CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Formula 26.5.28\n% Abramowitz and Stegun,\n% Handbook of Mathematical Functions.\n%\n% Parameters:\n%\n% Input, real X, the argument of the CDF.\n%\n% Input, integer M, N, the parameters of the PDF.\n% 1 <= M,\n% 1 <= N.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( x <= 0.0 )\n\n cdf = 0.0;\n\n else\n\n arg1 = 0.5 * n;\n arg2 = 0.5 * m;\n arg3 = n / ( n + m * x );\n\n cdf = beta_inc ( arg1, arg2, arg3 );\n\n end\n\n return\nend\n", "meta": {"author": "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/f_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7690317381087133}} {"text": "function [center, U, obj_fcn] = my_fcm(data, cluster_n, options)\n%FCM Data set clustering using fuzzy c-means clustering.\n%\n% [CENTER, U, OBJ_FCN] = FCM(DATA, N_CLUSTER) finds N_CLUSTER number of\n% clusters in the data set DATA. DATA is size M-by-N, where M is the number of\n% data points and N is the number of coordinates for each data point. The\n% coordinates for each cluster center are returned in the rows of the matrix\n% CENTER. The membership function matrix U contains the grade of membership of\n% each DATA point in each cluster. The values 0 and 1 indicate no membership\n% and full membership respectively. Grades between 0 and 1 indicate that the\n% data point has partial membership in a cluster. At each iteration, an\n% objective function is minimized to find the best location for the clusters\n% and its values are returned in OBJ_FCN.\n%\n% [CENTER, ...] = FCM(DATA,N_CLUSTER,OPTIONS) specifies a vector of options\n% for the clustering process:\n% OPTIONS(1): exponent for the matrix U (default: 2.0)\n% OPTIONS(2): maximum number of iterations (default: 100)\n% OPTIONS(3): minimum amount of improvement (default: 1e-5)\n% OPTIONS(4): info display during iteration (default: 1)\n% The clustering process stops when the maximum number of iterations\n% is reached, or when the objective function improvement between two\n% consecutive iterations is less than the minimum amount of improvement\n% specified. Use NaN to select the default value.\n%\n% Example\n% data = rand(100,2);\n% [center,U,obj_fcn] = fcm(data,2);\n% plot(data(:,1), data(:,2),'o');\n% hold on;\n% maxU = max(U);\n% % Find the data points with highest grade of membership in cluster 1\n% index1 = find(U(1,:) == maxU);\n% % Find the data points with highest grade of membership in cluster 2\n% index2 = find(U(2,:) == maxU);\n% line(data(index1,1),data(index1,2),'marker','*','color','g');\n% line(data(index2,1),data(index2,2),'marker','*','color','r');\n% % Plot the cluster centers\n% plot([center([1 2],1)],[center([1 2],2)],'*','color','k')\n% hold off;\n%\n% See also FCMDEMO, INITFCM, IRISFCM, DISTFCM, STEPFCM.\n\n% Roger Jang, 12-13-94, N. Hickey 04-16-01\n% Copyright 1994-2002 The MathWorks, Inc. \n% $Revision: 1.13 $ $Date: 2002/04/14 22:20:38 $\n\nif nargin ~= 2 & nargin ~= 3,\n\terror('Too many or too few input arguments!');\nend\n\ndata_n = size(data, 1);\nin_n = size(data, 2);\n\n% Change the following to set default options\ndefault_options = [2;\t% exponent for the partition matrix U\n\t\t100;\t% max. number of iteration\n\t\t1e-5;\t% min. amount of improvement\n\t\t1];\t% info display during iteration \n\nif nargin == 2,\n\toptions = default_options;\nelse\n\t% If \"options\" is not fully specified, pad it with default values.\n\tif length(options) < 4,\n\t\ttmp = default_options;\n\t\ttmp(1:length(options)) = options;\n\t\toptions = tmp;\n\tend\n\t% If some entries of \"options\" are nan's, replace them with defaults.\n\tnan_index = find(isnan(options)==1);\n\toptions(nan_index) = default_options(nan_index);\n\tif options(1) <= 1,\n\t\terror('The exponent should be greater than 1!');\n\tend\nend\n\nexpo = options(1);\t\t% Exponent for U\nmax_iter = options(2);\t\t% Max. iteration\nmin_impro = options(3);\t\t% Min. improvement\ndisplay = options(4);\t\t% Display info or not\n\nobj_fcn = zeros(max_iter, 1);\t% Array for objective function\n\n\nU = my_initfcm(cluster_n, data_n);\t% changed by Romano Cicchetti in order to obtain reproducable results\n% Main loop\nfor i = 1:max_iter,\n\t[U, center, obj_fcn(i)] = stepfcm(data, U, cluster_n, expo);\n\tif display, \n\t\tfprintf('Iteration count = %d, obj. fcn = %f\\n', i, obj_fcn(i));\n\tend\n\t% check termination condition\n\tif i > 1,\n\t\tif abs(obj_fcn(i) - obj_fcn(i-1)) < min_impro, break; end,\n\tend\nend\n\niter_n = i;\t% Actual number of iterations \nobj_fcn(iter_n+1:max_iter) = [];\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/algorithms/baranski_alg/my_fcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7689755168304772}} {"text": "function spline_test16 ( )\n\n%*****************************************************************************80\n%\n%% TEST16 tests SPLINE_CUBIC_SET, SPLINE_CUBIC_VAL2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author\n%\n% John Burkardt\n%\n n = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST16\\n' );\n fprintf ( 1, ' SPLINE_CUBIC_SET sets up a cubic spline;\\n' );\n fprintf ( 1, ' SPLINE_CUBIC_VAL2 evaluates it.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Runge''s function, evenly spaced knots.\\n' );\n\n for i = 1 : n\n\n t(i) = ( ( n - i ) * (-1.0E+00) ...\n + ( i - 1 ) * (+1.0E+00) ) ...\n / ( n - 1 );\n\n y(i) = frunge ( t(i) );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data to be interpolated:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of data values = %d\\n', n );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T Y\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, '%14f %14f\\n', t(i), y(i) );\n end\n%\n% Try boundary condition types 0, 1 and 2.\n%\n for k = 0 : 2\n\n if ( k == 0 )\n\n ibcbeg = 0;\n ybcbeg = 0.0E+00;\n\n ibcend = 0;\n ybcend = 0.0E+00;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 0 at both ends:\\n' );\n fprintf ( 1, ' Spline is quadratic in boundary intervals.\\n' );\n\n elseif ( k == 1 )\n\n ibcbeg = 1;\n ybcbeg = fprunge ( t(1) );\n\n ibcend = 1;\n ybcend = fprunge ( t(n) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 1 at both ends:\\n' );\n fprintf ( 1, ' Y''(left) = %f\\n', ybcbeg );\n fprintf ( 1, ' Y''(right) = %f\\n', ybcend );\n\n elseif ( k == 2 )\n\n ibcbeg = 2;\n ybcbeg = fpprunge ( t(1) );\n\n ibcend = 2;\n ybcend = fpprunge ( t(n) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 2 at both ends:\\n' );\n fprintf ( 1, ' YP\"(left) = %f\\n', ybcbeg );\n fprintf ( 1, ' YP\"(right) = %f\\n', ybcend );\n\n end\n\n ypp = spline_cubic_set ( n, t, y, ibcbeg, ybcbeg, ibcend, ybcend );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SPLINE\"(T), F\"(T):\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, '%14f %14f\\n', ypp(i), fpprunge(t(i)) );\n end\n\n left = 0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, SPLINE(T), F(T), LEFT_IN, LEFT_OUT\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : n\n\n if ( i == 0 )\n jhi = 1;\n elseif ( i < n )\n jhi = 2;\n else\n jhi = 2;\n end\n\n for j = 1 : jhi\n\n if ( i == 0 )\n tval = t(1) - 1.0E+00;\n elseif ( i < n )\n tval = ( ( jhi - j + 1 ) * t(i) ...\n + ( j - 1 ) * t(i+1) ) ...\n / ( jhi );\n else\n if ( j == 1 )\n tval = t(n);\n else\n tval = t(n) + 1.0E+00;\n end\n end\n\n left_in = left;\n\n [ yval, ypval, yppval ] = ...\n spline_cubic_val2 ( n, t, y, ypp, left, tval );\n\n fprintf ( 1, '%14f %14f %14f %6d %6d\\n', ...\n tval, yval, frunge ( tval ), left_in, left );\n\n end\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/spline_test16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7689738766860099}} {"text": "function ref = physical_to_reference_t3 ( t, n, phy )\n\n%*****************************************************************************80\n%\n%% PHYSICAL_TO_REFERENCE_T3 maps a physical point to a reference point.\n%\n% Discussion:\n%\n% Given the vertices of an order 3 physical triangle and a point\n% (X,Y) in the physical triangle, the routine computes the value\n% of the corresponding image point (XSI,ETA) in reference space.\n%\n% Note that this routine may also be appropriate for an order 6\n% triangle, if the mapping between reference and physical space\n% is linear. This implies, in particular, that the sides of the\n% image triangle are straight and that the \"midside\" nodes in the\n% physical triangle are halfway along the sides of\n% the physical triangle.\n%\n% Reference Element T3:\n%\n% |\n% 1 3\n% | |\\\n% | | \\\n% S | \\\n% | | \\\n% | | \\\n% 0 1-----2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the X and Y coordinates\n% of the vertices. The vertices are assumed to be the images of\n% (0,0), (1,0) and (0,1) respectively.\n%\n% Input, integer N, the number of points to transform.\n%\n% Input, real PHY(2,N), the coordinates of points in the physical space.\n%\n% Output, real REF(2,N), the coordinates of the corresponding\n% points in the reference space.\n%\n ref(1,1:n) = ( ( t(2,3) - t(2,1) ) * ( phy(1,1:n) - t(1,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( phy(2,1:n) - t(2,1) ) ) ...\n / ( ( t(2,3) - t(2,1) ) * ( t(1,2) - t(1,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( t(2,2) - t(2,1) ) );\n\n ref(2,1:n) = ( ( t(1,2) - t(1,1) ) * ( phy(2,1:n) - t(2,1) ) ...\n - ( t(2,2) - t(2,1) ) * ( phy(1,1:n) - t(1,1) ) ) ...\n / ( ( t(2,3) - t(2,1) ) * ( t(1,2) - t(1,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( t(2,2) - t(2,1) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/physical_to_reference_t3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.768973873800807}} {"text": "function value = hankel_n_condition ( n )\n\n%*****************************************************************************80\n%\n%% HANKEL_N_CONDITION returns the L1 condition of the HANKEL_N matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real VALUE, the L1 condition.\n%\n v = zeros ( n, 1 );\n\n v(1) = 1.0 / n;\n for i = 2 : n\n v(i) = 0.0;\n for j = 1 : i - 1\n v(i) = v(i) - ( n + j - i ) * v(j);\n end\n v(i) = v(i) / n;\n end\n\n a_norm = ( n * ( n + 1 ) ) / 2;\n b_norm = sum ( abs ( v(1: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/hankel_n_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7689738654310277}} {"text": "function [ n_data_new, x, y, fxy ] = beta_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BETA_VALUES returns some values of the Beta function.\n%\n% Formula:\n%\n% BETA(X,Y) = ( GAMMA(X) * GAMMA(Y) ) / GAMMA(X+Y)\n%\n% Restrictions:\n%\n% Both X and Y must be greater than 0.\n%\n% Properties:\n%\n% BETA(X,Y) = BETA(Y,X).\n% BETA(X,Y) = Integral ( 0 <= T <= 1 ) T**(X-1) (1-T)**(Y-1) dT.\n% BETA(X,Y) = GAMMA(X) * GAMMA(Y) / GAMMA(X+Y)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N_DATA, indicates the index of the previous test data\n% returned, or is 0 if this is the first call. For repeated calls,\n% set the input value of N_DATA to the output value of N_DATA_NEW\n% from the previous call.\n%\n% Output, integer N_DATA_NEW, the index of the test data.\n%\n% Output, real X, Y, the arguments of the function.\n%\n% Output, real FXY, the value of the function.\n%\n n_max = 17;\n b_vec = [ ...\n 5.000000E+00, 2.500000E+00, 1.666667E+00, 1.250000E+00, ...\n 5.000000E+00, 2.500000E+00, 1.000000E+00, 1.666667E-01, ...\n 0.333333E-01, 7.142857E-03, 1.587302E-03, 0.238095E-01, ...\n 5.952381E-03, 1.984127E-03, 7.936508E-04, 3.607504E-04, ...\n 8.325008E-05 ];\n x_vec = [ ...\n 0.2E+00, 0.4E+00, 0.6E+00, 0.8E+00, ...\n 1.0E+00, 1.0E+00, 1.0E+00, 2.0E+00, ...\n 3.0E+00, 4.0E+00, 5.0E+00, 6.0E+00, ...\n 6.0E+00, 6.0E+00, 6.0E+00, 6.0E+00, ...\n 7.0E+00 ];\n y_vec = [ ...\n 1.0E+00, 1.0E+00, 1.0E+00, 1.0E+00, ...\n 0.2E+00, 0.4E+00, 1.0E+00, 2.0E+00, ...\n 3.0E+00, 4.0E+00, 5.0E+00, 2.0E+00, ...\n 3.0E+00, 4.0E+00, 5.0E+00, 6.0E+00, ...\n 7.0E+00 ];\n\n n_data_new = n_data;\n\n if ( n_data_new < 0 )\n n_data_new = 0;\n end\n\n n_data_new = n_data_new + 1;\n\n if ( n_max < n_data_new )\n n_data_new = 0;\n x = 0.0E+00;\n y = 0.0E+00;\n fxy = 0.0E+00;\n else\n x = x_vec(n_data_new);\n y = y_vec(n_data_new);\n fxy = b_vec(n_data_new);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/beta_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.768940090508439}} {"text": "%% RATE OF CONVERGENCE OF ADAPTIVE FINITE ELEMENT METHOD USING WG ELEMENT\n%\n% This example is to show the rate of convergence of the lowest order weak\n% Galerkin element approximation of the second order elliptic equation.\n%\n% Reference\n%\n% L. Chen, J. Wang and X. Ye. A posteriori error estimates for Weak\n% Galerkin finite element methods for second order elliptic problems.\n% Journal of Scientific Computing, 59(2), 496-511, 2014.\n\n%% Lshape problem\n% mesh\n[node,elem] = cubemesh([-1,1,-1,1,-1,1],1);\n[node,elem] = delmesh(node,elem,'x>0 & y<0');\nbdFlag = setboundary3(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n% pde\npde = Lshapedata3;\n% option\nformat shorte\noption.L0 = 1;\noption.maxIt = 50;\noption.printlevel = 1;\noption.elemType = 'WG';\noption.plotflag = 1;\noption.maxN = 2e4;\n% AFEM\nerr = afemPoisson3(mesh,pde,option);\n% plot\nfigure;\nshowrate2(err.N,err.H1,10,'k-*','|| Du-Du_h||',err.N,err.eta,10,'k-+','eta');\n% latexerrtable(err.N,[err.H1 err.eta])\n\n%% Jump coefficients\n% The diffusion coefficent is piecewise constant with large jump.\n[node,elem] = cubemesh([-1,1,-1,1,-1,1],1);\nbdFlag = setboundary3(node,elem,'Dirichlet','(x==1) | (x==-1)');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n% pde\npde = jumpmgdata1;\nglobal epsilon\nepsilon = 1e-4;\n% option\noption.L0 = 3;\noption.maxIt = 50;\noption.printlevel = 1;\noption.elemType = 'WG';\noption.plotflag = 1;\noption.maxN = 1e4;\noption.viewcut = '~(x<=0 & y>=0 & z>=0)';\noption.viewangle = [59,20];\n% AFEM\nerr = afemPoisson3(mesh,pde,option);\n% plot\nfigure;\nshowrate2(err.N,err.H1,10,'k-*','||Du-Du_h||',err.N,err.eta,10,'k-+','eta');\n% Note no exact solution to compute the error. Code the energy later on.", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/afem/WGafemrate3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7689400869311078}} {"text": "function trans = localToGlobal3d(varargin)\n%LOCALTOGLOBAL3D Transformation matrix from local to global coordinate system.\n%\n% TRANS = localToGlobal3d(CENTER, THETA, PHI, PSI)\n% Compute the transformation matrix from a local (or modelling)\n% coordinate system to the global (or world) coordinate system.\n% This is a low-level function, used by several drawing functions.\n%\n% The transform is defined by:\n% - CENTER: the position of the local origin into the world coordinate\n% system\n% - THETA: colatitude, defined as the angle with the Oz axis (between 0\n% and 180 degrees), positive in the direction of the of Oy axis.\n% - PHI: azimut, defined as the angle of the normal with the Ox axis,\n% between 0 and 360 degrees\n% - PSI: intrinsic rotation, corresponding to the rotation of the object\n% around the direction vector, between 0 and 360 degrees\n%\n% The resulting transform is obtained by applying (in that order):\n% - Rotation by PSI around the Z-axis\n% - Rotation by THETA around the Y-axis\n% - Rotation by PHI around the Z-axis\n% - Translation by vector CENTER\n% This corresponds to Euler ZYZ rotation, using angles PHI, THETA and\n% PSI.\n%\n% The 'eulerAnglesToRotation3d' function may better suit your needs as\n% it is more 'natural'.\n%\n% Example\n% localToGlobal3d\n%\n% See also \n% transforms3d, eulerAnglesToRotation3d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2009-06-19, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009-2022 INRA - Cepia Software Platform\n\n% extract the components of the transform\nif nargin == 1\n % all components are bundled in the first argument\n var = varargin{1};\n center = var(1:3);\n theta = var(4);\n phi = var(5);\n psi = 0;\n if length(var) > 5\n psi = var(6);\n end\n \nelseif nargin == 4\n % arguments = center, then the 3 angles\n center = varargin{1};\n theta = varargin{2};\n phi = varargin{3};\n psi = varargin{4}; \n \nelseif nargin > 4\n % center is given in 3 arguments, then 3 angles\n center = [varargin{1} varargin{2} varargin{3}];\n theta = varargin{4};\n phi = varargin{5};\n psi = 0;\n if nargin > 5\n psi = varargin{6}; \n end\nend\n \n% conversion from degrees to radians\nk = pi / 180;\n\n% rotation around normal vector axis\nrot1 = createRotationOz(psi * k);\n\n% colatitude\nrot2 = createRotationOy(theta * k);\n\n% longitude\nrot3 = createRotationOz(phi * k);\n\n% shift center\ntr = createTranslation3d(center);\n\n% create final transform by concatenating transforms\ntrans = tr * rot3 * rot2 * rot1;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/private/localToGlobal3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7689400853892003}} {"text": "%% NLS1 Original\nclc\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata);\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Setup Options\nopts = optiset('solver','matlab','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'data',xdata,ydata,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nconfidence(Opt)\nplot(Opt)\n\n%% NLS1 Weighted [no grad]\nclc\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata);\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','lmder','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',[],'data',xdata,ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\n[cInt,stats] = confidence(Opt)\nplot(Opt)\n\n%% NLS1 Weighted no xdata [no grad]\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Function\nfun = @(x) x(1)*exp(x(2)*xdata);\ngrad = @(x) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','lmder','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',[],'ydata',ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted [with grad]\nclc\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata);\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','lmder','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'data',xdata,ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted no xdata [with grad]\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Function\nfun = @(x) x(1)*exp(x(2)*xdata);\ngrad = @(x) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','lmder','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'ydata',ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP [no grad], MANUAL WEIGHTS\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\n%Fitting Weights\nweights = ones(size(xdata)); weights(end) = 1e3; \nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]'.*weights;\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata).*weights;\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',[],'data',xdata,ydata,'weights',[],'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP [no grad], AUTO WEIGHTS\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]';\n%Fitting Weights\nweights = ones(size(xdata)); weights(end) = 1e3; \n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata);\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',[],'data',xdata,ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP no xdata [no grad]\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Function\nfun = @(x) x(1)*exp(x(2)*xdata);\ngrad = @(x) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',[],'ydata',ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP [WITH grad], MANUAL WEIGHTS\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\n%Fitting Weights\nweights = ones(size(xdata)); weights(end) = 1e3;\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]'.*weights;\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata).*weights;\ngrad = @(x,xdata) [ exp(x(2).*xdata).*weights, x(1).*xdata.*exp(x(2).*xdata).*weights];\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'data',xdata,ydata,'weights',[],'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP [WITH grad], AUTO WEIGHTS\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5]';\n%Fitting Weights\nweights = ones(size(xdata)); weights(end) = 1e3;\n%Function\nfun = @(x,xdata) x(1)*exp(x(2)*xdata);\ngrad = @(x,xdata) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'data',xdata,ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS1 Weighted as NLP no xdata [WITH grad]\nclc\n%Fitting Data\nxdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3]';\nydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];\n%Function\nfun = @(x) x(1)*exp(x(2)*xdata);\ngrad = @(x) [ exp(x(2).*xdata), x(1).*xdata.*exp(x(2).*xdata)];\n%Fitting Weights\nweights = ones(size(ydata)); weights(end) = 1e3;\n%Setup Options\nopts = optiset('solver','ipopt','display','iter');\n%Build & Solve\nOpt = opti('fun',fun,'grad',grad,'ydata',ydata,'weights',weights,'ndec',2,'options',opts)\nx0 = [100; -1]; % Starting guess\n[x,fval,exitflag,info] = solve(Opt,x0)\n%Plot\nplot(Opt)\n\n%% NLS2\nclc\n%Function\ni = (1:40)';\nfun = @(x) x(1)*exp(-x(2)*i) + x(3);\n%Fitting Data\nydata=[5.8728, 5.4948, 5.0081, 4.5929, 4.3574, 4.1198, 3.6843, 3.3642, 2.9742, 3.0237, 2.7002, 2.8781,...\n 2.5144, 2.4432, 2.2894, 2.0938, 1.9265, 2.1271, 1.8387, 1.7791, 1.6686, 1.6232, 1.571, 1.6057,...\n 1.3825, 1.5087, 1.3624, 1.4206, 1.2097, 1.3129, 1.131, 1.306, 1.2008, 1.3469, 1.1837, 1.2102,...\n 0.96518, 1.2129, 1.2003, 1.0743];\n%Setup Options\nopts = optiset('solver','mkltrnls','display','iter');\n%Build & Solve\nx0=[1.0; 0.0; 0.0];\nOpt = opti('fun',fun,'ydata',ydata,'ndec',3,'options',opts)\n[x,fval,exitflag,info] = solve(Opt,x0)\n\nplot(Opt)\n\n%% NLS2 w Weights\nclc\n%Function\ni = (1:40)';\nfun = @(x) x(1)*exp(-x(2)*i) + x(3);\n%Fitting Data\nydata=[5.8728, 5.4948, 5.0081, 4.5929, 4.3574, 4.1198, 3.6843, 3.3642, 2.9742, 3.0237, 2.7002, 2.8781,...\n 2.5144, 2.4432, 2.2894, 2.0938, 1.9265, 2.1271, 1.8387, 1.7791, 1.6686, 1.6232, 1.571, 1.6057,...\n 1.3825, 1.5087, 1.3624, 1.4206, 1.2097, 1.3129, 1.131, 1.306, 1.2008, 1.3469, 1.1837, 1.2102,...\n 0.96518, 1.2129, 1.2003, 1.0743];\n%Weighting\nwts = ones(size(ydata)); wts([1 end]) = 1e3;\n%Build & Solve\nx0=[1.0; 0.0; 0.0];\nOpt = opti('fun',fun,'ydata',ydata,'x0',x0);\nOptW = opti('fun',fun,'ydata',ydata,'weights',wts,'x0',x0);\nx = solve(Opt)\nxw = solve(OptW)\n\nplot(i,ydata,'ko',i(end),ydata(end),'ksq',i,fun(xw),'r*-',i,fun(x),'m*-')\nxlim([length(i)*0.45 length(i)*1.01]); xlabel('i'); ylabel('y'); \nlegend('Original Data','Target Point','Weighted Fit','Standard Fit');\ntitle('NLS Curve Fit - Comparison of Weighted and Un-weighted');\n\n%% NLS3 (Modified NLP - HS76)\nclc\n%Function\nfun = @(x) [x(1);\n sqrt(0.5)*x(2);\n x(3);\n sqrt(0.5)*x(4);];\n%Fitting Data\nydata = [0.0, 0.0, 0.0, 0.0];\n%Constraints\nlb = [0.0, 0.0, 0.0, 0.0];\nub = [inf, inf, inf, inf];\nA = -[-1.0, -2.0, -1.0, -1.0;\n -3.0, -1.0, -2.0, 1.0];\nb = -[-5.0, -0.4]';\nAeq = [0.0, 1.0, 4.0, 0.0];\nbeq = 1.5;\n%Setup Options\nopts = optiset('solver','levmar','display','iter');\n%Build & Solve\nx0 = [0.5, 0.5, 0.5, 0.5];\nOpt = opti('fun',fun,'ydata',ydata,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info] = solve(Opt,x0)\n\n%% NLS Example Prob\nclc\n%Get Problem\nprob = nls_prob(19);\nopts = optiset('display','iter');\n%Build OPTI Object\nOpt = opti(prob,opts);\n%Solve\n[x,fval,exitflag,info] = solve(Opt)\n%Plot\nplot(Opt,[],1)", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Test Problems/Development/test_weighted_nls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7689400810715946}} {"text": "function [lat2,lon2,h2]=direct(lat1,lon1,h1,az,va,d,a,e2)\n% DIRECT Computes direct (forward) geodetic problem.\n% Determines coordinates of 2nd station given ellipsoidal\n% coordinates of 1st station and azimuth, vertical angle\n% and distance from 1st to 2nd station. If az,va are local\n% astronomic, lat,lon must also be astronomic. If az,va\n% are local geodetic, lat,lon must be local geodetic.\n% Non-vectorized. See also INVERSE.\n% Version: 2011-02-19\n% Useage: [lat2,lon2,h2]=direct(lat1,lon1,h1,az,va,d,a,e2)\n% [lat2,lon2,h2]=direct(lat1,lon1,h1,az,va,d)\n% Input: lat1 - ellipsoidal latitude of 1st station (rads)\n% lon1 - ellipsoidal longitude of 1st station (rads)\n% h1 - ellipsoidal ht. of 1st station (m)\n% az - azimuth from station 1 to 2 (rads)\n% va - vertical angle from 1 to 2 (rads)\n% d - distance from 1 to 2 (m)\n% a - ref. ellipsoid major semi-axis (m); default GRS80\n% e2 - ref. ellipsoid eccentricity squared; default GRS80\n% Output: lat2 - ellipsoidal latitude of 2nd station (rads)\n% lon2 - ellipsoidal longitude of 2nd station (rads)\n% h2 - ellipsoidal ht. of 2nd station (m)\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nif nargin ~= 6 & nargin ~= 8\n warning('Incorrect number of input arguments');\n return\nend\nif nargin == 6\n [a,b,e2]=refell('grs80');\nend\n\n[X1,Y1,Z1]=ell2xyz(lat1,lon1,h1,a,e2);\n[dx,dy,dz]=sph2xyz(az,va,d);\n[dX,dY,dZ]=lg2ct(dx,dy,dz,lat1,lon1);\nX2=X1+dX;\nY2=Y1+dY;\nZ2=Z1+dZ;\n[lat2,lon2,h2]=xyz2ell(X2,Y2,Z2,a,e2);\n", "meta": {"author": "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/direct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7689323417284885}} {"text": "function l = legendre_symbol ( q, p )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_SYMBOL evaluates the Legendre symbol (Q/P).\n%\n% Discussion:\n%\n% Let P be an odd prime. Q is a QUADRATIC RESIDUE modulo P\n% if there is an integer R such that R**2 = Q ( mod P ).\n% The Legendre symbol ( Q / P ) is defined to be:\n%\n% + 1 if Q ( mod P ) /= 0 and Q is a quadratic residue modulo P,\n% - 1 if Q ( mod P ) /= 0 and Q is not a quadratic residue modulo P,\n% 0 if Q ( mod P ) == 0.\n%\n% We can also define ( Q / P ) for P = 2 by:\n%\n% + 1 if Q ( mod P ) /= 0\n% 0 if Q ( mod P ) == 0\n%\n% Example:\n%\n% (0/7) = 0\n% (1/7) = + 1 ( 1^2 = 1 mod 7 )\n% (2/7) = + 1 ( 3^2 = 2 mod 7 )\n% (3/7) = - 1\n% (4/7) = + 1 ( 2^2 = 4 mod 7 )\n% (5/7) = - 1\n% (6/7) = - 1\n%\n% Note:\n%\n% For any prime P, exactly half of the integers from 1 to P-1\n% are quadratic residues.\n%\n% ( 0 / P ) = 0.\n%\n% ( Q / P ) = ( mod ( Q, P ) / P ).\n%\n% ( Q / P ) = ( Q1 / P ) * ( Q2 / P ) if Q = Q1 * Q2.\n%\n% If Q is prime, and P is prime and greater than 2, then:\n%\n% if ( Q == 1 ) then\n%\n% ( Q / P ) = 1\n%\n% else if ( Q == 2 ) then\n%\n% ( Q / P ) = + 1 if mod ( P, 8 ) = 1 or mod ( P, 8 ) = 7,\n% ( Q / P ) = - 1 if mod ( P, 8 ) = 3 or mod ( P, 8 ) = 5.\n%\n% else\n%\n% ( Q / P ) = - ( P / Q ) if Q = 3 ( mod 4 ) and P = 3 ( mod 4 ),\n% = ( P / Q ) otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Charles Pinter,\n% A Book of Abstract Algebra,\n% McGraw Hill, 1982, pages 236-237.\n%\n% Daniel Zwillinger,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996, pages 86-87.\n%\n% Parameters:\n%\n% Input, integer Q, an integer whose Legendre symbol with\n% respect to P is desired.\n%\n% Input, integer P, a prime number, greater than 1, with respect\n% to which the Legendre symbol of Q is desired.\n%\n% Output, integer L, the Legendre symbol (Q/P).\n% Ordinarily, L will be -1, 0 or 1.\n% L = -2, P is less than or equal to 1.\n% L = -3, P is not prime.\n% L = -4, the internal stack of factors overflowed.\n% L = -5, not enough factorization space.\n%\n\n%\n% P must be greater than 1.\n%\n if ( p <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' P must be greater than 1.\\n' );\n l = -2;\n error ( 'LEGENDRE_SYMBOL - Fatal error!' );\n end\n%\n% P must be prime.\n%\n if ( ~i4_is_prime ( p ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' P is not prime.\\n' );\n l = -3;\n error ( 'LEGENDRE_SYMBOL - Fatal error!' );\n end\n%\n% ( k*P / P ) = 0.\n%\n if ( mod ( q, p ) == 0 )\n l = 0;\n return\n end\n%\n% For the special case P = 2, (Q/P) = 1 for all odd numbers.\n%\n if ( p == 2 )\n l = 1;\n return\n end\n%\n% Make a copy of Q, and force it to be nonnegative.\n%\n qq = q;\n\n while ( qq < 0 )\n qq = qq + p;\n end\n\n nstack = 0;\n pp = p;\n l = 1;\n\n while ( 1 )\n\n qq = mod ( qq, pp );\n%\n% Decompose QQ into factors of prime powers.\n%\n [ nfactor, factor, power, nleft ] = i4_factor ( qq );\n\n if ( nleft ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_SYMBOL - Fatal error!\\n' );\n fprintf ( 1, ' Not enough factorization space.\\n' );\n l = -5;\n error ( 'LEGENDRE_SYMBOL - Fatal error!' );\n end\n%\n% Each factor which is an odd power is added to the stack.\n%\n nmore = 0;\n\n for i = 1 : nfactor\n\n if ( mod ( power(i), 2 ) == 1 )\n\n nmore = nmore + 1;\n nstack = nstack + 1;\n\n pstack(nstack) = pp;\n qstack(nstack) = factor(i);\n\n end\n\n end\n\n if ( nmore ~= 0 )\n\n qq = qstack(nstack);\n nstack = nstack - 1;\n%\n% Check for a QQ of 1 or 2.\n%\n if ( qq == 1 )\n\n l = + 1 * l;\n\n elseif ( qq == 2 & ( mod ( pp, 8 ) == 1 | mod ( pp, 8 ) == 7 ) )\n\n l = + 1 * l;\n\n elseif ( qq == 2 & ( mod ( pp, 8 ) == 3 | mod ( pp, 8 ) == 5 ) )\n\n l = - 1 * l;\n\n else\n\n if ( mod ( pp, 4 ) == 3 & mod ( qq, 4 ) == 3 )\n l = - 1 * l;\n end\n\n [ pp, qq ] = i4_swap ( pp, qq );\n\n continue\n\n end\n\n end\n%\n% If the stack is empty, we're done.\n%\n if ( nstack == 0 )\n break\n end\n%\n% Otherwise, get the last P and Q from the stack, and process them.\n%\n pp = pstack(nstack);\n qq = qstack(nstack);\n nstack = nstack - 1;\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/legendre_symbol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7689268832489778}} {"text": "%% CHUTE Chutes and ladders analysis.\n%\n% Discussion:\n%\n% This script determines the probability of finishing a one-player\n% game of chutes and ladders in exactly N moves (PDF) or in no more \n% than N moves (CDF).\n\n%\n% The game starts at square 0, and ends when square 100 is reached.\n%\n% Modified:\n%\n% 19 September 2014\n%\n% Author:\n\n%\n\n% Desmond Higham, Nicholas Higham\n\n%\n\n% Reference:\n\n%\n\n% Desmond Higham, Nicholas Higham,\n\n% MATLAB Guide,\n\n% SIAM, 2005,\n\n% ISBN13: 9780898717891.\n\n%\n N = 100;\n%\n% \"+1\" translates square to state.\n%\n top = [ 1 4 9 16 21 28 36 47 49 51 56 62 64 71 80 87 93 95 98] + 1;\n bot = [38 14 31 6 42 84 44 26 11 67 53 19 60 91 100 24 73 75 78] + 1;\n\n P = toeplitz(zeros(1,N+1),[0 ones(1,6) zeros(1,N-6)]);\n\n for k = N-4:N+1\n P(k,k) = k-N+5;\n end\n P = P/6;\n\n for k = 1:length(top)\n r = top(k); s = bot(k); % Chute or ladder from r to s.\n P(:,s) = P(:,s) + P(:,r); % Add column r to column s.\n end\n P(top,:) = [];\n P(:,top) = []; % Remove starts of chutes and ladders.\n\n figure(1)\n spy(P)\n\n M = 200;\n cumprob = zeros(M,1);\n cumprob(1) = P(1,end);\n v = P(1,:);\n for n = 2:M,\n v = v*P;\n cumprob(n) = v(end);\n end\n\n figure(2)\n colormap([0.8,0.4,0.4])\n bar(diff([0;cumprob]))\n title('Probability for Game Length','FontSize',12,'FontWeight','Bold')\n grid on\n xlim([0 M])\n\n \nfigure(3)\n \ncolormap([0.8,0.4,0.4])\n bar(cumprob)\n title('Cumulative Probability for Game Length',...\n 'FontSize',12,'FontWeight','Bold')\n grid on\n xlim([0 M])\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/snakes_and_ladders/chute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7689268813850012}} {"text": "function circle_test ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_TEST applies continuation to the circle problem.\n%\n% Discussion:\n%\n% Our function is \n%\n% f(x,y) = x^2 + y^2 - 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n step_max = 35;\n step_num = 0;\n xy = zeros ( 2, step_max );\n%\n% A: \n% Choose a starting point,\n% Choose a starting \"parameter\",\n% Call Newton to try to get starting point to satisfy implicit function\n% while holding parameter fixed.\n%\n n = 2;\n x0 = [ 0.5; -2.0 ];\n p0 = 1;\n tol = 1.0E-05;\n\n fx_norm = max ( abs ( f_circle ( n, x0 ) ) );\n fprintf ( 1, ' %2d %14.6g %14.6g %8.2e\\n', 0, x0(1), x0(2), fx_norm );\n\n [ status, x2 ] = newton ( n, x0, p0, @f_circle, @fp_circle, tol );\n\n step_num = step_num + 1;\n\n xy(1:2,step_num) = x2(1:2,1);\n fx_norm = max ( abs ( f_circle ( n, x2 ) ) );\n fprintf ( 1, ' %2d %14.6g %14.6g %8.2e\\n', step_num, x2(1), x2(2), fx_norm );\n%\n% B:\n% X0 <= X2.\n% Take a step from the current point X0.\n%\n x0 = x2;\n t0 = zeros ( n, 1 );\n h = 0.15;\n \n for step_num = 2 : step_max\n\n [ status, x2, t2, p2 ] = step ( n, x0, t0, p0, @f_circle, @fp_circle, h, tol );\n\n if ( status ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP failed!\\n' );\n break\n end\n\n xy(1:2,step_num) = x2(1:2,1);\n fx_norm = max ( abs ( f_circle ( n, x2 ) ) );\n fprintf ( 1, ' %2d %14.6g %14.6g %8.2e\\n', step_num, x2(1), x2(2), fx_norm );\n\n if ( p0 ~= p2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Switching parameters from %d to %d\\n', p0, p2 );\n p0 = p2;\n end\n\n x0 = x2;\n t0 = t2;\n\n end\n%\n% Plot the points.\n%\n plot ( xy(1,:), xy(2,:), 'r.-', 'Markersize', 25 );\n grid on\n axis equal\n xlabel ( '<--- X --->', 'Fontsize', 16 );\n ylabel ( '<--- Y --->', 'Fontsize', 16 );\n title ( 'Points on the circle, by the continuation method.', 'Fontsize', 24 );\n\n filename = 'circle_test.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot file saved as \"%s\"\\n', filename );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/continuation/circle_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7689268723239282}} {"text": "%LINES5D Generates three 5-dimensional lines\n%\n%\tA = LINES5D(N);\n%\n% Generates a data set of N points, on 3 non-crossing, non-parallel lines\n% in 5 dimensions. \n%\n% If N is a vector of sizes, exactly N(I) objects are generated\n% for class I, I = 1,2.Default: N = [50 50 50].\n%\n% See also DATASETS, PRDATASETS\n\n% Copyright: E. Pekalska, 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: lines5d.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction data = lines5d(N)\n\t\t\tif nargin< 1, N = [50 50 50]; end\n\n\tN = genclass(N,ones(1,3)/3);\n\tn1 = N(1);\n\tn2 = N(2);\n\tn3 = N(3);\n\n s1 = [0 0 0 1 0];\n s2 = [1 1 1 0 0];\n s3 = [0 1 0 1 0];\n s4 = [1 1 1 1 1];\n s5 = [0 1 1 0 1];\n s6 = [1 0 1 1 1];\n c1 = [0:1/(n1-1):1]';\n c2 = [0:1/(n2-1):1]';\n c3 = [0:1/(n3-1):1]';\n a = c1*s1 + (1-c1)*s2;\n a = [a; c2*s3 + (1-c2)*s4];\n a = [a; c3*s5 + (1-c3)*s6];\n\n\tdata = prdataset(a,genlab(N));\n\tdata = setname(data,'5D Lines');\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/lines5d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7687758371735708}} {"text": "function Lambda = MakeFourierDiagonal_2D(n,deep)\n% MakeFourierDiagonal_2D: \n% Usage:\n% Lambda = Inv_SeparateAngles(R,deep,MaxIts,ErrTol);\n% Inputs:\n% n dyadic integer\n% deep Depth of the angular splitting\n% Outputs:\n% Lambda (2*n-1) * n/4 * 2 array of Fourier multipliers\n% Description\n% AtA has a Toeplitz structure. A Toeplitz matrix is embedded in\n% a larger circulant matrix. A circulant matrix is diagonal in a \n% Fourier basis; lambda is the vector of those diagonal\n% coefficients. \n% See Also\n% AtA_Toeplitz, MakeFourierDiagonal\n%\n% By Emmanuel Candes, 2003-2004\n\n\t n2 = n/2;\n boxlen = n/2^deep;\n\t boxcnt = 2^deep;\t\n \n\t [ix,w] = DetailMeyerWindow([n2/4 n2/2],3);\n\t lx = reverse(-ix);\n\t \n\t m = 0:(boxcnt - 1);\n ym = (m-boxcnt/2).*boxlen + boxlen/2;\n\t slope = -ym./n2;\t\t \n\t \n\t Lambda = zeros(2*n-1,n2/2,2);\n\t \n for r = 1:(n2/2),\n k = lx(r); \n shift = ym + slope.*(k+n2);\n alpha = -k/n2;\n w = MakeSineWindow(boxlen,alpha);\t\n lambda = MakeFourierDiagonal(n,shift,boxlen,1,w);\n \n Lambda(:,r,1) = lambda;\n \n rsym = n2/2 + 1 - r; %shift = -shift + 1;\n %Lambda(:,rsym,2) = MakeFourierDiagonal(n,shift,boxlen,1,w);\n Lambda(:,rsym,2) = ifft(conj(fft(lambda)));\n end\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/CurveCoeff/MakeFourierDiagonal_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7687722568485921}} {"text": "function [Aeq beq]= getAbeq(n_seg, n_order, waypoints, ts, start_cond, end_cond)\n n_all_poly = n_seg*(n_order+1);% the number of all polynomial coefficients\n %#####################################################\n % p,v,a,j constraint in start, \n Aeq_start = zeros(4, n_all_poly);\n beq_start = zeros(4, 1); \n % STEP 2.1: write expression of Aeq_start and beq_start\n Aeq_start(1:1:4, 1:1:n_order+1) = [0, 0, 0, 0, 0, 0, 0, 1;\n 0, 0, 0, 0, 0, 0, 1, 0;\n 0, 0, 0, 0, 0, 2, 0, 0;\n 0, 0, 0, 0, 6, 0, 0, 0];\n beq_start = start_cond';% p,v,a,j\n \n %#####################################################\n % p,v,a constraint in end\n Aeq_end = zeros(4, n_all_poly);\n beq_end = zeros(4, 1);\n % STEP 2.2: write expression of Aeq_end and beq_end\n T = ts(size(ts,1));% time of the last trajectory\n Aeq_end(1:1:4, n_all_poly-n_order:1:n_all_poly) = [ T^7, T^6, T^5, T^4, T^3, T^2, T, 1;\n 7*T^6, 6*T^5, 5*T^4, 4*T^3, 3*T^2, 2*T, 1, 0;\n 42*T^5, 30*T^4, 20*T^3, 12*T^2, 6*T, 2, 0, 0;\n 210*T^4, 120*T^3, 60*T^2, 24*T, 6, 0, 0, 0];\n beq_end = end_cond';% p,v,a,j\n \n %#####################################################\n % position constrain in all middle waypoints\n Aeq_wp = zeros(n_seg-1, n_all_poly);\n beq_wp = zeros(n_seg-1, 1);\n % STEP 2.3: write expression of Aeq_wp and beq_wp\n for midwp_index = 1:n_seg-1\n index = 1 + 8 * (midwp_index - 1);\n T = ts(midwp_index);\n Aeq_wp(midwp_index,index:index+7) = [T^7, T^6, T^5, T^4, T^3, T^2, T, 1];% the end of previous segment\n % Aeq_wp(midwp_index,index+8:index+8+7) = [0, 0, 0, 0, 0, 0, 0, 1];% the begin of next segment\n end\n beq_wp = waypoints(2:n_seg,1);\n \n %#####################################################\n % position continuity constrain between each 2 segments\n Aeq_con_p = zeros(n_seg-1, n_all_poly);\n beq_con_p = zeros(n_seg-1, 1);\n % STEP 2.4: write expression of Aeq_con_p and beq_con_p\n for con_p_index = 1:n_seg-1\n index = 1 + 8 * (con_p_index - 1);\n T = ts(con_p_index);\n Aeq_con_p(con_p_index,index:index+7) = [T^7, T^6, T^5, T^4, T^3, T^2, T, 1];% the end of previous segment\n Aeq_con_p(con_p_index,index+8:index+8+7) = [0, 0, 0, 0, 0, 0, 0, -1];% the begin of next segment\n end\n % beq_con_p is a zero vector\n \n %#####################################################\n % velocity continuity constrain between each 2 segments\n Aeq_con_v = zeros(n_seg-1, n_all_poly);\n beq_con_v = zeros(n_seg-1, 1);\n % STEP 2.5: write expression of Aeq_con_v and beq_con_v\n for con_v_index = 1:n_seg-1\n index = 1 + 8 * (con_v_index - 1);\n T = ts(con_v_index);\n Aeq_con_v(con_v_index,index:index+7) = [7*T^6, 6*T^5, 5*T^4, 4*T^3, 3*T^2, 2*T, 1, 0];% the end of previous segment\n Aeq_con_v(con_v_index,index+8:index+8+7) = [0, 0, 0, 0, 0, 0, -1, 0];% the begin of next segment\n end\n % beq_con_v is a zero vector\n \n %#####################################################\n % acceleration continuity constrain between each 2 segments\n Aeq_con_a = zeros(n_seg-1, n_all_poly);\n beq_con_a = zeros(n_seg-1, 1);\n % STEP 2.6: write expression of Aeq_con_a and beq_con_a\n for con_a_index = 1:n_seg-1\n index = 1 + 8 * (con_a_index - 1);\n T = ts(con_a_index);\n Aeq_con_a(con_a_index,index:index+7) = [42*T^5, 30*T^4, 20*T^3, 12*T^2, 6*T, 2, 0, 0];% the end of previous segment\n Aeq_con_a(con_a_index,index+8:index+8+7) = [0, 0, 0, 0, 0, -2, 0, 0];% the begin of next segment\n end\n % beq_con_a is a zero vector\n \n %#####################################################\n % jerk continuity constrain between each 2 segments\n Aeq_con_j = zeros(n_seg-1, n_all_poly);\n beq_con_j = zeros(n_seg-1, 1);\n % STEP 2.7: write expression of Aeq_con_j and beq_con_j\n for con_j_index = 1:n_seg-1\n index = 1 + 8 * (con_j_index - 1);\n T = ts(con_j_index);\n Aeq_con_j(con_j_index,index:index+7) = [210*T^4, 120*T^3, 60*T^2, 24*T, 6, 0, 0, 0];% the end of previous segment\n Aeq_con_j(con_j_index,index+8:index+8+7) = [0, 0, 0, 0, -6, 0, 0, 0];% the begin of next segment\n end\n % beq_con_j is a zero vector\n \n %#####################################################\n % combine all components to form Aeq and beq \n Aeq_con = [Aeq_con_p; Aeq_con_v; Aeq_con_a; Aeq_con_j];\n beq_con = [beq_con_p; beq_con_v; beq_con_a; beq_con_j];\n Aeq = [Aeq_start; Aeq_end; Aeq_wp; Aeq_con];\n beq = [beq_start; beq_end; beq_wp; beq_con];\nend", "meta": {"author": "Mesywang", "repo": "Motion-Planning-Algorithms", "sha": "e8211b1b5ce219978403b2bd3dbc7162c325a89b", "save_path": "github-repos/MATLAB/Mesywang-Motion-Planning-Algorithms", "path": "github-repos/MATLAB/Mesywang-Motion-Planning-Algorithms/Motion-Planning-Algorithms-e8211b1b5ce219978403b2bd3dbc7162c325a89b/MinimunSnapTrajectoryGenerator/getAbeq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7687722548376982}} {"text": "function f = p06_fun ( option, n, x )\n\n%*****************************************************************************80\n%\n%% P06_FUN evaluates the integrand for problem 6.\n%\n% Discussion:\n%\n% The exact value is (m-1)!! * sqrt ( pi ) / sqrt ( 2**m ).\n%\n% Integral ( -oo < x < +oo ) x^m exp (-x*x) dx\n%\n% The parameter M is set by calling P06_PARAM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer OPTION:\n% 0, integrand is f(x).\n% 1, integrand is exp(-x*x) * f(x);\n% 2, integrand is exp(-x*x/2) * f(x);\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real F(N), the function values.\n%\n x = x ( : );\n f = zeros ( n, 1 );\n\n m = 0;\n m = p06_param ( 'G', 'M', m );\n\n f(1:n) = x(1:n).^m;\n\n if ( option == 0 )\n f(1:n) = f(1:n) .* exp ( - x(1:n).^2 );\n elseif ( option == 1 )\n\n elseif ( option == 2 )\n f(1:n) = f(1:n) .* exp ( - 0.5 * x(1:n).^2 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_test_int/p06_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7686384431577005}} {"text": "%JTRAJ Compute a joint space trajectory between two configurations\n%\n% [Q,QD,QDD] = JTRAJ(Q0, QF, M) is a joint space trajectory Q (MxN) where the joint\n% coordinates vary from Q0 (1xN) to QF (1xN). A quintic (5th order) polynomial is used \n% with default zero boundary conditions for velocity and acceleration. \n% Time is assumed to vary from 0 to 1 in M steps. Joint velocity and \n% acceleration can be optionally returned as QD (MxN) and QDD (MxN) respectively.\n% The trajectory Q, QD and QDD are MxN matrices, with one row per time step,\n% and one column per joint.\n%\n% [Q,QD,QDD] = JTRAJ(Q0, QF, M, QD0, QDF) as above but also specifies initial \n% and final joint velocity for the trajectory.\n%\n% [Q,QD,QDD] = JTRAJ(Q0, QF, T) as above but the trajectory length is defined\n% by the length of the time vector T (Mx1).\n%\n% [Q,QD,QDD] = JTRAJ(Q0, QF, T, QD0, QDF) as above but specifies initial and \n% final joint velocity for the trajectory and a time vector.\n%\n% See also QPLOT, CTRAJ, SerialLink.jtraj.\n\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction [qt,qdt,qddt] = jtraj(q0, q1, tv, qd0, qd1)\n if length(tv) > 1\n tscal = max(tv);\n t = tv(:)/tscal;\n else\n tscal = 1;\n t = (0:(tv-1))'/(tv-1); % normalized time from 0 -> 1\n end\n\n q0 = q0(:);\n q1 = q1(:);\n\n if nargin == 3\n qd0 = zeros(size(q0));\n qd1 = qd0;\n elseif nargin == 5\n qd0 = qd0(:);\n qd1 = qd1(:);\n else\n error('incorrect number of arguments')\n end\n\n % compute the polynomial coefficients\n A = 6*(q1 - q0) - 3*(qd1+qd0)*tscal;\n B = -15*(q1 - q0) + (8*qd0 + 7*qd1)*tscal;\n C = 10*(q1 - q0) - (6*qd0 + 4*qd1)*tscal;\n E = qd0*tscal; % as the t vector has been normalized\n F = q0;\n\n tt = [t.^5 t.^4 t.^3 t.^2 t ones(size(t))];\n c = [A B C zeros(size(A)) E F]';\n \n qt = tt*c;\n\n % compute optional velocity\n if nargout >= 2\n c = [ zeros(size(A)) 5*A 4*B 3*C zeros(size(A)) E ]';\n qdt = tt*c/tscal;\n end\n\n % compute optional acceleration\n if nargout == 3\n c = [ zeros(size(A)) zeros(size(A)) 20*A 12*B 6*C zeros(size(A))]';\n qddt = tt*c/tscal^2;\n end\n", "meta": {"author": "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/jtraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7686384425001118}} {"text": "function Wrot = whiteningFromCovariance(CC)\n% takes as input the matrix CC of channel pairwise correlations\n% outputs a symmetric rotation matrix (also Nchan by Nchan) that rotates\n% the data onto uncorrelated, unit-norm axes\n\n[E, D] \t= svd(CC); % covariance eigendecomposition (same as svd for positive-definite matrix)\nD = diag(D); % take the non-zero values from the diagonal\neps \t= 1e-6;\nWrot \t= E * diag(1./(D + eps).^.5) * E'; % this is the symmetric whitening matrix (ZCA transform)\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/preProcess/whiteningFromCovariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545318852119, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.768459250253147}} {"text": "function J = ObjectiveFCN(u,x,Ts,N,Nu,xref,u0,p,Q,R,Ru)\n%% Cost function of nonlinear MPC for Lotka-Volterra system\n%\n% Inputs:\n% u: optimization variable, from time k to time k+N-1 \n% x: current state at time k\n% Ts: controller sample time\n% N: prediction horizon\n% Nu: control horizon [not implemented]\n% xref: state references, varying from time k+1 to k+N\n% u0: previous controller output at time k-1\n% p: Parameters for model\n% Q: State weights\n% R: Penalization/weights on rate of change in u, uk - uk-1 \n% Ru: Control input u penalization/weights\n%\n% Output:\n% J: objective function cost\n%\n\n%% Nonlinear MPC design parameters\n\n%% Cost Calculation\n% Set initial plant states, controller output and cost\nxk = x;\nuk = u(1);\nJ = 0;\n\n% Loop through each prediction step\nfor ct=1:N\n\n % Obtain plant state at next prediction step\n xk1 = rk4u(@F8Sys,xk,uk,Ts,1,[],p);\n \n % Accumulate state tracking cost from x(k+1) to x(k+N)\n J = J + (xk1-xref(:,ct))'*Q*(xk1-xref(:,ct));\n \n % Accumulate 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 \n % Update xk and uk for the next prediction step\n xk = xk1;\n if ct (L1+L2)\n disp('\\ninversekinematic_3dofplanar: unfeasible solution. The point cannot be reached'); \nend\n\n%compute geometric solution\nbeta = atan2(pm(2),pm(1)); \ngamma = real(acos((L1^2+R^2-L2^2)/(2*R*L1)));\ndelta = real(acos((L1^2+L2^2-R^2)/(2*L1*L2)));\n\n%arrange possible combinations for q(1) and q(2) \n%elbow down elbow up solutions\nq =[beta+gamma beta-gamma;\n delta-pi pi-delta];\n\n%in this case, phi = q(1) + q(2) + q(3) and\n%q(3) can be computed as q(3) = phi - q(1) - q(2) \n%corresponding to each of the previous solutions, a unique q(3) can be\n%computed for each case\nfor i=1:2 %iterate through columns \n q(3,i) = phi - q(1,i) - q(2,i); \nend\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/book/ikine_3gdl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7683621029514212}} {"text": "function Rx=correlmx(x,p,Rxtype);\n% Rx=correlmx(x,p,Rxtype) correlation matrix of a signal\n% \n% Rx : correlation matrix (p+1) x (p+1)\n% x : analyzed signal\n% p : last autocorrelation lag\n% Rxtype : computation algorithm (default : 'fbhermitian')\n% possible values : 'hermitian', 'fbhermitian', 'burg' or 'fbburg'\n%\n% example :\n%\n% N=100; sig=real(fmconst(N,0.1))+0.4*randn(N,1); \n% Rx=correlmx(sig,2,'burg'); [v,d] = eig(Rx), acos(-0.5*v(2,1)/v(1,1))/(2*pi)\n% Rx=correlmx(sig,2,'hermitian'); [v,d] = eig(Rx), acos(-0.5*v(2,1)/v(1,1))/(2*pi)\n\n% F. Auger, july 1998.\n\nif (nargin<2),\n error('At least two parameters required');\nelseif (nargin==2),\n Rxtype='fbhermitian';\nend;\n\n[L,xcol]=size(x);\nif xcol>1,\n error('x must be a column vector');\nelseif p>L,\n error('L must be greater than p');\nelseif p<1,\n error('p must be greater than 0');\nend;\n\nRxtype=upper(Rxtype);\nif strcmp(Rxtype,'HERMITIAN')|strcmp(Rxtype,'FBHERMITIAN'),\n vector=x(p+1-(0:p)); Rx=conj(vector) * vector.';\n for t=p+2:L,\n vector=x(t-(0:p)); Rx=Rx+conj(vector) * vector.';\n end;\n Rx=Rx/(L-p);\n\nelseif strcmp(Rxtype,'BURG')|strcmp(Rxtype,'FBBURG'),\n R0=sum(abs(x).^2)/L; % variance\n Rpos=zeros(1,p); Rneg=zeros(1,p);\n for n=1:p, \n Rpos(n)=sum(x(n+1:L).*conj(x(1:L-n)))/(L-n); \n Rneg(n)=sum(x(1:L-n).*conj(x(n+1:L)))/(L-n);\n end;\n Rx=toeplitz([R0 Rpos],[R0 Rneg]);\nelse error(['unknown algorithm name' Rxtype]); \nend;\n\nif strcmp(Rxtype(1:2),'FB'),\n Rx=0.5*(Rx+Rx');\nend;\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/correlmx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7683610187917329}} {"text": "function [ o, c, e ] = lpp_to_polynomial ( m, l, o_max )\n\n%*****************************************************************************80\n%\n%% LPP_TO_POLYNOMIAL writes a Legendre Product Polynomial as a polynomial.\n%\n% Discussion:\n%\n% For example, if \n% M = 3,\n% L = ( 1, 0, 2 ),\n% then\n% L(1,0,2)(X,Y,Z) \n% = L(1)(X) * L(0)(Y) * L(2)(Z)\n% = X * 1 * ( 3Z^2-1)/2\n% = - 1/2 X + (3/2) X Z^2\n% so\n% O = 2 (2 nonzero terms)\n% C = -0.5\n% 1.5\n% E = 4 <-- index in 3-space of exponent (1,0,0)\n% 15 <-- index in 3-space of exponent (1,0,2)\n%\n% The output value of O is no greater than\n% O_MAX = product ( 1 <= I <= M ) (L(I)+2)/2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer L(M), the index of each Legendre product polynomial factor.\n% 0 <= L(*).\n%\n% Input, integer O_MAX, an upper limit on the size of the output arrays.\n% O_MAX = product ( 1 <= I <= M ) (L(I)+2)/2.\n%\n% Output, integer O, the \"order\" of the polynomial product.\n%\n% Output, real C(O), the coefficients of the polynomial product.\n%\n% Output, integer E(O), the indices of the exponents of the \n% polynomial product.\n%\n o1 = 1;\n c1 = 1.0;\n e1 = 1;\n%\n% Implicate one factor at a time.\n%\n for i = 1 : m\n\n [ o2, c2, f2 ] = lp_coefficients ( l(i) );\n\n o = 0;\n\n for j2 = 1 : o2\n for j1 = 1 : o1\n o = o + 1;\n c(o) = c1(j1) * c2(j2);\n \n if ( 1 < i )\n p = mono_unrank_grlex ( i - 1, e1(j1) );\n end\n p(i) = f2(j2);\n e(o) = mono_rank_grlex ( i, p );\n\n end\n end\n\n [ c, e ] = polynomial_sort ( o, c, e );\n [ o, c, e ] = polynomial_compress ( o, c, e );\n\n o1 = o;\n c1 = c;\n e1 = 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/lagrange_nd/lpp_to_polynomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7683610096354233}} {"text": "function fem1d ( )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for FEM1D.\n%\n% Discussion:\n%\n% FEM1D solves a one dimensional ODE using the finite element method.\n%\n% The differential equation has the form:\n%\n% -d/dx ( p(x) du/dx ) + q(x) * u = f(x)\n%\n% The finite-element method uses piecewise linear basis functions.\n%\n% Here U is an unknown scalar function of X defined on the\n% interval [XL,XR], and P, Q and F are given functions of X.\n%\n% The values of U or U' at XL and XR are also specified.\n%\n% The interval [XL,XR] is \"meshed\" with NSUB+1 points,\n%\n% XN(0) = XL, XN(1)=XL+H, XN(2)=XL+2*H, ..., XN(NSUB)=XR.\n%\n% This creates NSUB subintervals, with interval number 1\n% having endpoints XN(0) and XN(1), and so on up to interval\n% NSUB, which has endpoints XN(NSUB-1) and XN(NSUB).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 October 2008\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% real F(NU).\n% ASSEMBLE stores into F the right hand side of the linear\n% equations.\n% SOLVE replaces those values of F by the solution of the\n% linear equations.\n%\n% real H(N), the length of the subintervals. \n%\n% integer IBC. declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% integer INDX(1:N+1).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% integer NL, the number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% integer NQUAD.\n% The number of quadrature points used in a subinterval.\n% This code uses NQUAD = 1.\n%\n% integer NSUB, the number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% integer NU, the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% real XL, the left endpoint of the interval over which the\n% differential equation is being solved.\n%\n% real XN(1:N+1).\n% XN(I) is the location of the I-th node. XN(1) is XL,\n% and XN(N+1) is XR.\n%\n% real XQUAD(N)\n% XQUAD(I) is the location of the single quadrature point\n% in interval I.\n%\n% real XR, the right endpoint of the interval over which the\n% differential equation is being solved.\n%\n n = 100;\n nl = 2;\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the two-point boundary value problem:\\n' );\n fprintf ( 1, ' -d/dx (p(x) du/dx) + q(x)*u = f(x)\\n' );\n fprintf ( 1, ' on an interval [xl,xr], with the values of\\n' );\n fprintf ( 1, ' u or u'' specified at xl and xr.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The interval is broken into %d subintervals.\\n', n );\n fprintf ( 1, ' The number of basis functions per element is %d\\n', nl );\n%\n% Initialize variables that define the problem.\n%\n [ ibc, nquad, ul, ur, xl, xr ] = init ( );\n%\n% Compute the quantities that describe the geometry of the problem.\n%\n [ h, indx, node, nu, xn, xquad ] = geometry ( ibc, nl, n, xl, xr );\n%\n% Assemble the matrix.\n%\n [ adiag, aleft, arite, f ] = assemble ( h, indx, nl, node, ...\n nu, nquad, n, ul, ur, xn, xquad );\n%\n% Print out the linear system.\n%\n system_print ( adiag, aleft, arite, f, nu );\n%\n% Solve the linear system.\n%\n u = solve ( adiag, aleft, arite, f, nu );\n%\n% Print the current solution.\n%\n output ( u, ibc, indx, n, nu, ul, ur, xn );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ adiag, aleft, arite, f ] = assemble ( h, indx, nl, ...\n node, nu, nquad, n, ul, ur, xn, xquad )\n\n%*****************************************************************************80\n%\n%% ASSEMBLE assembles the matrix and right hand side of the linear system.\n%\n% Discussion:\n%\n% Note that a 1 point quadrature rule, which is sometimes used to\n% assemble the matrix and right hand side, is just barely accurate\n% enough for simple problems. If you want better results, you\n% should use a quadrature rule that is more accurate.\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% Parameters:\n%\n% Input, real H(N), the length of the subintervals. \n%\n% Input, integer INDX(1:N+1).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Input, integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% Input, integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% Input, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Input, integer NQUAD, the number of quadrature points in a subinterval.\n% This code uses NQUAD = 1.\n%\n% Input, integer N, the number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real XN(1:N+1), the location of the I-th node. XN(1) is XL,\n% and XN(N+1) is XR.\n%\n% Input, real XQUAD(N), the location of the single quadrature point\n% in interval I.\n%\n% Output, real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% Output, real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% Output, real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% Output, real F(NU), the right hand side of the linear\n% equations.\n%\n f(1:nu) = 0.0;\n adiag(1:nu) = 0.0;\n aleft(1:nu) = 0.0;\n arite(1:nu) = 0.0;\n%\n% For element IE...\n%\n for ie = 1 : n\n\n he = h(ie);\n xleft = xn(node(1,ie)+1);\n xrite = xn(node(2,ie)+1);\n%\n% For quadrature point IQ...\n%\n for iq = 1 : nquad\n\n xqe = xquad(ie);\n%\n% For basis function IL...\n%\n for il = 1 : nl\n\n ig = node(il,ie);\n iu = indx(ig+1);\n\n if ( 0 < iu )\n\n [ phii, phiix ] = phi ( il, xqe, xleft, xrite );\n\n f(iu) = f(iu) + he * ff ( xqe ) * phii;\n%\n% Handle boundary conditions.\n%\n if ( ig == 0 )\n\n x = xn(1);\n f(iu) = f(iu) - pp ( x ) * ul;\n\n elseif ( ig == n )\n\n x = xn(n+1);\n f(iu) = f(iu) + pp ( x ) * ur;\n\n end\n%\n% For basis function JL...\n%\n for jl = 1 : nl\n\n jg = node(jl,ie);\n ju = indx(jg+1);\n\n [ phij, phijx ] = phi ( jl, xqe, xleft, xrite );\n\n aij = he * ( pp ( xqe ) * phiix * phijx ...\n + qq ( xqe ) * phii * phij );\n\n if ( ju <= 0 )\n\n if ( jg == 0 )\n f(iu) = f(iu) - aij * ul;\n elseif ( jg == n )\n f(iu) = f(iu) - aij * ur;\n end\n\n elseif ( iu == ju )\n adiag(iu) = adiag(iu) + aij;\n elseif ( ju < iu )\n aleft(iu) = aleft(iu) + aij;\n else\n arite(iu) = arite(iu) + aij;\n end\n\n end\n\n end\n\n end\n\n end\n\n end\n\n return\nend\nfunction value = ff ( x )\n\n%*****************************************************************************80\n%\n%% FF returns the right hand side of the differential equation.\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% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n value = 0.0;\n\n return\nend\nfunction [ h, indx, node, nu, xn, xquad ] = geometry ( ibc, nl, nsub, ...\n xl, xr )\n\n%*****************************************************************************80\n%\n%% GEOMETRY sets up the geometry for the interval [XL,XR].\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% Parameters:\n%\n% Input, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Input, integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% Input, integer NSUB.\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, real XL.\n% XL is the left endpoint of the interval over which the\n% differential equation is being solved.\n%\n% Input, real XR.\n% XR is the right endpoint of the interval over which the\n% differential equation is being solved.\n%\n% Output, real H(NSUB), the length of the subintervals. \n%\n% Output, integer INDX(1:NSUB+1).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Output, integer NODE(NL,NSUB).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% Output, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be NSUB-1,\n% NSUB, or NSUB+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Output, real XN(1:NSUB+1).\n% XN(I) is the location of the I-th node. XN(1) is XL,\n% and XN(N+1) is XR.\n%\n% Output, real XQUAD(NSUB)\n% XQUAD(I) is the location of the single quadrature point\n% in interval I.\n%\n\n%\n% Set the value of XN, the locations of the nodes.\n%\n xn = zeros ( nsub + 1, 1 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Node Location\\n' );\n fprintf ( 1, '\\n' );\n for i = 0 : nsub\n xn(i+1) = ( ( nsub - i ) * xl ...\n + ( i ) * xr ) ...\n / ( nsub );\n end\n r8vec_print_some ( nsub + 1, xn, 1, 10, ' First 10 nodes:' );\n%\n% Set the lengths of each subinterval.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Subint Length\\n' );\n fprintf ( 1, '\\n' );\n h = zeros ( nsub, 1 );\n for i = 1 : nsub\n h(i) = xn(i+1) - xn(i);\n end\n r8vec_print_some ( nsub, h, 1, 10, ' First 10 interval widths:' );\n%\n% Set the quadrature points, each of which is the midpoint of its subinterval.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Subint Quadrature point\\n' );\n fprintf ( 1, '\\n' );\n xquad = zeros ( nsub );\n for i = 1 : nsub\n xquad(i) = 0.5 * ( xn(i) + xn(i+1) );\n end\n r8vec_print_some ( nsub, xquad, 1, 10, ' First 10 quadrature points:' );\n%\n% Set the value of NODE, which records, for each interval,\n% the node numbers at the left and right.\n%\n node = zeros ( 2, nsub );\n for i = 1 : nsub\n node(1,i) = i - 1;\n node(2,i) = i;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' First 10 pairs of nodes defining intervals:\\n' );\n fprintf ( 1, 'Subint Left Node Right Node\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : min ( nsub, 10 )\n fprintf ( 1, ' %6d %6d %6d\\n', i, node(1,i), node(2,i) );\n end\n%\n% Starting with node 0, see if an unknown is associated with\n% the node. If so, give it an index.\n%\n nu = 0;\n%\n% Handle first node.\n%\n i = 0;\n if ( ibc == 1 || ibc == 3 )\n indx(i+1) = -1;\n else\n nu = nu + 1;\n indx(i+1) = nu;\n end\n%\n% Handle nodes 1 through nsub-1\n%\n for i = 1 : nsub-1\n nu = nu + 1;\n indx(i+1) = nu;\n end\n%\n% Handle the last node.\n%\n i = nsub;\n if ( ibc == 2 || ibc == 3 )\n indx(i+1) = -1;\n else\n nu = nu + 1;\n indx(i+1) = nu;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' First 10 unknown indices\\n' );\n fprintf ( 1, ' Node Unknown\\n' );\n fprintf ( 1, '\\n' );\n for i = 0 : min ( nsub, 9 )\n fprintf ( 1, ' %6d %6d\\n', i, indx(i+1) );\n end\n\n return\nend\nfunction [ ibc, nquad, ul, ur, xl, xr ] = init ( )\n\n%*****************************************************************************80\n%\n%% INIT initializes variables that define the problem.\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% Parameters:\n%\n% Output, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Output, integer NQUAD.\n% The number of quadrature points used in a subinterval.\n% This code uses NQUAD = 1.\n%\n% Output, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Output, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Output, real XL.\n% XL is the left endpoint of the interval over which the\n% differential equation is being solved.\n%\n% Output, real XR.\n% XR is the right endpoint of the interval over which the\n% differential equation is being solved.\n%\n ibc = 1;\n nquad = 1;\n ul = 0.0;\n ur = 1.0;\n xl = 0.0;\n xr = 1.0;\n%\n% Print out the values that have been set.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The equation is to be solved for\\n' );\n fprintf ( 1, 'X greater than XL = %f\\n', xl );\n fprintf ( 1, ' and less than XR = %f\\n', xr );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The boundary conditions are:\\n' );\n fprintf ( 1, '\\n' );\n\n if ( ibc == 1 || ibc == 3 )\n fprintf ( 1, ' At X = XL, U = %f\\n', ul );\n else\n fprintf ( 1, ' At X = XL, U'' = %f\\n', ul );\n end\n\n if ( ibc == 2 || ibc == 3 )\n fprintf ( 1, ' At X = XR, U = %f\\n', ur );\n else\n fprintf ( 1, ' At X = XR, U'' = %f\\n', ur );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Number of quadrature points per element is %d\\n', nquad );\n \n return\nend\nfunction output ( f, ibc, indx, nsub, nu, ul, ur, xn )\n\n%*****************************************************************************80\n%\n%% OUTPUT prints out the computed solution at the nodes.\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% Parameters:\n%\n% Input, real F(NU), the solution of the linear equations.\n%\n% Input, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Input, integer INDX(1:N+1).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% integer NSUB.\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real XN(1:N+1).\n% XN(I) is the location of the I-th node. XN(1) is XL,\n% and XN(N+1) is XR.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'First 10 entries of computed solution:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Node X(I) U(I)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : min ( nsub, 9 )\n\n if ( i == 0 )\n if ( ibc == 1 || ibc == 3 )\n u = ul;\n else\n u = f(indx(i+1));\n end\n elseif ( i == nsub )\n if ( ibc == 2 || ibc == 3 )\n u = ur;\n else\n u = f(indx(i+1));\n end\n else\n u = f(indx(i+1));\n end\n\n fprintf ( 1, ' %6d %12f %12f\\n', i, xn(i+1), u );\n\n end\n\n return\nend\nfunction [ phii, phiix ] = phi ( il, x, xleft, xrite )\n\n%*****************************************************************************80\n%\n%% PHI evaluates a linear basis function and its derivative.\n%\n% Discussion:\n%\n% In any interval, there are just two basis functions. The first\n% basis function is a line which is 1 at the left endpoint\n% and 0 at the right. The second basis function is 0 at\n% the left endpoint and 1 at the right.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer IL, the index of the basis function.\n% 1, the function which is 1 at XLEFT and 0 at XRITE.\n% 2, the function which is 0 at XLEFT and 1 at XRITE.\n%\n% Input, real X, the evaluation point.\n%\n% Input, real XLEFT, XRITE, the left and right\n% endpoints of the interval.\n%\n% Output, real PHII, PHIIX, the value of the\n% basis function and its derivative at X.\n%\n if ( xleft <= x && x <= xrite )\n\n if ( il == 1 )\n phii = ( xrite - x ) / ( xrite - xleft );\n phiix = -1.0 / ( xrite - xleft );\n else \n phii = ( x - xleft ) / ( xrite - xleft );\n phiix = 1.0 / ( xrite - xleft );\n end\n%\n% If X is outside of the interval, then the basis function\n% is always zero.\n%\n else\n\n phii = 0.0;\n phiix = 0.0;\n\n end\n\n return\nend\nfunction value = pp ( x )\n\n%*****************************************************************************80\n%\n%% PP returns the value of the coefficient function P(X).\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% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of P(X).\n%\n value = 1.0;\n\n return\nend\nfunction value = qq ( x )\n\n%*****************************************************************************80\n%\n%% QQ returns the value of the coefficient function Q(X).\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% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of Q(X).\n%\n value = 0.0;\n\n return\nend\nfunction r8vec_print_some ( n, a, i_lo, i_hi, title )\n\n%*****************************************************************************80\n%\n%% R8VEC_PRINT_SOME prints \"some\" of an R8VEC.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8 values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 September 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the vector.\n%\n% Input, real A(N), the vector to be printed.\n%\n% Input, integer MAX_PRINT, the maximum number of lines to print.\n%\n% Input, string TITLE, a title.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n fprintf ( 1, '\\n' );\n\n for i = max ( 1, i_lo ) : min ( n, i_hi )\n fprintf ( 1, ' %8d: %12f\\n', i, a(i) );\n end\n\n return\nend\nfunction u = solve ( adiag, aleft, arite, f, nu )\n\n%*****************************************************************************80\n%\n%% SOLVE solves a tridiagonal matrix system of the form A*x = b.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real ADIAG(NU), ALEFT(NU), ARITE(NU).\n% the diagonal, left and right entries of the equations.\n% Note that for the first equation, there is no ALEFT\n% coefficient, and for the last, there is no ARITE.\n% So there is no need to store a value in ALEFT(1), nor\n% in ARITE(NU).\n%\n% Input, real F(NU), the right hand side of the linear\n% system to be solved.\n%\n% Input, integer NU.\n% NU is the number of equations to be solved.\n%\n% Output, real U(NU), the solution of the linear system.\n%\n arite(1) = arite(1) / adiag(1);\n for i = 2 : nu-1\n adiag(i) = adiag(i) - aleft(i) * arite(i-1);\n arite(i) = arite(i) / adiag(i);\n end\n adiag(nu) = adiag(nu) - aleft(nu) * arite(nu-1);\n\n u = zeros ( nu, 1 );\n \n u(1) = f(1) / adiag(1);\n for i = 2 : nu\n u(i) = ( f(i) - aleft(i) * u(i-1) ) / adiag(i);\n end\n\n for i = nu-1 : -1 : 1\n u(i) = u(i) - arite(i) * u(i+1);\n end\n\n return\nend\nfunction system_print ( adiag, aleft, arite, f, nu )\n\n%*****************************************************************************80\n%\n%% SYSTEM_PRINT prints out the tridiagonal linear system to be solved.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ADIAG(NU), ALEFT(NU), ARITE(NU),\n% the diagonal, left and right entries of the equations.\n%\n% Input, real F(NU), the right hand side of the linear system.\n%\n% Input, integer NU, the number of equations to be solved.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'First 10 rows of tridiagonal linear system:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Equation ALEFT ADIAG ARITE RHS\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : min ( nu, 10 )\n\n fprintf ( 1, '%3d', i );\n\n if ( i == 1 )\n fprintf ( 1, ' ' );\n else\n fprintf ( 1, ' %12f', aleft(i) );\n end\n\n fprintf ( 1, ' %12f', adiag(i) );\n\n if ( i < nu )\n fprintf ( 1, ' %12f', arite(i) );\n else\n fprintf ( 1, ' ' );\n end\n\n fprintf ( 1, ' %12f\\n', f(i) );\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/fem1d/fem1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7683292961920345}} {"text": "function [edges,didSucceed]=graph4VertexDeg(d)\n%%GRAPH4VERTEXDEG Given a list of the degrees of vertices in a\n% non-directional graph, get a set of edges representing a graph\n% that satisfies the degree profile, or indicate if no such graph\n% can exist. Note that a set of edges for a degree profile is not\n% unique. This just returns one set.\n%\n%INPUTS: d An nX1 or 1Xn vector of the degrees of the n vertices. These are\n% integer values >=0. They represent the number of edges touching\n% the nodes.\n%\n%OUTPUTS: edges A 2XnumEdge set of edges that satisfies the degree profile.\n% An empty matrix is returned if all edges have zero degree\n% or if no set ofvedges exists that can result in the given\n% degree profile. An edge [i;j] goes between vertex i and\n% vertex j and adds to the degree count for both vertices.\n% didSucceed This is true if an edges exists that can satisfy d.\n% Otherwise, this is false and edges is an empty matrix.\n%\n%This function implements Algorithm H in Chapter 7 of [1].\n%\n%EXAMPLE:\n% [edges,didSucceed]=graph4VertexDeg([2;1;6;3;2;1;1])\n%The algorithm in the example will succeed and the edge set is\n%edges=[7,6,2,5,5,1,1,4;\n% 3,3,3,4,3,4,3,3];\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[d,idx]=sort([d(:);0],'descend');\n\n%Allocate space\nmaxEdges=ceil(sum(d)/2);\nedges=zeros(2,maxEdges);\nc=zeros(d(1),1);\n\nnumEdges=0;\n\n%Step H1\nk=d(1);\nj=0;\nwhile(k>0)\n j=j+1;\n while(k>d(j+1))\n c(k)=j;\n k=k-1;\n end\nend\n%If all of the d's are zero.\nif(j==0)\n edges=[];\n didSucceed=true;\n return;\nend\n\nwhile(1)\n %Step H2, find n.\n n=c(1);\n if(n==0)\n %Shrink to fit and restore the original indexation.\n edges=idx(edges(:,1:numEdges));\n %Restore the original indexation.\n didSucceed=true;\n return;\n elseif(d(1)>=n)\n edges=[];\n didSucceed=false;\n return;\n end\n\n %Step H3\n i=1;\n t=d(1);\n r=c(t);\n j=d(n);\n \n %Step H4, generate a new edge.\n while(1)\n c(j)=c(j)-1;\n m=c(t);\n numEdges=numEdges+1;\n edges(:,numEdges)=[n;m];\n d(m)=d(m)-1;\n c(t)=m-1;\n j=j-1;\n if(j==0)\n break;\n elseif(m==i)\n i=r+1;\n t=d(i);\n r=c(t);\n end\n end\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Graph_Algorithms/graph4VertexDeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7683292914362878}} {"text": "function mean = half_normal_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% HALF_NORMAL_MEAN returns the mean of the Half Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < B.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a + b * sqrt ( 2.0 / pi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/half_normal_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7682734129739911}} {"text": "function [d2f, err] = tapas_riddersdiff2(f, x, varargin)\n% Differentiates the function f *twice* at point x according to Ridders' method:\n%\n% Ridders, CJF. (1982). Accurate computation of F'(x) and F'(x) F''(x). Advances in Engineering\n% Software, 4(2), 75-6.\n%\n% INPUT:\n% f Function handle of a scalar real function of one real variable\n% x Point at which to differentiate f\n%\n% OUTPUT:\n% d2f Second derivative of f at x\n% err Error estimate\n%\n% OPTIONS:\n% Optionally, the third argument of the function can be a structure containing further\n% settings for Ridder's method.\n%\n% varargin{1}.init_h Initial finite difference (default: 1)\n% varargin{1}.div Divisor used to reduce h on each step (default: 1.2)\n% varargin{1}.min_steps Minimum number of steps in h (default: 3)\n% varargin{1}.max_steps Maximum number of steps in h (default: 100)\n% varargin{1}.tf Terminate if last step worse than preceding by a factor of tf\n% (default: 2)\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is released under the terms of the GNU General Public Licence (GPL), version 3. You can\n% redistribute it and/or modify it under the terms of the GPL (either version 3 or, at your option,\n% any later version). For further details, see the file COPYING or .\n \n % Defaults\n init_h = 1;\n div = 1.2;\n min_steps = 3;\n max_steps = 100;\n tf = 2;\n d2f = NaN;\n err = realmax;\n \n % Overrides\n if nargin > 2\n options = varargin{1};\n\n if isfield(options,'init_h')\n init_h = options.init_h;\n end\n \n if isfield(options,'div')\n div = options.div;\n end\n \n if isfield(options,'min_steps')\n min_steps = options.min_steps;\n end\n \n if isfield(options,'max_steps')\n max_steps = options.max_steps;\n end\n \n if isfield(options,'tf')\n tf = options.tf;\n end\n end\n \n % Initialize matrix of polynomial interpolation values\n P = NaN(max_steps);\n \n % Initialize finite difference step\n h = init_h;\n \n % Approximate 2nd derivative at initial step\n P(1,1) = (f(x+h)-2*f(x)+f(x-h))/h^2;\n \n % Loop through rows of P (i.e., steps of h)\n for i = 2:max_steps\n \n % New step size\n h = h/div;\n \n % Approximate 2nd derivative at this step\n P(i,1) = (f(x+h)-2*f(x)+f(x-h))/h^2;\n \n % Use square of div for extrapolation because errors increase\n % quadratically with h (here, of course, they decrease quadratically\n % because we're reducing h...)\n divsq = div^2;\n t = divsq;\n \n % Fill the current row using Richardson extrapolation\n for j = 2:i\n \n % Richardson\n P(i,j) = (t*P(i,j-1)-P(i-1,j-1))/(t-1);\n \n % Increment extrapolation factor\n t = t*divsq;\n \n % Error on this trial is defined as the maximum absolute difference\n % to the extrapolation parents\n currerr = max(abs(P(i,j)-P(i,j-1)),abs(P(i,j)-P(i-1,j-1)));\n \n if currerr < err\n err = currerr;\n d2f = P(i,j);\n end\n end\n\n % Stop if errors start increasing (to be expected for very small\n % values of h)\n if i > min_steps && abs(P(i,i)-P(i-1,i-1)) > tf*err\n return\n end\n end\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_riddersdiff2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7682601435152471}} {"text": "function [t,X] = smdplot(t,X) \n% See Article 2.6\n% [t,X]=smdplot(t,X)\n% This function plots the response and animates the\n% motion of a damped linear harmonic oscillator\n% characterized by the differential equation\n% m*x''+c*x'+k*x=f1*cos(w*t)+f2*sin(w*t)\n% with initial conditions x(0)=x0, x'(0)=v0.\n% The animation depicts forced motion of a block\n% attached to a wall by a spring. The block\n% slides on a horizontal plane which provides \n% viscous damping.\n\n% Default data case used when no input arguments\n% are given\nif nargin==0\n m=1; c=.3; k=1; f1=1.5; f2=0; w=2; x0=0; v0=2; \n %tmax=30; nt=250; t=linspace(0,tmax,nt);\n tmax=25; nt=200; t=linspace(0,tmax,nt);\n X=smdsolve(m,c,k,f1,f2,w,x0,v0,t);\nend\n\n% Plot the displacement versus time \nplot(t,X), xlabel('time'), ylabel('displacement')\ntitle(...\n'FORCED RESPONSE OF A DAMPED HARMONIC OSCILLATOR')\ngrid on, shg, pause(3) \n\n% Add a block and a spring to the displacement\nxmx=max(abs(X)); X=X/1.1/xmx;\nxb=[0,0,1,1,0,0]/2; yb=[0,-1,-1,1,1,0]/2;\n\n% Make an arrow tip \nd=.08; h=.05;\nxtip=[0,-d,-d,0]; ytip=[0,0,0,h,-h,0];\n\n% Add a spring and a block to the response\n[xs,ys]=spring; nm=length(X); ns=length(xs);\nnb=length(xb); x=zeros(nm,ns+nb);y=[ys,yb];\nfor j=1:nm, x(j,:)=[-1+(1+X(j))*xs,X(j)+xb];end \nr=[min(x(:)),max(x(:))+1,-2,2];\nrx=r([1 1 2]); ry=[.5,-.5,-.5]; close;\n\n% Plot the motion\nfor j=1:nm\n % Compute and scale the applied force\n f=f1*cos(w*t(j))+f2*sin(w*t(j));\n f=.3*f; fa=abs(f); sf=sign(f);\n xj=x(j,:); xmaxj=max(xj);\n if sf>0\n xforc=xmaxj+[0,fa,fa+xtip];\n else\n xforc=xmaxj+[fa,0,-xtip];\n end\n \n % Plot the spring, block, and force\n plot(xj,y,rx,ry,'k',xforc,ytip,'r')\n title('FORCED MOTION WITH DAMPING')\n axis(r), axis('off'), drawnow\n figure(gcf), pause(.05) \nend \n \n%====================================\n\nfunction [x,y] = spring(len,ht)\n% This function generates a set of points\n% defining a spring\n\nif nargin==0, len=1; ht=.125; end\nx=[0,.5,linspace(1,11,10),11.5,12];\ny=[ones(1,5);-ones(1,5)];\ny=[0;0;y(:);0;0]'; y=ht/2/max(y)*y;\nx=len/max(x)*x;\n \n%====================================\n\nfunction [x,v]=smdsolve(m,c,k,f1,f2,w,x0,v0,t)\n% [x,v]=smdsolve(m,c,k,f1,f2,w,x0,v0,t)\n% This function solves the differential equation\n% m*x''(t)+c*x'(t)+k*x(t)=f1*cos(w*t)+f2*sin(w*t)\n% with x(0)=x0 and x'(0)=v0\n%\n% m,c,k - mass, damping and stiffness coefficients\n% f1,f2 - magnitudes of cosine and sine terms in\n% the forcing function\n% w - frequency of the forcing function\n% t - vector of times to evaluate the solution\n% x,v - computed position and velocity vectors\n\nccrit=2*sqrt(m*k); wn=sqrt(k/m);\n\n% If the system is undamped and resonance will \n% occur, add a little damping\nif c==0 & w==wn; c=ccrit/1e6; end;\n\n% If damping is critical, modify the damping\n% very slightly to avoid repeated roots\nzeta=c/ccrit; if zeta==1, zeta=zeta+1e-6; end \n\n% Forced response solution\na=(f1-i*f2)/(k-m*w^2+i*c*w);\nX0=real(a); V0=real(i*w*a);\nX=real(a*exp(i*w*t)); V=real(i*w*a*exp(i*w*t));\n\n% Homogeneous solution\nr=sqrt(zeta^2-1); s1=wn*(-zeta+r); s2=wn*(-zeta-r);\np=[1,1;s1,s2]\\[x0-X0;v0-V0];\n\n% Total solution satisfying the initial conditions \nx=X+real(p(1)*exp(s1*t)+p(2)*exp(s2*t));\nv=V+real(p(1)*s1*exp(s1*t)+p(2)*s2*exp(s2*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/6558-dynamics-of-some-classical-system-models/dynamics/smdplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7682601417275744}} {"text": "function c = t_project_coefficients ( n, f )\n\n%*****************************************************************************80\n%\n%% T_PROJECT_COEFFICIENTS: function projected onto T(0:n,x).\n%\n% Discussion:\n%\n% It is assumed that the interval of definition is -1 <= x <= +1.\n%\n% Over this interval, f(x) will be well approximated by\n%\n% f(x) approx sum ( 0 <= i <= n ) c(i) * T(i,x)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the highest order polynomial to compute.\n%\n% Input, function handle F, of the form\n% function v = f ( x )\n%\n% Output, real C(N+1,1), the projection coefficients of f(x) onto\n% T(0,x) through T(n,x).\n%\n for k = 1 : n + 1\n y = cos ( pi * ( k - 0.5 ) / ( n + 1 ) );\n d(k) = f ( y );\n end\n\n fac = 2.0 / ( n + 1 );\n for j = 1 : ( n + 1 )\n sum = 0.0;\n for k = 1 : ( n + 1 )\n sum = sum + d(k) * cos ( ( pi * ( j - 1 ) ) * ( ( k - 0.5 ) / ( n + 1 ) ) );\n end\n c(j) = fac * sum;\n end\n\n c(1) = c(1) / 2.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/chebyshev_polynomial/t_project_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7682501666298233}} {"text": "function [ok,tp,tq] = linenear(pa,pb,pc,pd)\n%LINENEAR calc. the nearest points on line segments embedded \n%in d-dimensions. Line paramters are bounded on [-1,+1].\n\n%-----------------------------------------------------------\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 10/10/2017\n%-----------------------------------------------------------\n\n m1 = (pa+pb) * +.5 ;\n D1 = (pb-pa) * +.5 ;\n \n m2 = (pc+pd) * +.5 ;\n D2 = (pd-pc) * +.5 ;\n\n r1 = sum(m2.*D1,2) ...\n - sum(m1.*D1,2) ;\n r2 = sum(m1.*D2,2) ...\n - sum(m2.*D2,2) ;\n\n A1 = sum(D1.*D1,2) ;\n A2 =-sum(D1.*D2,2) ;\n A3 =-sum(D1.*D2,2) ;\n A4 = sum(D2.*D2,2) ;\n\n dd = A1.*A4 - A2.*A3 ;\n\n tp = A4.*r1 - A2.*r2 ;\n tq =-A3.*r1 + A1.*r2 ;\n\n rt = max(abs([A1,A2,A3,A4]),[],2);\n rt = rt * eps ^ .8 ;\n \n ok = abs(dd) > +rt ;\n \n tp(~ok) = +0. ; \n tq(~ok) = +0. ;\n \n tp(ok) = tp(ok) ./ dd(ok) ;\n tq(ok) = tq(ok) ./ dd(ok) ;\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/linenear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7682495492575712}} {"text": "% generating channels with fliter method and spectrum method\n% evaluate autocorrelation functions\n%%\nclear all\nclc\nclose all\n\n% doppler\nfDTs=0.01;\nfD=100; \n% sampling time\nTs=fDTs/fD;\n\nNs=1E5;\n\n%% spectrum method\nh1=flat_spec(Ns,fD,fDTs);\n\n% autocorrelation \nAcn=xcorr(h1,'biased');\nl=length(Acn);\n% truncate\nw=ceil(4/fDTs);\nTAc=Acn(ceil(l/2)-w:ceil(l/2)+w);\n\nlt=length(TAc);\nt=-Ts*floor(lt/2):Ts:Ts*floor(lt/2);\n% theoritical value of autocorrelation\nAc_th=besselj(0,2*pi*fD*t);\n\nfigure;\nplot(t,real(Ac_th),t,real(TAc),'r');\ntitle('Autocorrelation');\nxlabel('time');\nlegend('theory','spec. method');\ngrid on\n\n%% filter method \nh1=flat_filter(Ns,fD,fDTs);\n\nAcn=xcorr(h1,'biased');\nl=length(Acn);\nw=ceil(4/fDTs);\nTAc=Acn(ceil(l/2)-w:ceil(l/2)+w);\n\nl=length(TAc);\nt=-Ts*floor(l/2):Ts:Ts*floor(l/2);\n% theory\nAc_th=besselj(0,2*pi*fD*t);\n\nfigure;\nplot(t,real(Ac_th),t,real(TAc),'r');\ntitle('Autocorrelation');\nxlabel('time');\nlegend('theory','filter method');\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/36620-flat-fading-channel/CH/channelEvaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7682495473204075}} {"text": "function [ pts ] = genRansacTestPoints( ptNum,outlrRatio,inlrStd,inlrCoef )\n%GENRANSACTESTPOINTS Generate the points used by RANSAC function\n% PTS = GENRANSACTESTPOINTS(PTNUM,OUTLRRATIO,INLRSTD,INLRCOEF) PTS is\n% 2*PTNUM, including PTNUM points, among which ROUND(OUTLRRATIO*PTNUM)\n% are outliers, others are inliers. \n%\t\tThe inliers are around the line: y = INLRCOEF(1)*x + INLRCOEF(2),\n% INLRSTD is the standard deviation of, the dist between inliers and the\n%\tline. The outliers \n\noutlrNum = round(outlrRatio*ptNum);\ninlrNum = ptNum-outlrNum;\n\nk = inlrCoef(1);\nb = inlrCoef(2);\nX = (rand(1,inlrNum)-.5)*ptNum; % X is in [-ptNum/2,ptNum/2]\nY = k*X+b;\n\n% add noise for inliers\ndist = randn(1,inlrNum)*inlrStd;\ntheta = atan(k);\nX = X+dist*(-sin(theta));\nY = Y+dist*cos(theta);\ninlrs = [X;Y];\n\noutlrs = (rand(2,outlrNum)-.5)*ptNum;\n% outlrs = (rand(2,outlrNum)-[ones(1,outlrNum)*.5;ones(1,outlrNum)*.1])*ptNum;\npts = [inlrs,outlrs];\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/30809-ransac-algorithm-with-example-of-finding-homography/genRansacTestPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7682495422807352}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\nsig = sigmoid(X * all_theta');\n[maxSig, maxSig_2] = max(sig');\np = maxSig_2';\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "rieder91", "repo": "MachineLearning", "sha": "f6708f216326cb5c9e9e5c3afc912060bfa10486", "save_path": "github-repos/MATLAB/rieder91-MachineLearning", "path": "github-repos/MATLAB/rieder91-MachineLearning/MachineLearning-f6708f216326cb5c9e9e5c3afc912060bfa10486/Exercise 3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7682392981782509}} {"text": "function [ c, discrepancy ] = partition_brute ( n, w )\n\n%*****************************************************************************80\n%\n%% PARTITION_BRUTE approaches the partition problem using brute force.\n%\n% Discussion:\n%\n% We are given a set of N integers W.\n%\n% We seek to partition W into subsets W0 and W1, such that the subsets\n% have equal sums.\n%\n% The \"discrepancy\" is the absolute value of the difference between the\n% two sums, and will be zero if we have solved the problem.\n%\n% For a given set of integers, there may be zero, one, or many solutions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the size of the set.\n%\n% Input, integer W(N), the integers.\n%\n% Output, integer C(N), indicates the proposed solution.\n% C(I) is 0 for items in set W0 and 1 for items in set W1.\n%\n% Output, integer DISCREPANCY, the discrepancy.\n%\n w = w(:);\n w_sum = sum ( w(1:n) );\n discrepancy = w_sum;\n\n d = [];\n rank = -1;\n\n while ( 1 )\n\n [ d, rank ] = subset_next ( n, d, rank );\n\n if ( rank == -1 )\n break\n end\n\n d_discrepancy = abs ( w_sum - 2 * d' * w );\n\n if ( d_discrepancy < discrepancy )\n discrepancy = d_discrepancy;\n c(1:n) = d(1:n);\n end\n\n if ( discrepancy == 0 )\n break\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/partition_problem/partition_brute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.7682392809436832}} {"text": "function [week,sec_of_week] = gps_time(julday)\n% GPS_TIME Conversion of Julian Day number to GPS week and\n%\t Seconds of Week as reckoned from midnight between \n% Saturday and Sunday\n\n% Written by Kai Borre\n% January 7, 2016\n\n a = floor(julday+.5);\n b = a+1537;\n c = floor((b-122.1)/365.25);\n e = floor(365.25*c);\n f = floor((b-e)/30.6001);\n d = b-e-floor(30.6001*f)+rem(julday+.5,1);\n day_of_week = rem(floor(julday+.5),7);\n week = floor((julday-2444244.5)/7);\n % We add +1 as the GPS week starts at Saturday midnight\n sec_of_week = (rem(d,1)+day_of_week+1)*86400;\n%%%%%%% end gps_time.m\t%%%%%%%%%%%%%\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/gps_time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7681553200768133}} {"text": "function [e0,e1,theta] = det2MM(im,sigmaI,sigmaO)\n% function [e0,e1,theta] = det2MM(im,sigmaI,sigmaO)\n%\n% Compute the eigenspectrum of the spatially averaged second moment\n% matrix.\n%\n% INPUT\n%\tim\tImage.\n%\tsigmaI\tInner scale (sigma for image derivatives).\n%\tsigmaO\tOuter scale (sigma for spatial averaging).\n%\n% OUTPUT\n%\te0,e1\tSmaller,larger eigenvalues.\n%\ttheta\tOrientation of fist eigenvector + pi/2\n%\t\t(i.e. orientation of possible edge).\n%\n% David R. Martin \n% March 2003\n\nif ndims(im)>2, im = rgb2gray(im); end;\nidiag = norm(size(im));\n\nif nargin<2, sigmaI=2; end\nif nargin<3, sigmaO=sigmaI; end % Scott Konishi says this is close\n % to optimal.\nsigmaI = max(0.5,sigmaI);\nsigmaO = max(0.5,sigmaO);\n\n% compute x and y image derivatives at inner scale\nfb = cell(2,1);\nfb{1} = oeFilter(sigmaI,3,pi/2,1);\nfb{2} = fb{1}';\nfim = fbRun(fb,im);\ndx = fim{1};\ndy = fim{2};\n\n% compute smoothed squared image derivatives at outer scale\nf = oeFilter(sigmaO,3);\ndx2 = applyFilter(f,dx.^2);\ndy2 = applyFilter(f,dy.^2);\ndxy = applyFilter(f,dx.*dy);\n\n% compute eigenvalues of the spatially averaged 2nd moment matrix\n% and the orientations of the eigenvectors\nk = sqrt( (dx2-dy2).^2 + 4.*dxy.^2 );\neig0 = (dx2 + dy2 - k) / 2;\neig1 = (dx2 + dy2 + k) / 2;\nt0 = atan2( dx2-eig0, -dxy );\nt1 = atan2( dx2-eig1, -dxy );\n\n% order eigenvalues by their absolute value, so e0<=e1, and pick\n% out the orientation corresponding to the largest eigenvalue\nx = (abs(eig1) > abs(eig0));\ne0 = abs(eig0.*x + eig1.*~x);\ne1 = abs(eig1.*x + eig0.*~x);\ntheta = t1.*x + t0.*~x;\ntheta = mod(theta+pi/2,pi);\n\n% check postconditions\nif any(e0>e1), error('e0>e1'); end\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/det2MM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7680940493028405}} {"text": "function [di, dj] = gradient_2d(M, mask)\n% [di dj] = gradient_2d(M)\n% [di dj] = gradient_2d(M, mask)\n%\n% Approximate the gradient of a two-dimensional function represented by M(i,j), using\n% a 3x3 plane fitting algorithm.\n% \n% PARAMETERS\n%\n% M Matrix of function values, M(i,j) = f(i,j), the spacing is assumed to be uniform.\n%\n% mask (Optional) Matrix of the same size of M, with zero values in positions of M to be ignored by the \n% gradient computations.\n%\n% RETURN VALUES\n%\n% di First component of the gradient: di(i,j) is the approximated [d/di f](i,j)\n%\n% dj Second component of the gradient: dj(i,j) is the approximated [d/dj f](i,j)\n%\n% LIMITATIONS\n%\n% To avoid ill-conditioned solutions, the mask is ignored near the \"edges\" of M,\n% so this may result in artifacts in some cases. Leaving a \"safety\" border\n% on the edges should be more than enough to prevent the issue.\n%\n% Author: Luca Vezzaro (elvezzaro@gmail.com)\n\n\tnr = size(M, 1);\n\tnc = size(M, 2);\n\t\n\tif nargin < 2\n\t\tmask = ones(nr, nc);\n\tend\n\t\n\tv = zeros(3,1);\n\t\n\t% The used algorithm is simple: the evaluation point is set\n\t% as the origin, and a plane is fitted to the 8 nearest positions,\n\t% centered on the origin. On the boundary, there are less values,\n\t% but the method is the same.\n\t\n\t% First the \"corners\"\n\t\n\tp(1,:) = [1 0]; v(1) = M(2,1) - M(1,1);\n\tp(2,:) = [0 1]; v(2) = M(1,2) - M(1,1);\n\tp(3,:) = [1 1]; v(3) = M(2,2) - M(1,1);\n\t\t\n\tn = p \\ v;\n\t\t\t\n\tdi(1,1) = n(1);\n\tdj(1,1) = n(2);\n\t\n\tp(1,:) = [0 -1]; v(1) = M(1,nc-1) - M(1,nc);\n\tp(2,:) = [1 -1]; v(2) = M(2,nc-1) - M(1,nc);\n\tp(3,:) = [1 0]; v(3) = M(2,nc) - M(1,nc);\n\t\t\n\tn = p \\ v;\n\t\t\t\n\tdi(1,nc) = n(1);\n\tdj(1,nc) = n(2);\n\t\n\tp(1,:) = [-1 0]; v(1) = M(nr-1,1) - M(nr,1);\n\tp(2,:) = [-1 1]; v(2) = M(nr-1,2) - M(nr,1);\n\tp(3,:) = [0 1]; v(3) = M(nr,2) - M(nr,1);\n\t\t\n\tn = p \\ v;\n\t\t\t\n\tdi(nr,1) = n(1);\n\tdj(nr,1) = n(2);\n\n\tp(1,:) = [-1 -1]; v(1) = M(nr-1,nc-1) - M(nr,nc);\n\tp(2,:) = [0 -1]; v(2) = M(nr,nc-1) - M(nr,nc);\n\tp(3,:) = [-1 0]; v(3) = M(nr-1,nc) - M(nr,nc); \n\t\t\n\tn = p \\ v;\n\t\t\t\n\tdi(nr,nc) = n(1);\n\tdj(nr,nc) = n(2);\n\t\n\t% Then, the boundaries\n\t\n\tfor j=2:nc-1\n\t\tp(1,:) = [0 -1]; v(1) = M(1,j-1) - M(1,j);\n\t\tp(2,:) = [1 -1]; v(2) = M(2,j-1) - M(1,j);\n\t\tp(3,:) = [1 0]; v(3) = M(2,j) - M(1,j);\n\t\tp(4,:) = [0 1]; v(4) = M(1,j+1) - M(1,j);\n\t\tp(5,:) = [1 1]; v(5) = M(2,j+1) - M(1,j);\n\t\t\t\n\t\tn = p \\ v;\n\t\t\t\n\t\tdi(1,j) = n(1);\n\t\tdj(1,j) = n(2);\n\t\t\n\t\tp(1,:) = [-1 -1]; v(1) = M(nr-1,j-1) - M(nr,j);\n\t\tp(2,:) = [0 -1]; v(2) = M(nr,j-1) - M(nr,j);\n\t\tp(3,:) = [-1 0]; v(3) = M(nr-1,j) - M(nr,j);\n\t\tp(4,:) = [-1 1]; v(4) = M(nr-1,j+1) - M(nr,j);\n\t\tp(5,:) = [0 1]; v(5) = M(nr,j+1) - M(nr,j);\n\t\t\t\n\t\tn = p \\ v;\n\t\t\t\n\t\tdi(nr,j) = n(1);\n\t\tdj(nr,j) = n(2);\n\tend\n\t\n\tfor i=2:nr-1\n\t\tp(1,:) = [-1 0]; v(1) = M(i-1,1) - M(i,1);\n\t\tp(2,:) = [1 0]; v(2) = M(i+1,1) - M(i,1);\n\t\tp(3,:) = [-1 1]; v(3) = M(i-1,2) - M(i,1);\n\t\tp(4,:) = [0 1]; v(4) = M(i,2) - M(i,1);\n\t\tp(5,:) = [1 1]; v(5) = M(i+1,2) - M(i,1); \n\t\t\n\t\n\t\tn = p \\ v;\n\t\t\t\n\t\tdi(i,1) = n(1);\n\t\tdj(i,1) = n(2);\n\t\t\n\t\tp(1,:) = [-1 -1]; v(1) = M(i-1,nc-1) - M(i,nc);\n\t\tp(2,:) = [0 -1]; v(2) = M(i,nc-1) - M(i,nc);\n\t\tp(3,:) = [1 -1]; v(3) = M(i+1,nc-1) - M(i,nc);\n\t\tp(4,:) = [-1 0]; v(4) = M(i-1,nc) - M(i,nc);\n\t\tp(5,:) = [1 0]; v(5) = M(i+1,nc) - M(i,nc);\n\t\t\n\t\n\t\tn = p \\ v;\n\t\t\t\n\t\tdi(i,nc) = n(1);\n\t\tdj(i,nc) = n(2);\n\tend\n\n\t% And finally the remaining function values\n\tfor i=2:nr-1\n\t\tfor j=2:nc-1\n\t\t\tif mask(i,j) ~= 0\n\t\t\t\tk = 1;\n\t\t\t\t\n\t\t\t\tif mask(i-1,j-1) ~= 0\n\t\t\t\t\tp(k,:) = [-1 -1]; v(k) = M(i-1,j-1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i-1,j) ~= 0\n\t\t\t\t\tp(k,:) = [-1 0]; v(k) = M(i-1,j) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i-1,j+1) ~= 0\n\t\t\t\t\tp(k,:) = [-1 1]; v(k) = M(i-1,j+1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i,j-1) ~= 0\n\t\t\t\t\tp(k,:) = [0 -1]; v(k) = M(i,j-1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i,j+1) ~= 0\n\t\t\t\t\tp(k,:) = [0 1]; v(k) = M(i,j+1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i+1,j-1) ~= 0\n\t\t\t\t\tp(k,:) = [1 -1]; v(k) = M(i+1,j-1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i+1,j) ~= 0\n\t\t\t\t\tp(k,:) = [1 0]; v(k) = M(i+1,j) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif mask(i+1,j+1) ~= 0\n\t\t\t\t\tp(k,:) = [1 1]; v(k) = M(i+1,j+1) - M(i,j);\n\t\t\t\t\tk = k + 1;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif k > 2\n\t\t\t\t\tn = p(1:k-1,:) \\ v(1:k-1);\n\t\t\t\t\t\n\t\t\t\t\tdi(i,j) = n(1);\n\t\t\t\t\tdj(i,j) = n(2);\n\t\t\t\telse\n\t\t\t\t\tdi(i,j) = 0;\n\t\t\t\t\tdj(i,j) = 0;\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tdi(i,j) = 0;\n\t\t\t\tdj(i,j) = 0;\n\t\t\tend\n\t\tend\n\tend", "meta": {"author": "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/gradient_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7680940485181104}} {"text": "function ell = equivalentEllipsoid(points)\n% Equivalent ellipsoid of a set of 3D points.\n%\n% ELL = equivalentEllipsoid(PTS)\n% Compute the equivalent ellipsoid of the set of points PTS. The result\n% is an ellipsoid defined by:\n% ELL = [XC YC ZC A B C PHI THETA PSI]\n% where [XC YC ZY] is the center, [A B C] are the lengths of the\n% semi-axes (in decreasing order), and [PHI THETA PSI] are Euler angles\n% representing the ellipsoid orientation, in degrees.\n%\n% Example\n% pts = randn(300, 3);\n% pts = transformPoint3d(pts, createScaling3d([6 4 2]));\n% pts = transformPoint3d(pts, createRotationOx(pi/6));\n% pts = transformPoint3d(pts, createRotationOy(pi/4));\n% pts = transformPoint3d(pts, createRotationOz(pi/3));\n% pts = transformPoint3d(pts, createTranslation3d([5 4 3]));\n% elli = equivalentEllipsoid(pts);\n% figure; drawPoint3d(pts); axis equal;\n% hold on; drawEllipsoid(elli, ...\n% 'drawEllipses', true, 'EllipseColor', 'b', 'EllipseWidth', 3);\n%\n% See also\n% spheres, drawEllipsoid, equivalentEllipse, principalAxes\n% rotation3dToEulerAngles\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-03-12, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% number of points\nn = size(points, 1);\n\n% compute centroid\ncenter = mean(points);\n\n% compute the covariance matrix\ncovPts = cov(points)/n;\n\n% perform a principal component analysis with 2 variables, \n% to extract equivalent axes\n[U, S] = svd(covPts);\n\n% extract length of each semi axis\nradii = sqrt(5) * sqrt(diag(S)*n)';\n\n% sort axes from greater to lower\n[radii, ind] = sort(radii, 'descend');\n\n% format U to ensure first axis points to positive x direction\nU = U(ind, :);\nif U(1,1) < 0\n U = -U;\n % keep matrix determinant positive\n U(:,3) = -U(:,3);\nend\n\n% convert axes rotation matrix to Euler angles\nangles = rotation3dToEulerAngles(U);\n\n% concatenate result to form an ellipsoid object\nell = [center, radii, angles];\n", "meta": {"author": "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/equivalentEllipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7680940481257449}} {"text": "function [ w, x ] = gm_rule_set ( rule, dim_num, point_num )\n\n%*****************************************************************************80\n%\n%% GM_RULE_SET sets a Grundmann-Moeller rule.\n%\n% Discussion:\n%\n% This is a revised version of the calculation which seeks to compute\n% the value of the weight in a cautious way that avoids intermediate\n% overflow. Thanks to John Peterson for pointing out the problem on\n% 26 June 2008.\n%\n% This rule returns weights and abscissas of a Grundmann-Moeller\n% quadrature rule for the DIM_NUM-dimensional unit simplex.\n%\n% The dimension POINT_NUM can be determined by calling GM_RULE_SIZE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 June 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Axel Grundmann, Michael Moeller,\n% Invariant Integration Formulas for the N-Simplex\n% by Combinatorial Methods,\n% SIAM Journal on Numerical Analysis,\n% Volume 15, Number 2, April 1978, pages 282-290.\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n% 0 <= RULE.\n%\n% Input, integer DIM_NUM, the spatial dimension.\n% 1 <= DIM_NUM.\n%\n% Input, integer POINT_NUM, the number of points in the rule.\n%\n% Output, real W(POINT_NUM), the weights.\n%\n% Output, real X(DIM_NUM,POINT_NUM), the abscissas.\n%\n s = rule;\n d = 2 * s + 1;\n k = 0;\n n = dim_num;\n one_pm = 1;\n\n for i = 0 : s\n\n weight = one_pm;\n\n for j = 1 : max ( n, d, d + n - i )\n\n if ( j <= n )\n weight = weight * ( j );\n end\n if ( j <= d )\n weight = weight * ( d + n - 2 * i );\n end\n if ( j <= 2 * s )\n weight = weight / 2.0;\n end\n if ( j <= i )\n weight = weight / j;\n end\n if ( j <= d + n - i )\n weight = weight / j;\n end\n\n end\n\n one_pm = - one_pm;\n\n beta_sum = s - i;\n more = 0;\n beta = [];\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ beta, more, h, t ] = comp_next ( beta_sum, dim_num + 1, ...\n beta, more, h, t );\n\n k = k + 1;\n\n w(k) = weight;\n\n x(1:dim_num,k) = ( 2 * beta(2:dim_num+1)' + 1 ) / ( d + n - 2 * i );\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/simplex_gm_rule/gm_rule_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.7680769849106794}} {"text": "function [c1,c2]= binaryfit(phi,U,epsilon) \n% compute c1 c2 for optimal binary fitting \n% input: \n% U: input image\n% phi: level set function\n% epsilon: parameter for computing smooth Heaviside and dirac function\n% output: \n% c1: a constant to fit the image U in the region phi>0\n% c2: a constant to fit the image U in the region phi<0\n\nH = Heaviside(phi,epsilon); % compute the Heaveside function values \n\na = H .* U;\nnumer_1 = sum(a(:)); \ndenom_1 = sum(H(:));\nc1 = numer_1 / denom_1;\n\nb = (1-H) .* U;\nnumer_2 = sum(b(:));\nc = 1-H;\ndenom_2 = sum(c(:));\nc2 = numer_2 / denom_2;\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/检测算法/AirportDetection-master/grsl/soacm/binaryfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7679553616701515}} {"text": "function [center, U, obj_fcn] = fcm(data, cluster_n, options)\n%FCM Data set clustering using fuzzy c-means clustering.\n%\n% [CENTER, U, OBJ_FCN] = FCM(DATA, N_CLUSTER) finds N_CLUSTER number of\n% clusters in the data set DATA. DATA is size M-by-N, where M is the number of\n% data points and N is the number of coordinates for each data point. The\n% coordinates for each cluster center are returned in the rows of the matrix\n% CENTER. The membership function matrix U contains the grade of membership of\n% each DATA point in each cluster. The values 0 and 1 indicate no membership\n% and full membership respectively. Grades between 0 and 1 indicate that the\n% data point has partial membership in a cluster. At each iteration, an\n% objective function is minimized to find the best location for the clusters\n% and its values are returned in OBJ_FCN.\n%\n% [CENTER, ...] = FCM(DATA,N_CLUSTER,OPTIONS) specifies a vector of options\n% for the clustering process:\n% OPTIONS(1): exponent for the matrix U (default: 2.0)\n% OPTIONS(2): maximum number of iterations (default: 100)\n% OPTIONS(3): minimum amount of improvement (default: 1e-5)\n% OPTIONS(4): info display during iteration (default: 1)\n% The clustering process stops when the maximum number of iterations\n% is reached, or when the objective function improvement between two\n% consecutive iterations is less than the minimum amount of improvement\n% specified. Use NaN to select the default value.\n%\n% Example\n% data = rand(100,2);\n% [center,U,obj_fcn] = fcm(data,2);\n% plot(data(:,1), data(:,2),'o');\n% hold on;\n% maxU = max(U);\n% % Find the data points with highest grade of membership in cluster 1\n% index1 = find(U(1,:) == maxU);\n% % Find the data points with highest grade of membership in cluster 2\n% index2 = find(U(2,:) == maxU);\n% line(data(index1,1),data(index1,2),'marker','*','color','g');\n% line(data(index2,1),data(index2,2),'marker','*','color','r');\n% % Plot the cluster centers\n% plot([center([1 2],1)],[center([1 2],2)],'*','color','k')\n% hold off;\n%\n% See also FCMDEMO, INITFCM, IRISFCM, DISTFCM, STEPFCM.\n\n% Roger Jang, 12-13-94, N. Hickey 04-16-01\n% Copyright 1994-2018 The MathWorks, Inc. \n\nif nargin ~= 2 && nargin ~= 3\n\terror(message(\"fuzzy:general:errFLT_incorrectNumInputArguments\"))\nend\n\ndata_n = size(data, 1);\n\n% Change the following to set default options\ndefault_options = [2;\t% exponent for the partition matrix U\n\t\t100;\t% max. number of iteration\n\t\t1e-5;\t% min. amount of improvement\n\t\t1];\t% info display during iteration \n\nif nargin == 2\n\toptions = default_options;\nelse\n\t% If \"options\" is not fully specified, pad it with default values.\n\tif length(options) < 4\n\t\ttmp = default_options;\n\t\ttmp(1:length(options)) = options;\n\t\toptions = tmp;\n\tend\n\t% If some entries of \"options\" are nan's, replace them with defaults.\n\tnan_index = find(isnan(options)==1);\n\toptions(nan_index) = default_options(nan_index);\n\tif options(1) <= 1\n\t\terror(message(\"fuzzy:general:errFcm_expMustBeGtOne\"))\n\tend\nend\n\nexpo = options(1);\t\t% Exponent for U\nmax_iter = options(2);\t\t% Max. iteration\nmin_impro = options(3);\t\t% Min. improvement\ndisplay = options(4);\t\t% Display info or not\n\nobj_fcn = zeros(max_iter, 1);\t% Array for objective function\n\nU = initfcm(cluster_n, data_n);\t\t\t% Initial fuzzy partition\n% Main loop\nfor i = 1:max_iter\n\t[U, center, obj_fcn(i)] = stepfcm(data, U, cluster_n, expo);\n\tif display\n\t\tfprintf('Iteration count = %d, obj. fcn = %f\\n', i, obj_fcn(i));\n\tend\n\t% check termination condition\n\tif i > 1\n\t\tif abs(obj_fcn(i) - obj_fcn(i-1)) < min_impro, break; end\n\tend\nend\n\niter_n = i;\t% Actual number of iterations \nobj_fcn(iter_n+1:max_iter) = [];\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/MOEA-D-EGO/fcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7679457159803751}} {"text": "function inside = triangle_contains_point_2d ( t, p )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_CONTAINS_POINT_2D finds if a point is inside a triangle in 2D.\n%\n% Discussion:\n%\n% The routine assumes that the vertices are given in counter-clockwise\n% order.\n%\n% The routine determines if a point P is \"to the right of\" each of the lines\n% that bound the triangle. It does this by computing the cross product\n% of vectors from a vertex to its next vertex, and to P.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the triangle vertices.\n% The vertices should be given in counter clockwise order.\n%\n% Input, real P(2), the point to be checked.\n%\n% Output, logical INSIDE, is TRUE if the point is inside\n% the triangle or on its boundary.\n%\n dim_num = 2;\n\n inside = 0;\n\n if ( 0.0 < ( p(1) - t(1,1) ) * ( t(2,2) - t(2,1) ) ...\n - ( t(1,2) - t(1,1) ) * ( p(2) - t(2,1) ) );\n return\n end\n\n if ( 0.0 < ( p(1) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...\n - ( t(1,3) - t(1,2) ) * ( p(2) - t(2,2) ) );\n return\n end\n\n if ( 0.0 < ( p(1) - t(1,3) ) * ( t(2,1) - t(2,3) ) ...\n - ( t(1,1) - t(1,3) ) * ( p(2) - t(2,3) ) );\n return\n end\n\n inside = 1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/triangle_contains_point_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7677740476878464}} {"text": " function cx = cheby_u_poly ( m, n, x )\n\n%*****************************************************************************80\n%\n%% CHEBY_U_POLY evaluates Chebyshev polynomials U(n,x).\n%\n% Differential equation:\n%\n% (1-X*X) Y'' - 3 X Y' + N (N+2) Y = 0\n%\n% First terms:\n%\n% U(0,X) = 1\n% U(1,X) = 2 X\n% U(2,X) = 4 X^2 - 1\n% U(3,X) = 8 X^3 - 4 X\n% U(4,X) = 16 X^4 - 12 X^2 + 1\n% U(5,X) = 32 X^5 - 32 X^3 + 6 X\n% U(6,X) = 64 X^6 - 80 X^4 + 24 X^2 - 1\n% U(7,X) = 128 X^7 - 192 X^5 + 80 X^3 - 8X\n%\n% Recursion:\n%\n% U(0,X) = 1,\n% U(1,X) = 2 * X,\n% U(N,X) = 2 * X * U(N-1,X) - U(N-2,X)\n%\n% Norm:\n%\n% Integral ( -1 <= X <= 1 ) ( 1 - X^2 ) * U(N,X)^2 dX = PI/2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of evaluation points.\n%\n% Input, integer N, the highest polynomial to compute.\n%\n% Input, real X(M,1), the evaluation points.\n%\n% Output, real V(M,N+1), the values of the Chebyshev polynomials \n% 0 through N at X(1:M).\n%\n if ( n < 0 )\n v = [];\n return\n end\n\n v = zeros ( m, n + 1 );\n\n v(1:m,1) = 1.0;\n\n if ( n < 1 )\n return\n end\n\n x = x(:);\n\n v(1:m,2) = 2.0 * x(1:m,1);\n\n for j = 2 : n\n v(1:m,j+1) = 2.0 * x(1:m,1) .* v(1:m,j) - v(1:m,j-1);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/cheby_u_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.767774031971018}} {"text": "function chx = bbp_pi ( d )\n\n%*****************************************************************************80\n%\n%% BBP_PI implements the Bailey-Borwein-Plouffe algorithm.\n%\n% Discussion:\n%\n% The BBP algorithm can be used to compute a a few hex digits of pi starting\n% at any position.\n%\n% In particular, bbp_pi ( d ) is a char string of hex digits d+1 through \n% d+13 in the hexadecimal expansion of pi.\n%\n% This function does not require extended precision arithmetic or \n% symbolic computation.\n%\n% The results are usually accurate to about 11 or 12 of the 13 digits.\n%\n% This program is derived from a C program by David H. Bailey dated \n% 2006-09-08, http://www.experimentalmath.info/bbp-codes/piqpr8.c \n%\n% For many other references: Google \"BBP Pi\".\n%\n% Licensing:\n%\n% Copyright (c) 2011, The MathWorks, Inc.\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% * Neither the name of the The MathWorks, Inc. nor the names \n% of its contributors may be used to endorse or promote products derived \n% from this software without specific prior written permission.\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% Modified:\n%\n% 27 February 2012\n%\n% Author:\n%\n% Cleve Moler\n%\n% Reference:\n%\n% Cleve Moler,\n% Cleve's Corner, \"Computing Pi\",\n% http://www.mathworks.com/company/newsletters/news_notes/2011/ \n%\n% Parameters:\n%\n% Input, integer D, the number of decimal digits desired.\n%\n% Output, symbolic P, the value of pi to D digits.\n% \n s1 = series ( 1, d );\n s2 = series ( 4, d );\n s3 = series ( 5, d );\n s4 = series ( 6, d );\n P = 4. * s1 - 2. * s2 - s3 - s4;\n P = P - floor ( P ) + 1.; \n chx = hexchar ( P, 13 );\n\n return\nend\nfunction s = series ( m, d )\n\n%*****************************************************************************80\n%\n%% SERIES\n%\n% s = series(m,d) = sum_k 16^(d-k)/(8*k+m)\n% using the modular powering technique.\n%\n s = 0;\n k = 0;\n t = Inf;\n\n while k < 13 || t > eps\n ak = 8 * k + m;\n if k < d\n t = powmod(16, d - k, ak) / ak;\n else\n t = 16^(d - k) / ak; \n end\n s = mod(s + t, 1);\n k = k + 1;\n end\n\n return\nend\nfunction r = powmod ( b, p, a )\n\n%*****************************************************************************80\n%\n%% POWMOD computes mod(b^p,a) without computing b^p.\n%\n persistent twop\n\n if isempty ( twop )\n twop = 2.^(0:25)';\n end\n\n if a == 1\n r = 0;\n return\n end\n\n n = find ( p <= twop, 1, 'first' );\n\n pt = twop ( n );\n r = 1;\n for j = 1 : n\n if p >= pt\n r = mod ( b * r, a );\n p = p - pt;\n end\n pt = 0.5 * pt;\n if pt >= 1\n r = mod ( r * r, a );\n end\n end\n\n return\nend\nfunction chx = hexchar ( s, n )\n\n%*****************************************************************************80\n%\n%% HEXCHAR returns hex digits.\n%\n% chx(s,n) = string of the first n hex digits of s.\n%\n hx = '0123456789ABCDEF';\n\n s = abs ( s );\n\n for j = 1 : n\n s = 16. * mod ( s, 1 );\n chx(j) = hx ( floor ( s ) + 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/vpa/bbp_pi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7677740253327117}} {"text": "function [nInput,inputMin,inputMax, nTarget, targetMin, targetMax] = preNorm(input, target, inputMax)\n% Preprocesses data so that minimum is -1 and maximum is 1.\n% \n%% Syntax\n% [nInput,inputMin,inputMax] = preNorm(input);\n% [nInput,inputMin,inputMax,nTarget,targetMin,targetMax] = preNorm(input, target);\n% [nInput] = preNorm(input,inputMin,inputMax);\n% \n% \n%% Description\n% Function normalizes inputs so that they fall in the interval [-1,1].\n% Algorithm: nInput = 2*(input-inputMin)/(inputMax-inputMin) - 1; If the\n% data needs to be normalzed using previously computed minimums and\n% maximums, we use: nInput = preNorm(input,inputMin,inputMax);\n% \n% Input:\n% * input ... the n x D input matrix\n% * target/inputMin ... the target vector/if there are 3 input arguments it\n% will be considered as a vector of minimums\n% * inputMax ... maximums\n% \n% Output:\n% * nInput ... the n x D normalized input matrix\n% * inputMin ... the row vector containing minimums for each dimension\n% * inputMax ... the row vector containing maximums for each dimension\n% * nTarget ... the normalized target vector\n% * targetMin ... the target minimum\n% * targetMax ... the target maximum\n% \n% See also:\n% postNorm, postNormVar\n\n%% Signature\n% * Written by Tomaz Sustar, January 2012\n\n\n\nif nargin > 3\n error('Wrong number of arguments.');\nend\n\nif nargin==3 % normalize targets if given\n inputMin = target;\n [nInput,inputMin,inputMax] = normalize(input,inputMin,inputMax); %normalize input\nelse\n [nInput,inputMin,inputMax] = normalize(input); %normalize input\nend\n\n\nif nargin==2 % normalize targets if given\n [nTarget, targetMin, targetMax] = normalize(target); \nend\n\n\n\nfunction [nInput,inputMin,inputMax] = normalize(input, inputMin, inputMax)\n[n, D] = size(input); % n - number of mesurements, D - input space dimenson \n\nif nargin ~= 3\n inputMin = min(input); % row vector of minimiums \n inputMax = max(input); % row vector of maximums\nend\n\nisequal = inputMin==inputMax;\nnotequal = ~isequal;\nif sum(isequal) ~= 0\n warning('Some maximums and minimums are equal. Those inputs will not be transformed.');\n inputMin0 = inputMin.*notequal - 1*isequal; % where equal set minimums to -1\n inputMax0 = inputMax.*notequal + 1*isequal; % and maximums to +1 so the data will not be transformed\nelse\n inputMin0 = inputMin;\n inputMax0 = inputMax;\nend\n\nnInput = 2*(input-repmat(inputMin0,n,1))./repmat((inputMax0-inputMin0),n,1) - 1; % normalize\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-utilities/preNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.7677712132080782}} {"text": "function [H,mu,SR]=standardEpanechnikovKernelBW(param1,N)\n%%STANDARDEPANECHNIKOVKERNELBW Estimate the (univariate or multivariate)\n% kernel bandwidth when approximating a set of samples whose\n% underlying density is (or is approximated as) Gaussian with an\n% Epanechnikov kernel. The Epanechnikov kernel has certain\n% desirable optimality properties.\n%\n%INPUTS: param1 If inputType=0, then this is:\n% xi A numDimXN set of samples of the distribution from which\n% a Gaussian kernel estimator should interpolate a PDF. For\n% multidimensional estimation, there must be >=numDim\n% samples. Specifically, the sample covariance matrix must\n% be positive definite.\n% If inputType=1, then this is:\n% SR A root covariance matrix such that SR*SR' equals the \n% (exact or approximated) covariance matrix of the PDF\n% being approximated.\n% N If this parameter is provided, then param1 is assumed to be\n% SR and N is the number of samples that are being smoothed.\n% Otherwise, if this is omitted or an empty matrix is passed,\n% param1 is xi.\n%\n%OUTPUTS: H The numDimXnumDim kernel bandwidth.\n% mu If xi is given, then this is the sample mean. Otherwise, this\n% is an empty matrix.\n% SR The root covariance matrix from the input or computed from xi.\n%\n%The formulae for the optimal bandwidth of an Epanechnikov kernel given\n%samples from an underlying Gaussian distribution is given in Equation 2.3\n%of [1]. The function EpanechnikovKernel implements the Epanechnikov\n%kernel.\n%\n%REFERENCES:\n%[1] C. Musso, N. Oudjane, and F. LeGland, \"Improving regularised particle\n% filters,\" in Sequential Monte Carlo Methods in Practice, A. Doucet, J.\n% F. G. de Freitas, and N. J. Gordon, Eds., Ch. 12, New York:\n% Springer-Verlag, 2001.\n%\n%March 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2)\n N=[];\nend\n\nnx=size(param1,1);%Dimensionality.\n\nif(isempty(N))%xi is given\n xi=param1;\n N=size(xi,2);\n [mu,S]=calcMixtureMoments(xi);\n SR=cholSemiDef(S,'lower',1);%Not fully triangular. but S=SR*SR'\nelse%SR is given and N must be given.\n mu=[];\n SR=param1;\nend\n\ncn=hypersphereVolume(1,nx);\nA=((8/cn)*(nx+4)*2*sqrt(pi)^nx)^(1/(nx+4));\nhOpt=A*N^(-1/(nx+4));\n\nH=hOpt*SR*eye(nx);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Kernel_Estimation/standardEpanechnikovKernelBW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7677712111392082}} {"text": "function value = lrline ( xu, yu, xv1, yv1, xv2, yv2, dv )\n\n%*****************************************************************************80\n%\n%% LRLINE determines if a point is left of, right or, or on a directed line.\n%\n% Discussion:\n%\n% The directed line is parallel to, and at a signed distance DV from\n% a directed base line from (XV1,YV1) to (XV2,YV2).\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Barry Joe.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Barry Joe,\n% GEOMPACK - a software package for the generation of meshes\n% using geometric algorithms,\n% Advances in Engineering Software,\n% Volume 13, pages 325-331, 1991.\n%\n% Parameters:\n%\n% Input, real XU, YU, the coordinates of the point whose\n% position relative to the directed line is to be determined.\n%\n% Input, real XV1, YV1, XV2, YV2, the coordinates of two points\n% that determine the directed base line.\n%\n% Input, real DV, the signed distance of the directed line\n% from the directed base line through the points (XV1,YV1) and (XV2,YV2).\n% DV is positive for a line to the left of the base line.\n%\n% Output, integer VALUE, the result:\n% +1, the point is to the right of the directed line;\n% 0, the point is on the directed line;\n% -1, the point is to the left of the directed line.\n%\n tol = 100.0 * r8_epsilon ( );\n\n dx = xv2 - xv1;\n dy = yv2 - yv1;\n dxu = xu - xv1;\n dyu = yu - yv1;\n\n tolabs = tol * max ( abs ( dx ), ...\n max ( abs ( dy ), ...\n max ( abs ( dxu ), ...\n max ( abs ( dyu ), abs ( dv ) ) ) ) );\n\n t = dy * dxu - dx * dyu + dv * sqrt ( dx * dx + dy * dy );\n\n if ( tolabs < t )\n value = 1;\n elseif ( -tolabs <= t )\n value = 0;\n else\n value = -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/pwl_interp_2d_scattered/lrline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7677712025431485}} {"text": "function qr = quatrot(w);\n% QUATROT - returns the quaternion representing the rotation given by\n% the 3D vector w (rotation of ||w|| around the direction given by w)\n%\n% qr = quatrot(w);\n%\n% ON - 3/99\n%\n\nth = norm(w);\n\nqr = [cos(th/2) sin(th/2)*w(:)'/th];\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/quatrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7677227239338834}} {"text": "% sgwt_demo1 : SGWT for swiss roll data set\n%\n% This demo builds the SGWT for the swiss roll synthetic data set. It\n% computes a set of scales adapted to the computed upper bound on the\n% spectrum of the graph Laplacian, and displays the scaling function and\n% the scaled wavelet kernels, as well as the corresponding frame bounds. It\n% then computes the wavelets centered on a single vertex, and displays\n% them. This essentally reproduces figure 3 from \n% Hammond,Vangergheynst, Gribonval 2010.\n\n% This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox)\n% Copyright (C) 2010, David K. Hammond. \n%\n% The SGWT toolbox is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% The SGWT toolbox is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with the SGWT toolbox. If not, see .\n\n% Create swiss roll point cloud\nfunction sgwt_demo1 \nclose all\nfprintf('Welcome to SGWT demo #1\\n');\n\nnpoints=500;\nfprintf('Creating Swiss Roll point cloud with %g points\\n',npoints);\ndataparams=struct('n',npoints,'dataset',-1','noise',0,'state',0);\nr=create_synthetic_dataset(dataparams);\nx=rescale_center(r.x);\n\n\nfprintf('Computing edge weights and graph Laplacian\\n');\n% Compute Weighted graph adjacency matrix, and graph Laplacian\nd=distanz(x);\ns=.1;\nA=exp(-d.^2/(2*s^2)); \nL=full(sgwt_laplacian(A));\n\nfprintf('Measuring largest eigenvalue, lmax = ');\n\n%% Design filters for transform\nNscales=4;\nlmax=sgwt_rough_lmax(L);\nfprintf('%g\\n',lmax);\n\nfprintf('Designing transform in spectral domain\\n'); \n\ndesigntype='abspline3';\n%designtype='mexican_hat';\n%designtype='meyer';\n%designtype='simple_tf';\n\n[g,t]=sgwt_filter_design(lmax,Nscales,'designtype',designtype);\n\narange=[0 lmax];\n%% Display filter design in spectral domain\nfigure\nsgwt_view_design(g,t,arange);\nylim([0 3])\nset(gcf,'position',[0 780,600,300])\n%% Chebyshev polynomial approximation\nm=50; % order of polynomial approximation\nfprintf('Computing Chebyshev polynomials of order %g for fast transform \\n',m);\nfor k=1:numel(g)\n c{k}=sgwt_cheby_coeff(g{k},m,m+1,arange);\nend\n\n%% compute transform of delta at one vertex\njcenter=32; % vertex to center wavelets to be shown\nfprintf('Computing forward transform of delta at vertex %g\\n',jcenter);\nN=size(L,1);\nd=sgwt_delta(N,jcenter);\n% forward transform, using chebyshev approximation\nwpall=sgwt_cheby_op(d,L,c,arange);\n\nfprintf('Displaying wavelets\\n');\nif (exist('OCTAVE_VERSION','builtin')~=0)\n % settings for octave\n msize=5;\n plotchar='s';\nelse \n % settings for native matlab\n msize=100;\n plotchar='.';\nend\n\n\ncp=[-1.4,-16.9,3.4]; % camera position\n%% Visualize result\n\n% show original point\nws=300;\nfigure;\nxp=0; yp=ws+100;\nset(gcf,'position',[xp,yp,ws-10,ws+10]);\nscatter3(x(1,:),x(2,:),x(3,:),msize,d,plotchar);\nset(gcf,'Colormap',[.5 .5 .5;1 0 0]);\nclean_axes(cp);\ntitle(sprintf('Vertex %g',jcenter));\n\n% show wavelets\nfor n=1:Nscales+1\n wp=wpall{n};\n figure\n xp=mod(n,3)*(ws+10);\n yp=(1-floor((n)/3))*(ws+100);\n set(gcf,'position',[xp,yp,ws-10,ws+10]);\n scatter3(x(1,:),x(2,:),x(3,:),msize,wp,plotchar);\n colormap jet\n caxis([-1 1]*max(abs(wp)));\n clean_axes(cp);\n\n hcb=colorbar('location','north');\n cxt=get(hcb,'Xtick');\n cxt=[cxt(1),0,cxt(end)];\n set(hcb,'Xtick',cxt);\n cpos=get(hcb,'Position');\n cpos(4)=.02; % make colorbar thinner\n set(hcb,'Position',cpos);\n set(hcb,'Position',[.25 .91 .6 .02]);\n \n if n==1\n title('Scaling function');\n else \n title(sprintf('Wavelet at scale j=%g, t_j = %0.2f',n-1,t((n-1))));\n\n end\nend\n\n\nfunction clean_axes(cp)\nxlim([-1 1]);ylim([-1 1]);zlim([-1 1]);\nset(gca,'Xtick',[-1 0 1]);\nset(gca,'Ytick',[-1 0 1]);\nset(gca,'Ztick',[-1 0 1]);\naxis square\nset(gca,'CameraPosition',cp);\n\n% rescale_center\n% center input data at origin, then rescale so that all coordinates\n% are between -1 and 1\n% \n% x should be dxN\nfunction r=rescale_center(x)\nN=size(x,2);\nd=size(x,1);\nx=x-repmat(mean(x,2),[1,N]);\nc=max(abs(x(:)));\nr=x/c;\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/old/sgwt_toolbox/demo/sgwt_demo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7677227183648947}} {"text": "% Figure 6.58 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n% \n\nclear all\nclose all\n\nnum=9;\nden=conv([1 0.5],[1 1]);\nden=conv(den,[1 2]);\nw=logspace(-1,1,500);\n[mag,phas]=bode(num,den,w);\n[OLGM,OLPM,OLWcg,OLWcp]=margin(mag,phas,w)\n\n%Lead compensator, first guess\nnuml=[1 1];\ndenl=0.333*[1 3];\nnumc=conv(num,numl);\ndenc=conv(den,denl);\n[magc,phasc]=bode(numc,denc,w);\n[D1GM,D1PM,D1Wcg,D1Wcp]=margin(magc,phasc,w)\ndencl=denc+[0 0 0 numc];\nt=0:.1:20;\ny=step(numc,dencl,t);\n%Design Iteration, next guess\nnuml=[1 1.5];\ndenl=0.1*[1 15];\nnumcc=conv(num,numl);\ndencc=conv(den,denl);\n[magcc,phascc]=bode(numcc,dencc,w);\n[D2GM,D2PM,D2Wcg,D2Wcp]=margin(magcc,phascc,w)\nsubplot(2,1,1)\nloglog(w,mag,'-',w,magc,'--',w,magcc,'-.',w,ones(500,1),'-');\ngrid;\n%xlabel('w (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 6.58 Bode Plot for lead-compensation design (a) magnitude');\nsubplot(2,1,2)\nsemilogx(w,phas,'-',w,phasc,'--',w,phascc,'-.',w,-180*ones(500,1));\ngrid;\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\ntitle('Fig. 6.58 (b) phase');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig6_58.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.767667058682188}} {"text": "function [U, L, mu, mse] = pca(X, m)\n% Principal component analysis\n% Input:\n% X: d x n data matrix \n% m: target dimension\n% Output:\n% U: d x m Projection matrix\n% L: m x 1 Eigen values\n% mu: d x 1 mean\n% mse: mean square error\n% Written by Mo Chen (sth4nth@gmail.com).\nn = size(X,2);\nmu = mean(X,2);\nXo = bsxfun(@minus,X,mu);\nS = Xo*Xo'/n; % 12.3\n[U,L] = eig(S); % 12.5\n[L,idx] = sort(diag(L),'descend'); \nmse = sum(L)-sum(L(1:m));\nU = U(:,idx(1:m));\nL = L(1:m);\n\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter12/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.767667057569942}} {"text": "function d = vgg_H_sampson_distance_sqr(H,X1,X2)\n\n% d = vgg_H_sampson_distance_sqr(H,X1,X2)\n%\n% Returns an approximation of the squared geometric distance from the\n% 4d joint-space point [X1;X2] to the H manifold. See Torr CVIU 97.\n\nif (size(X1) ~= size(X2))\n error('Point sets not same size!');\nend\n\np1 = X1 ./ repmat(X1(3,:),3,1);\np2 = X2 ./ repmat(X2(3,:),3,1);\n\nalg = vgg_H_algebraic_distance(H,p1,p2);\n\nN = size(X1,2);\n\nh = reshape(H',9,1);\n\nG1 = [ H(1,1) - p2(1,:) * H(3,1) ; ...\n H(1,2) - p2(1,:) * H(3,2) ; ... \n -p1(1,:) * H(3,1) - p1(2,:) * H(3,2) - H(3,3) ; ...\n zeros(1,N) ];\n\nG2 = [ H(2,1) - p2(2,:) * H(3,1) ; ...\n H(2,2) - p2(2,:) * H(3,2) ; ...\n zeros(1,N) ; ...\n -p1(1,:) * H(3,1) - p1(2,:) * H(3,2) - H(3,3) ];\n\nmagG1 = sqrt(sum(G1 .* G1));\nmagG2 = sqrt(sum(G2 .* G2));\nmagG1G2 = sum(G1 .* G2);\n\nalpha = acos( magG1G2 ./ (magG1 .* magG2) );\n\nD1 = alg(1,:) ./ magG1;\nD2 = alg(2,:) ./ magG2;\n\nd = (D1.*D1 + D2.*D2 - 2 * D1 .* D2 .* cos(alpha)) ./ sin(alpha);\n\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_H_sampson_distance_sqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7676538340657871}} {"text": "function ps = normpdf2( xs, m, C )\n% Normal prob. density function (pdf) with arbitrary covariance matrix.\n%\n% Evaluate the multi-variate density with mean vector m and covariance\n% matrix C for the input vector xs. Assumes that the N datapoints are d\n% dimensional. Then m is dx1 or 1xd, C is dxd, and xs is dxN or NxD where\n% N is the number of samples to be evaluated.\n%\n% USAGE\n% ps = normpdf2( xs, m, C )\n%\n% INPUTS\n% xs - points to evaluated (Nxd or dxN)\n% m - mean vector (dx1 or 1xd)\n% C - Covariance matrix (dxd)\n%\n% OUTPUTS\n% ps - probability density at each x (Nx1)\n%\n% EXAMPLE\n% ps = normpdf2( randn(10,2), [0 0], eye(2) )\n%\n% See also NORMPDF\n%\n% Piotr's Image&Video Toolbox Version 2.30\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% get dimensions of data\nd=length(m);\nif( size(xs,1)~=d ); xs=xs'; end\nN=size(xs,2);\n\nif( d==1 ) % fast special case\n ps = 1/sqrt(2*pi*C) * exp(-(xs-m).*(xs-m)/(2*C))';\n \nelseif( rcond(C)\n ps = zeros(N,1);\n \nelse % get probabilities\n xs = (xs-m(:)*ones(1,N))';\n denom = (2*pi)^(d/2)*sqrt(abs(det(C)));\n mahal = sum( (xs/C).*xs, 2 );\n numer = exp(-0.5*mahal);\n ps = numer/denom;\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/matlab/normpdf2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.767526505138196}} {"text": "% Optimal doping profile optimization\n% Boyd, Kim, Vandenberghe, and Hassibi, \"A tutorial on geometric programming\"\n% Joshi, Boyd, and Dutton, \"Optimal doping profiles via geometric programming\"\n% Written for CVX by Almir Mutapcic 02/08/06\n% (a figure is generated)\n%\n% Determines the optimal doping profile that minimizes base transit\n% time in a (homojunction) bipolar junction transistor.\n% This problem can be posed as a GP:\n%\n% minimize tau_B\n% s.t. Nmin <= v <= Nmax\n% y_(i+1) + v_i^const1 <= y_i\n% w_(i+1) + v_i^const2 <= w_i, etc...\n%\n% where variables are v_i, y_i, and w_i.\n\n% discretization size\nM = 50;\n% M = 1000; % takes a few minutes to process constraints\n\n% problem constants\ng1 = 0.42;\ng2 = 0.69;\nNmax = 5*10^18;\nNmin = 5*10^16;\nNref = 10^17;\nDn0 = 20.72;\nni0 = 1.4*(10^10);\nWB = 10^(-5);\nC = WB^2/((M^2)*(Nref^g1)*Dn0);\n\n% exponent powers\npwi = g2 -1;\npwj = 1+g1-g2;\n\n% optimization variables\ncvx_begin gp\n variables v(M) y(M) w(M)\n\n % objective function is the base transmit time\n tau_B = C*w(1);\n\n minimize( tau_B )\n subject to\n % problem constraints\n v >= Nmin;\n v <= Nmax;\n\n for i = 1:M-1\n if( mod(i,100) == 0 ), fprintf(1,'progress counter: %d\\n',i), end;\n y(i+1) + v(i)^pwj <= y(i);\n w(i+1) + y(i)*v(i)^pwi <= w(i);\n end\n\n y(M) == v(M)^pwj;\n w(M) == y(M)*v(M)^pwi;\ncvx_end\n\n% plot the basic optimal doping profile\nfigure, clf\nnbw = 0:1/M:1-1/M;\nsemilogy(nbw,v,'LineWidth',2);\naxis([0 1 1e16 1e19]);\nxlabel('base');\nylabel('doping');\ntext(0,Nmin,'Nmin ', 'HorizontalAlignment','right');\ntext(0,Nmax,'Nmax ', 'HorizontalAlignment','right');\ndisp('Optimal doping profile is plotted.')\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/gp_tutorial/basic_odp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7673966794059995}} {"text": "%% Bivariate Kernel Density Estimation Demonstration\n% Several examples show how to use the gkdeb2 function.\n\n%% Distribution with unbounded support\n% Distribution with four peaks.\nx = [randn(100,1), (randn(100,1)-10)*2;\n randn(100,1)+10, randn(100,1);\n randn(100,1)+10, (randn(100,1)-10)*2;\n randn(100,2)];\ngkde2(x);\n\n%% Distribution with upper and lower bounds: uniform distribution\nclear\nx=rand(10000,2);\n% PDF with bounded support\np.xylim=[0 0 1 1];\ngkde2(x,p);\n% Compare with unbounded PDF estimate\nfigure;\ngkde2(x);\n\n%% Distribution with lower bound only: exponential distribution\nclear\nx=-log(rand(1000,2));\n% PDF with bounded support\np.xylim=[0 0 Inf Inf];\ngkde2(x,p);\n% Compare with unbounded PDF estimate\nfigure\ngkde2(x);\n\n%% Distribution with lower bound only: log-normal distribution\nclear\nx=exp(randn(1000,2));\n% PDF with bounded support\np.xylim=[0 0 Inf Inf];\ngkde2(x,p);\n% Compare with unbounded PDF estimate\nfigure\ngkde2(x);\n\n%% Distribution with lower bound only: chi-square distribution\nclear\nx=randn(1000,2).^2;\n% PDF with bounded support\np.xylim=[0 0 Inf Inf];\np.alpha=0.95;\ngkde2(x,p);\n% Compare with unbounded PDF estimate\nfigure\np1.alpha=0.95;\ngkde2(x,p1);\n\n%% Distribution with lower bound only: Rayleigh distribution\nclear\nx=sqrt(randn(2,1000).^2 + randn(2,1000).^2);\n% PDF with bounded support\np.xylim=[0 0 Inf Inf];\np.alpha=0.95;\ngkde2(x,p);\n% Compare with unbounded PDF estimate\nfigure\np1.alpha=0.95;\ngkde2(x,p1);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19280-bivariant-kernel-density-estimation-v2-1/gkde2test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7673751267665115}} {"text": "function [dx, dxGrad] = dynamics(x,u,p)\n% [dx, dxGrad] = dynamics(x,u,p)\n%\n% Computes the dynamics (and gradients) for the simple pendulum\n%\n\nq = x(1,:);\ndq = x(2,:);\n\n k = p.k; c = p.c;\n ddq = -c*dq - k*sin(q) + u;\n dx = [dq;ddq];\n\nif nargout == 2 % Analytic gradients\n nTime = length(u);\n \n dqGrad = zeros(1,4,nTime); %4 = [time + angle + rate + torque];\n dqGrad(1,3,:) = 1; %gradient dq wrt dq\n \n ddqGrad = zeros(1,4,nTime); %4 = [time + angle + rate + torque];\n ddqGrad(1,2,:) = -k*cos(q); %gradient ddq wrt q\n ddqGrad(1,3,:) = -c; %gradient ddq wrt dq\n ddqGrad(1,4,:) = 1; %gradient ddq wrt u\n \n dxGrad = cat(1, dqGrad, ddqGrad);\n \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/gradientsTutorial/dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7673517141881244}} {"text": "function[L,ia,ib,num]=blocklen(x,delta)\n%BLOCKLEN Counts the lengths of 'blocks' in an array.\n%\n% Suppose X is a column vector which contains blocks of identical\n% values, e.g. X=[0 0 0 1 1 3 2 2 2]';\n%\n% L=BLOCKLEN(X) counts the lengths of contiguous blocks containing\n% identical values of X, and returns an array L of size SIZE(X).\n% Each elements of L specifies the length of the block to which the\n% corresponding element of X belongs.\n%\n% In the above example, L=[3 3 3 2 2 1 3 3 3]';\n%\n% [L,IA,IB,NUM]=BLOCKLEN(X) optionally returns indices IA and IB \n% into the first and last elements, respectively, of each block, as\n% as well as the block number NUM. NUM is the same size as L.\n%\n% [...]=BLOCKLEN(X,D) defines the junction between two blocks as\n% locations where ABS(DIFF(X))>D. Thus D=1 is a 'rate of change'\n% definition, and X=[1 2 3 5 6 10 16 17 18]'; will yield the same \n% result for L as in the previous example.\n%\n% See also BLOCKNUM.\n% \n% Usage: [L,ia,ib]=blocklen(x); \n% _________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information \n% (C) 2000--2014 J.M. Lilly --- type 'help jlab_license' for details\n \n \n% 06.09.04 JML fixed incorrect IA, IB output length\n\nif strcmpi(x,'--t')\n blocklentest;return;\nend\n\nif nargin==1\n delta=0;\nend\n\nii=(1:length(x))';\n\nindex=find(diff(x)~=delta);\nia=[1;index+1];\nib=[index;length(ii)];\n\nL=zeros(size(ii));\nL(ia)=ib-ia+1;\nL=cumsum(L);\n\nL0=zeros(size(ii));\nib2=ib(1:end-1);\nia2=ia(1:end-1);\nL0(ib2+1)=ib2-ia2+1;\nL0=cumsum(L0);\nL=L-L0;\n\nif nargout ==4\n num=zeros(size(x));\n num(ia)=1;\n num=cumsum(num);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction[]=blocklentest\nx= [0 0 0 1 1 3 2 2 2]';\ny= [3 3 3 2 2 1 3 3 3]';\nnum= [1 1 1 2 2 3 4 4 4]';\n\n[y2,ia2,ib2,num2]=blocklen(x);\nreporttest('BLOCKLEN with D==0',all(y==y2)&&all(num==num2))\n\n\nx=[1 2 3 5 6 10 16 17 18]';\n[y2,ia2,ib2,num2]=blocklen(x,1);\nreporttest('BLOCKLEN with D==1',all(y==y2)&&all(num==num2))\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/jCommon/blocklen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.9161096067182449, "lm_q1q2_score": 0.7673517026155037}} {"text": "function [meantheta,R,sigma,confangle,kappa]=anglemean(theta);\n% calculates the mean of angles\n%\n% [meantheta,anglestrength,sigma,confangle,kappa]=anglemean(theta); \n% \n% anglestrength: can be thought of as the inverse variance. [varies between 0 and one]\n% sigma: circular standard deviation\n% confangle: a 95% confidence angle (confidence of the mean value)\n% kappa: an estimate of kappa in the Von Mises distribution\n%\n% check: http://www.cosy.sbg.ac.at/~reini/huber_dutra_freitas_igarss_01.pdf\n%\n% Aslak Grinsted 2002\ntheta=mod(theta(:),2*pi);\nn=length(theta);\nS=sum(sin(theta));\nC=sum(cos(theta));\nmeantheta=atan2(S,C);\n\nif nargout<2\n return\nend\n%if ((S>C)&(C>0))\n% meantheta=atan(S/C);\n%elseif (C<0)\n% meantheta=atan(S/C)+pi;\n%else\n% meantheta=atan(S/C)+2*pi;\n%end\n%meantheta=mod(meantheta,2*pi);\nRsum=sqrt(S^2+C^2);\nR=Rsum/n;\n\nif (R<.53)\n kappa=2*R+R^3+5*R^5/6;\nelseif (R<.85)\n kappa=-0.4+1.39*R+0.43/(1-R);\nelse\n kappa=1/(R^3-4*R^2+3*R);\nend\n\n\n\n%\n%\n% circular standard deviation:\nsigma=sqrt(-2*log(R));\n\n\nif nargout<4\n return\nend\n\n\n%conflim=.95; \n%a=(length(theta)-Rsum)/chi2pdf()\n\n%this is true if the \nchi2=3.841; % = chi2inv(.95,1)\nif ((R<.9)&(R>sqrt(chi2/(2*n))))\n confangle=acos(sqrt(2*n*(2*Rsum^2-n*chi2)/(4*n-chi2))/Rsum);\nelseif (R>.9)\n confangle=acos(sqrt(n^2-(n^2-Rsum^2)*exp(chi2/n))/Rsum);\nelse %R is really really small ... \n confangle=pi/2;\n warning('Confidence angle not well determined.')\n %this is not good, but not important because the confidence is so low anyway...\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/WaveletToolbox/anglemean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7672452007567614}} {"text": "function D = eig3(A)\n% function D = eig3(A)\n%\n% Compute in one shot the eigen-values of multiples (3 x 3) matrices\n%\n% INPUT:\n% A: (3 x 3 x n) array\n% OUTPUT:\n% D: (3 x n). EIG3 returns in D(:,k) three eigen-values of A(:,:,k)\n%\n% See also: CardanRoots, eig2, eig\n%\n% Author: Bruno Luong \n% History:\n% Original 20-May-2010\n\nif size(A,1) ~= 3 || size(A,2) ~= 3\n error('A must be [3x3xn] array');\nend\n\nA = reshape(A, 9, []).';\n\nP3 = 1;\n% Trace\nP2 = -(A(:,1)+A(:,5)+A(:,9));\n% Principal minors\nM11 = A(:,5).*A(:,9) - A(:,8).*A(:,6);\nM22 = A(:,9).*A(:,1) - A(:,3).*A(:,7);\nM33 = A(:,1).*A(:,5) - A(:,4).*A(:,2);\nP1 = (M11 + M22 + M33);\n% Determinant\nP0 = - A(:,1).*M11 ...\n + A(:,4).*(A(:,2).*A(:,9)-A(:,8).*A(:,3)) ...\n - A(:,7).*(A(:,2).*A(:,6)-A(:,5).*A(:,3));\n\nD = CardanRoots(P3, P2, P1, P0).';\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/27680-multiple-eigen-values-for-2x2-and-3x3-matrices/Eig3Folder/eig3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7671966405480555}} {"text": "function d = DistanceToSO3(mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes mat: A 3x3 matrix.\n% Returns the Frobenius norm to describe the distance of mat from the SO(3) \n% manifold.\n% Computes the distance from R to the SO(3) manifold using the following \n% method:\n% If det(mat) <= 0, return a large number. \n% If det(mat) > 0, return norm(mat' * mat - I).\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% d = DistanceToSO3(mat)\n% \n% Output:\n% d =\n% 0.0884\n\nif det(mat) > 0\n\td = norm(mat' * mat - eye(3), 'fro');\nelse\n d = 1e+9;\nend\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/DistanceToSO3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7671966381060022}} {"text": "function [gx,gy]=gaussgradient(IM,sigma)\n%GAUSSGRADIENT Gradient using first order derivative of Gaussian.\n% [gx,gy]=gaussgradient(IM,sigma) outputs the gradient image gx and gy of\n% image IM using a 2-D Gaussian kernel. Sigma is the standard deviation of\n% this kernel along both directions.\n%\n% Contributed by Guanglei Xiong (xgl99@mails.tsinghua.edu.cn)\n% at Tsinghua University, Beijing, China.\n\n%determine the appropriate size of kernel. The smaller epsilon, the larger\n%size.\nepsilon=1e-2;\nhalfsize=ceil(sigma*sqrt(-2*log(sqrt(2*pi)*sigma*epsilon)));\nsize=2*halfsize+1;\n%generate a 2-D Gaussian kernel along x direction\nfor i=1:size\n for j=1:size\n u=[i-halfsize-1 j-halfsize-1];\n hx(i,j)=gauss(u(1),sigma)*dgauss(u(2),sigma);\n end\nend\nhx=hx/sqrt(sum(sum(abs(hx).*abs(hx))));\n%generate a 2-D Gaussian kernel along y direction\nhy=hx';\n%2-D filtering\ngx=imfilter(IM,hx,'replicate','conv');\ngy=imfilter(IM,hy,'replicate','conv');\n\nfunction y = gauss(x,sigma)\n%Gaussian\ny = exp(-x^2/(2*sigma^2)) / (sigma*sqrt(2*pi));\n\nfunction y = dgauss(x,sigma)\n%first order derivative of Gaussian\ny = -x * gauss(x,sigma) / sigma^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/8060-gradient-using-first-order-derivative-of-gaussian/gaussgradient/gaussgradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7671274169438251}} {"text": "function B=evalBSplinePolys(t,x,k,idx)\n%%EVALBSPLINEPOLYS Given a set of at least 2*(k-1) knots in non-decreasing\n% order (some can be repeated), evaluate all associated\n% scalar order-k b-spline polynomials that might be\n% nonzero. These are B_{idx-k+1,k}(x) to B_{idx,k}(x). The\n% first subscript refers to the knots used in determining\n% the polynomial and the second subscript refers to the\n% order of the polynomial. The center index of the knots\n% is idx and must be k-1<=idxlength(t)-(k-1))\n error('The value of iIdx is too large.') \nend\n\n%This is doing if(any(xt(idx+1)) However, finite precision errors\n%can make things slightly off and create unnecessary warnings, so the\n%comparisons with a tolerance help to avoid that.\nepsMult=4;\nif(any(-(x-t(idx))>epsMult*eps(x)|(x-t(idx+1))>epsMult*eps(x)))\n warning('Points are outside of the valid region implied by iIdx. Function results can be inaccurate.')\nend\n\nx=x(:)';\nnumPoints=length(x);\n\nB=zeros(k,numPoints);\n\ndeltaR=zeros(k-1,numPoints);\ndeltaL=zeros(k-1,numPoints);\n\nB(1,:)=1;\nfor j=1:(k-1)\n deltaR(j,:)=t(idx+j)-x;\n deltaL(j,:)=x-t(idx+1-j);\n \n recurVal=zeros(1,numPoints);\n for r=1:j\n term=B(r,:)./(deltaR(r,:)+deltaL(j+1-r,:));\n B(r,:)=recurVal+deltaR(r,:).*term;\n \n recurVal=deltaL(j+1-r,:).*term;\n end\n B(j+1,:)=recurVal;\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/Interpolation/B-Splines/evalBSplinePolys.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7671144794133432}} {"text": "function int_val = spline_linear_int ( ndata, tdata, ydata, a, b )\n\n%*****************************************************************************80\n%\n%% SPLINE_LINEAR_INT evaluates the integral of a piecewise linear spline.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NDATA, the number of data points defining the spline.\n%\n% Input, real TDATA(NDATA), YDATA(NDATA), the values of the independent\n% and dependent variables at the data points. The values of TDATA should\n% be distinct and increasing.\n%\n% Input, real A, B, the interval over which the integral is desired.\n%\n% Output, real INT_VAL, the value of the integral.\n%\n int_val = 0.0;\n\n if ( a == b )\n return;\n end\n\n a_copy = min ( a, b );\n b_copy = max ( a, b );\n%\n% Find the interval [ TDATA(A_LEFT), TDATA(A_RIGHT) ] that contains, or is\n% nearest to, A.\n%\n [ a_left, a_right ] = r8vec_bracket ( ndata, tdata, a_copy );\n%\n% Find the interval [ TDATA(B_LEFT), TDATA(B_RIGHT) ] that contains, or is\n% nearest to, B.\n%\n [ b_left, b_right ] = r8vec_bracket ( ndata, tdata, b_copy );\n%\n% If A and B are in the same interval...\n%\n if ( a_left == b_left )\n\n tval = ( a_copy + b_copy ) / 2.0;\n\n yp = ( ydata(a_right) - ydata(a_left) ) / ...\n ( tdata(a_right) - tdata(a_left) );\n\n yval = ydata(a_left) + ( tval - tdata(a_left) ) * yp;\n\n int_val = yval * ( b_copy - a_copy );\n\n return;\n end\n%\n% Otherwise, integrate from:\n%\n% A to TDATA(A_RIGHT),\n% TDATA(A_RIGHT) to TDATA(A_RIGHT+1),...\n% TDATA(B_LEFT-1) to TDATA(B_LEFT),\n% TDATA(B_LEFT) to B.\n%\n% Use the fact that the integral of a linear function is the\n% value of the function at the midpoint times the width of the interval.\n%\n tval = ( a_copy + tdata(a_right) ) / 2.0E+00;\n\n yp = ( ydata(a_right) - ydata(a_left) ) / ...\n ( tdata(a_right) - tdata(a_left) );\n\n yval = ydata(a_left) + ( tval - tdata(a_left) ) * yp;\n\n int_val = int_val + yval * ( tdata(a_right) - a_copy );\n\n for i_left = a_right : b_left - 1\n\n tval = ( tdata(i_left+1) + tdata(i_left) ) / 2.0E+00;\n\n yp = ( ydata(i_left+1) - ydata(i_left) ) / ...\n ( tdata(i_left+1) - tdata(i_left) );\n\n yval = ydata(i_left) + ( tval - tdata(i_left) ) * yp;\n\n int_val = int_val + yval * ( tdata(i_left + 1) - tdata(i_left) );\n\n end\n\n tval = ( tdata(b_left) + b_copy ) / 2.0E+00;\n\n yp = ( ydata(b_right) - ydata(b_left) ) / ...\n ( tdata(b_right) - tdata(b_left) );\n\n yval = ydata(b_left) + ( tval - tdata(b_left) ) * yp;\n\n int_val = int_val + yval * ( b_copy - tdata(b_left) );\n\n if ( b < a )\n int_val = -int_val;\n end\n\n return\nend\n", "meta": {"author": "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_linear_int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7670577817447218}} {"text": "function wts = cliqf ( nt, t, kind, alpha, beta, a, b, lo )\n\n%*****************************************************************************80\n%\n%% CLIQF computes a classical quadrature formula, with optional printing.\n%\n% Discussion:\n%\n% This routine computes all the weights of an interpolatory\n% quadrature formula with\n% 1. only simple knots and\n% 2. a classical weight function with any valid A and B, and\n% 3. optionally prints the knots and weights and a check of the moments.\n%\n% To evaluate this quadrature formula for a given function F,\n% call routine EIQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Input, integer LO, indicates what is to be done.\n% > 0, compute and print weights and moments check.\n% = 0, compute weights.\n% < 0, compute and print weights.\n%\n% Output, real WTS(NT), the weights.\n%\n key = 1;\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n ndx = zeros(nt,1);\n\n wts = ciqf ( nt, t, mlt, nt, ndx, key, kind, alpha, beta, a, b, lo );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms655/cliqf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7670577793730178}} {"text": "function [A,b,x] = heat(n,kappa)\n%HEAT Test problem: inverse heat equation.\n%\n% [A,b,x] = heat(n,kappa)\n%\n% A first kind Volterra integral equation with [0,1] as\n% integration interval. The kernel is K(s,t) = k(s-t) with\n% k(t) = t^(-3/2)/(2*kappa*sqrt(pi))*exp(-1/(4*kappa^2*t)) .\n% Here, kappa controls the ill-conditioning of the matrix:\n% kappa = 5 gives a well-conditioned problem\n% kappa = 1 gives an ill-conditioned problem.\n% The default is kappa = 1.\n%\n% An exact soltuion is constructed, and then the right-hand side\n% b is produced as b = A*x.\n\n% Reference: A. S. Carasso, \"Determining surface temperatures from interior\n% observations\", SIAM J. Appl. Math. 42 (1982), 558-574. See also L. Elden,\n% \"The numerical solution of a non-characteristic Cauchy problem for a\n% parabolic equation\"; in P. Deuflhand and E. Hairer (Eds.), \"Numerical\n% Treatment of Inverse Problems in Differential and Integral Equations\",\n% Birkhauser, 1983.\n\n% Discretization by means of simple quadrature (midpoint rule).\n\n% Per Christian Hansen, IMM, Sep, 13, 2001.\n\n% Set default kappa.\nif (nargin==1), kappa = 1; end\n\n% Initialization.\nh = 1/n; t = h/2:h:1;\nc = h/(2*kappa*sqrt(pi));\nd = 1/(4*kappa^2);\n\n% Compute the matrix A.\nk = c*t.^(-1.5).*exp(-d./t);\nr = zeros(1,length(t)); r(1) = k(1); A = toeplitz(k,r);\n\n% Compute the vectors x and b.\nif (nargout>1)\n x = zeros(n,1);\n for i=1:n/2\n ti = i*20/n;\n if (ti < 2)\n x(i) = 0.75*ti^2/4;\n elseif (ti < 3)\n x(i) = 0.75 + (ti-2)*(3-ti);\n else\n x(i) = 0.75*exp(-(ti-3)*2);\n end\n end\n x(n/2+1:n) = zeros(1,n/2);\n b = A*x;\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/heat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.767057771334352}} {"text": "function a = dif2_inverse ( n )\n\n%*****************************************************************************80\n%\n%% DIF2_INVERSE returns the inverse of the DIF2 matrix.\n%\n% Formula:\n%\n% if ( I <= J )\n% A(I,J) = I * (N-J+1) / (N+1)\n% else\n% A(I,J) = J * (N-I+1) / (N+1)\n%\n% Example:\n%\n% N = 4\n%\n% 4 3 2 1\n% (1/5) * 3 6 4 2\n% 2 4 6 3\n% 1 2 3 4\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% det ( A ) = 1 / ( N + 1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n if ( i <= j )\n a(i,j) = ( i * ( n - j + 1 ) ) / ( n + 1 );\n else\n a(i,j) = ( j * ( n - i + 1 ) ) / ( n + 1 );\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/dif2_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7670577685636913}} {"text": "function varargout = gabrielGraph(pts)\n%GABRIELGRAPH Gabriel Graph of a set of points\n%\n% EDGES = gabrielGraph(PTS)\n% Computes the Gabriel graph of the input set of points PTS. The Gabriel\n% graph is based on the euclidean Delaunay triangulation, and keeps only\n% edges whose circumcircle does not contain any other input point than\n% the edge extremities.\n%\n% [NODES EDGES] = gabrielGraph(PTS)\n% Also returns the initial set of points;\n%\n% Example\n% pts = rand(100, 2);\n% edges = gabrielGraph(pts);\n% figure; drawPoint(pts);\n% hold on; axis([0 1 0 1]); axis equal;\n% drawGraph(pts, edges);\n%\n% See also\n% drawGraph, delaunayGraph\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-01-22, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% compute Delaunay triangulation\nif verLessThan('matlab', '8.1')\n % Code for versions before R2013a\n dt = DelaunayTri(pts); %#ok\nelse\n % Code for versions R2013a and later\n dt = delaunayTriangulation(pts);\nend\n\n% extract edges (N-by-2 array)\neds = dt.edges();\n\n% radius of the circule circumscribed to each edge\nrads = edgeLength([pts(eds(:,1), :) pts(eds(:,2), :)]) / 2;\n\n% extract middle point of each edge\nmidPts = midPoint(pts(eds(:,1), :), pts(eds(:,2), :));\n\n% distance between midpoints and all points\n% closest points should be edge vertices\ndists = minDistancePoints(midPts, pts);\n\n% geometric tolerance (adapted to point set extent)\ntol = max(max(pts) - min(pts)) * eps;\n\n% keep only edges whose circumcircle does not contain any other point\nkeep = dists >= rads - tol;\nedges = eds(keep, :);\n\nif nargout < 2\n varargout = {edges};\nelse\n varargout = {pts, edges};\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/gabrielGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7670577658668677}} {"text": "function fX=SchurMatFunEval(f,X)\n%%SCHURMATFUNEVAL Evaluate the matrix function f(X), where the function f\n% is a function that has a Taylor series representation using the\n% Schur-Parlett method. In this approach, f(x) only needs to be\n% evaluated on _scalar_ quantities. Thus, this function can be used\n% to turn scalar functions into matrix functions. Matrix functions\n% with a Taylor series expansions satisfy the identities\n% X*f(X)=f(X)*X and f(inv(B)*X*B)=B*f(X)*inv(B) and include\n% functions such as the matrix exponential and square root.\n%\n%INPUTS: f A function handle that takes a scalar input and returns a scalar\n% output.\n% X The real or complex nXn matrix that should be evaluated via the\n% function f.\n%\n%OUTPUTS: fX The value f(X), where the function f applied to scalar terms\n% is applied to the matrix X. This is not the same as applying f\n% to every scalar element in X.\n%\n%This function implements Algorithm 9.1.1 of Chapter 9.1.4 of [1].\n%\n%EXAMPLE:\n%Here, we show that the result agrees with the mpow function to take a\n%matrix square root.\n% X=randn(6,6);\n% f=@(x)sqrt(x);\n% fX=SchurMatFunEval(f,X);\n% diffVal=fX-mpower(X,1/2)\n%One will see that the entries in diffVal are all on the order of 1e-14 or\n%less, indicating that the two are probably equal within finite precision\n%bounds.\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%January 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=length(X);\n\n%We must use the 'complex' option or else T is not guaranteed to be\n%upper triangular.\n[Q,T]=schur(X,'complex');\n\n%The diagonal terms.\nF=zeros(n,n);\nfor i=1:n\n F(i,i)=f(T(i,i));\nend\n\nfor p=1:(n-1)\n for i=1:(n-p)\n j=i+p;\n s=T(i,j)*(F(j,j)-F(i,i));\n for k=(i+1):(j-1)\n s=s+T(i,k)*F(k,j)-F(i,k)*T(k,j);\n end\n F(i,j)=s/(T(j,j)-T(i,i));\n end\nend\n\nif(isreal(X))\n fX=real(Q*F*Q');\nelse\n fX=Q*F*Q';\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/SchurMatFunEval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7670577569046482}} {"text": "function [ x, seed ] = beta_binomial_sample ( a, b, c, seed )\n\n%*****************************************************************************80\n%\n%% BETA_BINOMIAL_SAMPLE samples the Beta Binomial 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, parameters of the PDF.\n% 0.0D+00 < A,\n% 0.0D+00 < B.\n%\n% Input, integer C, a parameter of the PDF.\n% 0 <= C.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = beta_binomial_cdf_inv ( cdf, a, b, c );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/beta_binomial_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7670544543444981}} {"text": "function r8plu_mul_test ( )\n\n%*****************************************************************************80\n%\n%% R8PLU_MUL_TEST tests R8PLU_MUL;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8PLU_MUL_TEST\\n' );\n fprintf ( 1, ' R8PLU_MUL computes the product A*x=b\\n' );\n fprintf ( 1, ' using the compressed PLU factors of A.\\n' );\n fprintf ( 1, ' Using initial random number seed = %d\\n', seed );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n%\n% Set the matrix.\n%\n [ a, seed ] = r8mat_uniform_01 ( n, n, seed );\n\n r8mat_print ( n, n, a, ' The matrix A:' );\n%\n% Set the right hand side B1.\n%\n for i = 1 : n\n x(i) = i;\n end\n\n b(1:n) = a(1:n,1:n) * x(1:n)';\n\n r8vec_print ( n, b, ' The right hand side B (computed from A):' );\n%\n% Factor the matrix.\n%\n [ pivot, lu, info ] = r8mat_to_r8plu ( n, a );\n%\n% Compute the matrix-vector product.\n%\n b = r8plu_mul ( n, pivot, lu, x );\n\n r8vec_print ( n, b, ' The right hand side B (computed from PLU):' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8plu_mul_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7670225082186998}} {"text": " function y = fractional_delay(x, delay)\n%function y = fractional_delay(x, delay)\n%|\n%| given N samples x[n] of a real, periodic, band-limited signal x(t),\n%| compute sinc interpolated samples of delayed signal y(t) = x(t - delay)\n%| each column of x can be shifted by a different amount if delay is a vector.\n%| in\n%|\tx\t[N L]\n%|\tdelay\t[L]\n%| out\n%|\ty\t[N L]\n%|\n%| see laakso:96:stu for more ideas.\n%|\n%| Copyright 2003-11-1, Jeff Fessler, The University of Michigan\n%| Extend to allow x to have multiple columns, 2003-11-2, Yingying Zhang.\n\nif nargin < 1, ir_usage, end\nif streq(x, 'test'), fractional_delay_test, return, end\nif size(x,2) ~= length(delay)\n\terror 'Need size(x) = [N L]; length(delay) = L'\nend\n\ndims = size(x);\nN = dims(1);\nL = dims(2);\nif length(dims) > 2, error 'x must be 1d or 2d', end\nX = fft(x); % fft of each column\n\n% it is important to choose the k indices appropriately!\nif rem(N,2) % odd\n\tk = [-(N-1)/2:(N-1)/2]';\nelse\n\tk = [-N/2:(N/2-1)]';\nend\n\nc = exp(-1i * 2*pi/N * k * delay(:)'); % [N L] outer product\n\nif ~rem(N,2) % even\n\tmid = 1;\n\tc(mid,:) = real(c(mid,:)); % this is the other key trick!\nend\n\nc = ifftshift(c, 1); % ifftshift differs from fftshift for odd N!\n\nY = X .* c;\ny = ifft(Y);\n\n\n% fractional_delay_test\n% self test\nfunction fractional_delay_test\n\nNlist = [5 6];\nim clf, pl = @(i) subplot(240+i);\nfor ii=1:2\n\tN = Nlist(ii);\n\tn = [0:(N-1)]';\n\txt = @(t, N) sinc_periodic(t, N);\n\tx = xt(n, N);\n\txx = [x x];\n\tdelay = [3.7; -2.2];\n\ty = fractional_delay(xx, delay);\n\n\tt = linspace(0,2*N,401);\n\tyt1 = xt(t-delay(1),N);\n\tyt2 = xt(t-delay(2),N);\n\n\tif im\n\tpl(0+ii), plot(t, xt(t,N), '-', n, xx(:,1), 'o')\n\taxis([0 2*N -0.4 1.1]), titlef('N=%d 1st input', N)\n\tpl(2+ii), plot(t, xt(t,N), '-', n, xx(:,2), 'o')\n\taxis([0 2*N -0.4 1.1]), titlef('N=%d 2nd input', N)\n\tpl(4+ii), plot(t, yt1, '-', n, real(y(:,1)), 's', n, imag(y(:,1)), '.')\n\taxis([0 2*N -0.4 1.1]), titlef('delay=%g 1st input',delay(1))\n\tpl(6+ii), plot(t, yt2, '-', n, real(y(:,2)), 's', n, imag(y(:,2)), '.')\n\taxis([0 2*N -0.4 1.1]), titlef('delay=%g 2nd input',delay(2))\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/utilities/fractional_delay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7670224915895277}} {"text": "%% Machine Learning Online Class\n% Exercise 1: Linear regression with multiple variables\n%\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the\n% linear regression exercise. \n%\n% You will need to complete the following functions in this \n% exericse:\n%\n% warmUpExercise.m\n% plotData.m\n% gradientDescent.m\n% computeCost.m\n% gradientDescentMulti.m\n% computeCostMulti.m\n% featureNormalize.m\n% normalEqn.m\n%\n% For this part of the exercise, you will need to change some\n% parts of the code below for various experiments (e.g., changing\n% learning rates).\n%\n\n%% Initialization\n\n%% ================ Part 1: Feature Normalization ================\n\n%% Clear and Close Figures\nclear all; close all; clc\n\nfprintf('Loading data ...\\n');\n\n%% Load Data\ndata = csvread('ex1data2.txt');\nX = data(:, 1:2);\ny = data(:, 3);\nm = length(y);\n\n% Print out some data points\nfprintf('First 10 examples from the dataset: \\n');\nfprintf(' x = [%.0f %.0f], y = %.0f \\n', [X(1:10,:) y(1:10,:)]');\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n% Scale features and set them to zero mean\nfprintf('Normalizing Features ...\\n');\n\n[X mu sigma] = featureNormalize(X);\n\n% Add intercept term to X\nX = [ones(m, 1) X];\n\n\n%% ================ Part 2: Gradient Descent ================\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: We have provided you with the following starter\n% code that runs gradient descent with a particular\n% learning rate (alpha). \n%\n% Your task is to first make sure that your functions - \n% computeCost and gradientDescent already work with \n% this starter code and support multiple variables.\n%\n% After that, try running gradient descent with \n% different values of alpha and see which one gives\n% you the best result.\n%\n% Finally, you should complete the code at the end\n% to predict the price of a 1650 sq-ft, 3 br house.\n%\n% Hint: By using the 'hold on' command, you can plot multiple\n% graphs on the same figure.\n%\n% Hint: At prediction, make sure you do the same feature normalization.\n%\n\nfprintf('Running gradient descent ...\\n');\n\n% Choose some alpha value\nalpha = 0.3;\nnum_iters = 100;\n\n% Init Theta and Run Gradient Descent \ntheta = zeros(3, 1);\n[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);\n\n% Plot the convergence graph\nfigure;\nplot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);\nxlabel('Number of iterations');\nylabel('Cost J');\n\n% Display gradient descent's result\nfprintf('Theta computed from gradient descent: \\n');\nfprintf(' %f \\n', theta);\nfprintf('\\n');\n\n% Estimate the price of a 1650 sq-ft, 3 br house\n% ====================== YOUR CODE HERE ======================\n% Recall that the first column of X is all-ones. Thus, it does\n% not need to be normalized.\nprice = 0; % You should change this\n\n\n% ============================================================\n\nfprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...\n '(using gradient descent):\\n $%f\\n'], price);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ================ Part 3: Normal Equations ================\n\nfprintf('Solving with normal equations...\\n');\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: The following code computes the closed form \n% solution for linear regression using the normal\n% equations. You should complete the code in \n% normalEqn.m\n%\n% After doing so, you should complete this code \n% to predict the price of a 1650 sq-ft, 3 br house.\n%\n\n%% Load Data\ndata = csvread('ex1data2.txt');\nX = data(:, 1:2);\ny = data(:, 3);\nm = length(y);\n\n% Add intercept term to X\nX = [ones(m, 1) X];\n\n% Calculate the parameters from the normal equation\ntheta = normalEqn(X, y);\n\n% Display normal equation's result\nfprintf('Theta computed from the normal equations: \\n');\nfprintf(' %f \\n', theta);\nfprintf('\\n');\n\n\n% Estimate the price of a 1650 sq-ft, 3 br house\n% ====================== YOUR CODE HERE ======================\nprice = 0; % You should change this\n\n\n% ============================================================\n\nfprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...\n '(using normal equations):\\n $%f\\n'], price);\n\n", "meta": {"author": "zhouxc", "repo": "Stanford-Machine-Learning-Course", "sha": "cb1002771b33ac3af4a14be2afa0431212a66ea5", "save_path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course", "path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course/Stanford-Machine-Learning-Course-cb1002771b33ac3af4a14be2afa0431212a66ea5/Linear Regression/mlclass-ex1/ex1_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8902942195727171, "lm_q1q2_score": 0.7670224814672695}} {"text": "function dist = imDistanceMap(img, varargin)\n%IMDISTANCEMAP Compute chamfer distance using scanning algorithm\n%\n% Usage:\n% RES = imDistanceMap(BIN);\n% where BIN is a binary images, computes for each foreground pixel the\n% minimum distance to the background.\n% The function propagates distances to orthogonal and diagonal pixels,\n% using weights equal to 1 for orthogonal pixels, and sqrt(2) for\n% diagonal markers. The result RES is given in a double array the same\n% size as BIN.\n%\n% RES = imDistanceMap(LBL);\n% The function can be applied to a label image LBL, where the values of\n% LBL correspond to region indices. In that case, the result RES\n% corresponds to the superposition of the results on computed on each\n% label.\n%\n%\n% Methods:\n% The function uses scanning algorithm, by applying one forward and one\n% backward scan. \n%\n% RES = imDistanceMap(..., WEIGHTS);\n% Specifies different weights for computing distance between 2 pixels.\n% WEIGHTS is a 2 elements array, with WEIGHTS(1) corresponding to the\n% distance between two orthonal pixels, and WEIGHTS(2) corresponding to\n% the distance between two diagonal pixels.\n% Possible choices\n% WEIGHTS = [1 sqrt(2)] -> quasi-euclidean distance\n% WEIGHTS = [1 Inf] -> \"Manhattan\" or \"cityblock\" distance\n% WEIGHTS = [1 1] -> \"Chessboard\" distance\n% WEIGHTS = [3 4] -> Borgerfors' weights\n% WEIGHTS = [5 7] -> close approximation of sqrt(2)\n% WEIGHTS = [5 7 11] -> Uses an additional weight for chess-knight\n% shifts around each pixel( default)\n%\n% Note: when specifying weights, the result has the same class/data type\n% than the array of weights. It is possible to balance between speed and\n% memory usage:\n% - if weights are double (the default), the memory usage is larger, but\n% the result can be given in pixel units \n% - if weights are integer (for Borgefors weights, for example), the\n% memory usage is reduced, but representation limit of datatype can\n% be easily reached. One needs to divide by the first weight to get\n% result comparabale with natural distances.\n% For uint8, using [3 4] weigths, the maximal computable distance is\n% around 255/3 = 85 pixels. Using 'int16' seems to be a good\n% tradeoff, the maximal distance with [3 4] weights is around 11000\n% pixels.\n%\n% RES = imDistanceMap(..., 'normalize', TF);\n% If TF is true, normalizes the resulting map by the first weight.\n% Default is true.\n%\n% RES = imDistanceMap(..., 'verbose', true);\n% Displays info on iterations.\n%\n% Examples:\n% % Computes distance map on closed circles, with Borgefors Metric\n% img = imread('circles.png');\n% se = strel('disk', 6);\n% img2 = imclose(img, se);\n% dist = imDistanceMap(img2, [3 4]);\n% imshow(dist, []); colormap jet;\n%\n% % uses the examples from bwdist with different distances\n% img = ones(255, 255);\n% img(126, 126) = 0;\n% res1 = imDistanceMap(img);\n% res2 = imDistanceMap(img, [1 inf]);\n% res3 = imDistanceMap(img, [1 1]);\n% res4 = imDistanceMap(img, [1 1.5]);\n% figure;\n% subplot(221); subimage(mat2gray(res1));\n% hold on; imcontour(res1); title('quasi-euclidean');\n% subplot(222); subimage(mat2gray(res2));\n% hold on; imcontour(res2); title('city-block');\n% subplot(223); subimage(mat2gray(res3));\n% hold on; imcontour(res3); title('chessboard');\n% subplot(224); subimage(mat2gray(res4));\n% hold on; imcontour(res4); title('approx euclidean');\n%\n% \n% See also:\n% bwdist, imGeodesicDistanceMap, imSeparateParticles\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2012-08-20, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2010-08-25 fix memory allocation for large images, add vebosity option\n% 2012-08-20 adapt imChamferDistance to create imDistanceMap\n% 2018-02-22 add management of contiguous labels, and of three weights\n\n\n%% Process input arguments\n\n% default weights for orthogonal or diagonal\nweights = [5 7 11];\n\nnormalize = true;\n\n% extract user-specified weights\nif ~isempty(varargin)\n weights = varargin{1};\n varargin(1) = [];\nend\n\n% extract verbosity option\nverbose = false;\nif length(varargin) > 1\n varName = varargin{1};\n if ~ischar(varName)\n error('Require options as name-value pairs');\n end\n \n if strcmpi(varName, 'normalize')\n normalize = varargin{2};\n elseif strcmpi(varName, 'verbose')\n verbose = varargin{2};\n else\n error(['unknown option: ' varName]);\n end\nend\n\n\n%% Initialisations\n\n% determines type of output from type of weights\noutputType = class(weights);\n\n% small check up to avoid degenerate cases\nw1 = weights(1);\nw2 = weights(2);\nif w2 < w1\n w2 = 2 * w1;\nend\n\n% shifts in directions i and j for (1) forward and (2) backward iterations\nif length(weights) == 2\n nShifts = 4;\n di1 = [-1 -1 -1 0];\n dj1 = [-1 0 1 -1];\n di2 = [+1 +1 +1 0];\n dj2 = [-1 0 1 +1];\n ws = [w2 w1 w2 w1];\n \nelseif length(weights) == 3\n nShifts = 8;\n w3 = weights(3);\n di1 = [-2 -2 -1 -1 -1 -1 -1 0];\n dj1 = [-1 +1 -2 -1 0 1 +2 -1];\n di2 = [+2 +2 +1 +1 +1 +1 +1 0];\n dj2 = [-1 +1 +2 +1 0 -1 -2 +1];\n ws = [w3 w3 w3 w2 w1 w2 w3 w1];\nend\n\n% allocate memory for result\ndist = ones(size(img), outputType);\n\n% init result: either max value, or 0 for marker pixels\nif isinteger(w1)\n dist(:) = intmax(outputType);\nelse\n dist(:) = inf;\nend\ndist(~img) = 0;\n\n% size of image\n[D1, D2] = size(img);\n\n\n%% Forward iteration\n\nif verbose\n disp('Forward iteration %d');\nend\n\nfor i = 1:D1\n for j = 1:D2\n % computes only for pixels within a region\n if img(i, j) == 0\n continue;\n end\n \n % compute minimal propagated distance\n newVal = dist(i, j);\n for k = 1:nShifts\n % coordinate of neighbor\n i2 = i + di1(k);\n j2 = j + dj1(k);\n \n % check bounds\n if i2 < 1 || i2 > D1 || j2 < 1 || j2 > D2\n continue;\n end\n \n % compute new value\n if img(i2, j2) == img(i, j)\n % neighbor in same region \n % -> add offset weight to neighbor distance\n newVal = min(newVal, dist(i2, j2) + ws(k));\n else\n % neighbor in another region \n % -> initialize with the offset weight\n newVal = min(newVal, ws(k));\n end\n \n end\n \n % if distance was changed, update result\n dist(i,j) = newVal;\n end\n \nend % iteration on lines\n\n\n\n%% Backward iteration\n\nif verbose\n disp('Backward iteration');\nend\n\nfor i = D1:-1:1\n for j = D2:-1:1\n % computes only for foreground pixels\n if img(i, j) == 0\n continue;\n end\n \n % compute minimal propagated distance\n newVal = dist(i, j);\n for k = 1:nShifts\n % coordinate of neighbor\n i2 = i + di2(k);\n j2 = j + dj2(k);\n \n % check bounds\n if i2 < 1 || i2 > D1 || j2 < 1 || j2 > D2\n continue;\n end\n \n % compute new value\n if img(i2, j2) == img(i, j)\n % neighbor in same region \n % -> add offset weight to neighbor distance\n newVal = min(newVal, dist(i2, j2) + ws(k));\n else\n % neighbor in another region \n % -> initialize with the offset weight\n newVal = min(newVal, ws(k));\n end\n \n end\n \n % if distance was changed, update result\n dist(i,j) = newVal;\n end\n \nend % line iteration\n\nif normalize\n dist(dist>0) = dist(dist>0) / w1;\nend\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imFilters/imDistanceMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7670028604183982}} {"text": "function Pvalue=myfisher33(x)\n%P=MYFISHER33(X)- Fisher's Exact Probability Test on 3x3 matrix.\n%Fisher's exact test of 3x3 contingency tables permits calculation of\n%precise probabilities in situation where, as a consequence of small cell\n%frequencies, the much more rapid normal approximation and chi-square\n%calculations are liable to be inaccurate. The Fisher's exact test involves\n%the computations of several factorials to obtain the probability of the\n%observed and each of the more extreme tables. Factorials growth quickly,\n%so it's necessary use logarithms of factorials. This computations is very\n%easy in Matlab because x!=gamma(x+1) and log(x!)=gammaln(x+1). This\n%function is now fully vectorized to speed up the computation.\n% Syntax: \tmyfisher33(x)\n% \n% Inputs:\n% X - 3x3 data matrix \n% Outputs:\n% P - 2-tailed p-value\n%\n% Example:\n%\n% A B C\n% -------------------\n% X 4 1 1\n% ------------------- \n% Y 1 3 1\n% -------------------\n% Z 0 1 5\n% -------------------\n%\n% x=[4 1 1; 1 3 1; 0 1 5];\n%\n% Calling on Matlab the function: \n% myfisher33(x)\n%\n% 3x3 matrix Fisher's exact test: 301 tables were evaluated\n% -------------------------------------------------------\n% 2-tail p-value = 0.0322177822\n% -------------------------------------------------------\n%\n% Created by Giuseppe Cardillo\n% giuseppe.cardillo-edta@poste.it\n%\n% To cite this file, this would be an appropriate format:\n% Cardillo G. (2007) MyFisher33: a very compact routine for Fisher's exact\n% test on 3x3 matrix\n% http://www.mathworks.com/matlabcentral/fileexchange/15482\n\n%Input Error handling\nif ~isequal(size(x),[3 3])\n error('Input matrix must be a 3x3 matrix')\nend\nif ~all(isfinite(x(:))) || ~all(isnumeric(x(:)))\n error('Warning: all X values must be numeric and finite')\nend\nif ~isequal(x(:),round(x(:)))\n error('Warning: X data matrix values must be whole numbers')\nend\n\nRs=sum(x,2); %rows sum\nCs=sum(x); %columns sum\nN=sum(Rs); %Number of observations\n\n%If necessed, rearrange matrix\nif ~issorted(Cs)\n [Cs,ind]=sort(Cs);\n x=x(:,ind);\nend\nif ~issorted(Rs)\n [Rs,ind]=sort(Rs);\n x=x(ind,:);\nend\n\nKf=sum(gammaln([Rs' Cs]+1))-gammaln(N+1); %The costant factor K=log(prod(R!)*prod(C!)/N!)\nzf=gammaln(x+1); %compute log(x!)\nop=exp(Kf-sum(zf(:))); %compute the p-value of the observed matrix\n\n% First step: Compute all possible primary tables (play on the first two\n% degrees of freedom)\nI=0:1:min(Rs(1),Cs(1)); %all possible values of X(1,1)\nJ=min(Rs(1)-I,Cs(2)); %max value of X(1,2) given X(1,1)\net=sum(J+1); %primary tables to evaluate\nm1=zeros(et,3); %matrix preallocation\n%set the arrays of indices\nidxAstop=cumsum(J+1); \nidxAstart=[1 idxAstop(1:end-1)+1];\n%Build-up the matrix\nfor K=1:length(I)\n m1(idxAstart(K):idxAstop(K),1)=I(K);\n m1(idxAstart(K):idxAstop(K),2)=0:1:J(K);\nend\n%Put all the possible values of X(1,3) given X(1,1) and X(1,2)\nm1(:,3)=Rs(1)-sum(m1(:,1:2),2);\n\n%Second step:\n%Compute all possible secondary tables (play on the second two\n% degrees of freedom)\nm2=repmat(Cs,et,1);\nCs2=m2-m1; %Residual sum of rows given the first row\nL=min(Rs(2),Cs2(:,1)); %find the max values of X(2,1) given X(1,1) and X(1,2)\nKK=max(L)+1; %Remember that zero is a possible value...\n%matrix preallocation\nUpB=zeros(et,KK); \nfor K=1:KK\n%find the max values of X(2,2) given X(1,1), X(1,2) and X(2,2)\n UpB(:,K)=min(Cs2(:,2),Rs(2)-(K-1)); \nend\n%matrix preallocation\nLoB=zeros(et,KK); InT=repmat(NaN,et,KK);\nsectab=zeros(1,et); %array preallocation\nfor K=1:et\n %find the min values of X(2,2) given X(1,1), X(1,2) and X(2,2)\n z=L(K)+1;\n a=0:1:L(K);\n LoB(K,1:z)=max(0,Rs(2)-a-Cs2(K,3));\n %Compute the range of variation of X(2,2)\n InT(K,1:z)=UpB(K,1:z)-LoB(K,1:z)+1;\n %Compute how many secondary tables are generated from each primary table\n sectab(K)=sum(InT(K,1:z),2);\nend\net2=sum(sectab); %total tables to evaluate\n%Matrix and vector preallocation\nM=zeros(et2,9); \n%Set indices\nInT=InT'; InT(isnan(InT))=[];\nidxAstop=cumsum(InT(:))';\nidxAstart=[1 idxAstop(1:end-1)+1];\nidxBstop=cumsum(sectab); idxBstart=[1 idxBstop(1:end-1)+1];\n%Build-up the secondary tables\nz=1;\nfor K=1:et\n %Expand the primary table\n M(idxBstart(K):idxBstop(K),1:3)=repmat(m1(K,:),sectab(K),1);\n I=0:1:L(K); %values of X(2,1) given X(1,1) and X(1,2)\n %Put them in the matrix in the correct position\n for J=1:length(I)\n M(idxAstart(z):idxAstop(z),4)=I(J);\n M(idxAstart(z):idxAstop(z),5)=LoB(K,J):1:UpB(K,J); %values of X(2,2) given X(1,1), X(1,2) and X(2,2)\n z=z+1;\n end\nend\n%Complete the table\nM(:,6)=Rs(2)-sum(M(:,4:5),2);\nM(:,7:9)=repmat(Cs,et2,1)-M(:,1:3)-M(:,4:6);\nzf=gammaln(M+1); %compute log(x!)\nnp=exp(Kf-sum(zf,2)); %compute the p-value of each possible matrix\nP=sum(np(np. \n\n% extract factors\nfacs = zeros(1, max_number - min_number);\nfac_max = facs;\nfor index = min_number:max_number;\n facs(index - min_number + 1) = length(factor(index));\n fac_max(index - min_number + 1) = max(factor(index));\nend\n\n% plot factors\nfigure;\nsubplot(2, 1, 1), bar(min_number:max_number, facs);\nset(gca, 'XLim', [(min_number -0.5) (max_number + 0.5)]);\ntitle('number of factors');\nsubplot(2, 1, 2), bar(min_number:max_number, fac_max);\nset(gca, 'XLim', [(min_number -0.5) (max_number + 0.5)]);\ntitle('largest factor');\n\n% compute best factors in range\ndisp('Numbers with a maximum prime factor of 2');\nind = min_number + find(fac_max == 2) - 1;\ndisp(num2str(ind));\ndisp('Numbers with a maximum prime factor of 3');\nind = min_number + find(fac_max == 3) - 1;\ndisp(num2str(ind));\ndisp('Numbers with a maximum prime factor of 5');\nind = min_number + find(fac_max == 5) - 1;\ndisp(num2str(ind));\ndisp('Numbers with a maximum prime factor of 7');\nind = min_number + find(fac_max == 7) - 1;\ndisp(num2str(ind));\ndisp('Numbers to avoid (prime numbers)');\nnums = min_number:max_number;\ndisp(num2str(nums(fac_max == nums)));\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/checkFactors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7667781855712629}} {"text": "function [bestEpsilon bestF1] = selectThreshold(yval, pval)\n%SELECTTHRESHOLD Find the best threshold (epsilon) to use for selecting\n%outliers\n% [bestEpsilon bestF1] = SELECTTHRESHOLD(yval, pval) finds the best\n% threshold to use for selecting outliers based on the results from a\n% validation set (pval) and the ground truth (yval).\n%\n\nbestEpsilon = 0;\nbestF1 = 0;\nF1 = 0;\n\nstepsize = (max(pval) - min(pval)) / 1000;\nfor epsilon = min(pval):stepsize:max(pval)\n \n % ====================== YOUR CODE HERE ======================\n % Instructions: Compute the F1 score of choosing epsilon as the\n % threshold and place the value in F1. The code at the\n % end of the loop will compare the F1 score for this\n % choice of epsilon and set it to be the best epsilon if\n % it is better than the current choice of epsilon.\n % \n % Note: You can use predictions = (pval < epsilon) to get a binary vector\n % of 0's and 1's of the outlier predictions\n \n cvPrediction = pval bestF1\n bestF1 = F1;\n bestEpsilon = epsilon;\n end\nend\n\nend\n", "meta": {"author": "lawlite19", "repo": "MachineLearningEx", "sha": "44be60fe4d639d18af5ea5011f069eed348e97b8", "save_path": "github-repos/MATLAB/lawlite19-MachineLearningEx", "path": "github-repos/MATLAB/lawlite19-MachineLearningEx/MachineLearningEx-44be60fe4d639d18af5ea5011f069eed348e97b8/machine-learning-ex8/ex8/selectThreshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.7666769577527419}} {"text": "function bivand2_test ( )\n\n%*****************************************************************************80\n%\n%% BIVAND2_TEST tests BIVAND2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BIVAND2_TEST:\\n' );\n fprintf ( 1, ' Compute a bidimensional Vandermonde matrix\\n' );\n fprintf ( 1, ' associated with the product polynomials of\\n' );\n fprintf ( 1, ' maximum degree less than N.\\n' );\n\n n = 3;\n nn = n^2;\n\n alpha = [ 1.0; 2.0; 3.0 ];\n beta = [ 10.0; 20.0; 30.0 ];\n\n r8vec_print ( n, alpha, ' Vandermonde vector ALPHA:' );\n r8vec_print ( n, beta, ' Vandermonde vector BETA:' );\n\n a = bivand2 ( n, alpha, beta );\n\n r8mat_print ( nn, nn, a, ' Bidimensional Vandermonde 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/vandermonde/bivand2_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.7666769517584525}} {"text": "function result = torus_square_14c ( func, r1, r2 )\n\n%*****************************************************************************80\n%\n%% TORUS_SQUARE_14C approximates an integral in a \"square\" torus in 3D.\n%\n% Discussion:\n%\n% A 14-th degree 960 point formula is used.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that:\n%\n% R1 - R2 <= SQRT ( X**2 + Y**2 ) <= R1 + R2,\n% -R2 <= Z <= R2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 May 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Arthur H Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function of three variables which is to be integrated, of the form:\n% function value = func ( x, y, z )\n%\n% Input, real R1, R2, the radii that define the torus.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n norder = 8;\n\n [ rtab, weight ] = legendre_set ( norder );\n\n w = 1.0E+00 / ( 60.0E+00 * r1 );\n quad = 0.0E+00;\n\n for n = 1 : 15\n\n angle = 2.0E+00 * pi * n / 15.0E+00;\n cth = cos ( angle );\n sth = sin ( angle );\n\n for i = 1 : norder\n\n u = r1 + rtab(i) * r2;\n x = u * cth;\n y = u * sth;\n\n for j = 1 : norder\n z = rtab(j) * r2;\n quad = quad + u * w * weight(i) * weight(j) * feval ( func, x, y, z );\n end\n\n end\n\n end\n\n volume = torus_square_volume_3d ( r1, r2 );\n result = quad * volume;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/torus_square_14c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.766662171919717}} {"text": "classdef GaussianD\n%%GAUSSIAND Functions to handle the scalar and multivariate Gaussian\n% distribution.\n%Implemented methods are: mean,cov, PDF, PDFI, PDFIDerivs (for multivariate\n% derivatives of the PDF), PDFS, logPDFS,\n% PDFSGradHessVechS (for the gradient and Hessian\n% of the elements of a lower-triangular square-root\n% of the covariance matrix), CDF (for scalar\n% distributions), invCDF (for scalar\n% distributions), normProdDist, normConvDist (for\n% scalar distributions), momentGenFun\n% (multivariate, including derivatives), cumGenFun\n% (multivariate, including derivatives), rand,\n% randS, integralOverRegion, entropy\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n\nfunction val=mean(mu)\n%%MEAN Obtain the mean of the Gaussian distribution.\n%\n%INPUTS: mu The mean of the PDF. If the PDF is multivariate, then this is\n% a numDimX1 column vector.\n%\n%OUTPUTS: val The numDimX1 mean of the Gaussian distribution.\n%\n%The Gaussian distribution is parameterized by its mean and covariance\n%matrix. Thus, this function just returns the mean it is given.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=mu;\nend\n\nfunction val=cov(Sigma)\n%%COV Obtain the covariance matrix of the Gaussian distribution (the\n% variance if scalar).\n%\n%INPUTS: Sigma The variance (if scalar) or covariance matrix (if\n% multidimensional) of the PDF. The variance cannot be zero\n% and the covariance matrix cannot be singular.\n%\n%OUTPUTS: val The covariance matrix of the Gaussian distribution.\n%\n%The Gaussian distribution is parameterized by its mean and covariance\n%matrix. Thus, this function just returns the covariance matrix it is\n%given.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=Sigma;\nend\n\nfunction vals=PDF(z,mu,Sigma)\n%%PDF Evaluate a scalar or multivariate Gaussian (normal) PDF at specified\n% points given the mean and the covariance matrix.\n%\n%INPUTS: z The points at which the PDF should be evaluated. If the PDF is\n% multivariate, then this is a column vector. If evaluation at\n% multiple points are desired, then this is a numDimXN matrix with\n% each column being the a point (a vector).\n% mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector. If omitted or an empty matrix is passed,\n% a zero mean is used.\n% Sigma The variance (if scalar) or numDimXnumDim covariance matrix\n% (if multidimensional) of the PDF. The variance cannot be zero\n% and the covariance matrix cannot be singular. If omitted or an\n% empty matrix is passed, the identity matrix is used as the\n% covariance matrix.\n%\n%OUTPUTS: vals The scalar values of the normal PDF with mean mu and\n% covariance matrix Sigma evaluated at the points in z. If\n% multiple points are passed (z is a matrix), then val is a\n% row vector.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n numDim=size(z,1);\n if(nargin<2||isempty(mu))\n mu=zeros(numDim,1);\n end\n \n if(nargin<3||isempty(Sigma))\n Sigma=eye(numDim,numDim); \n end\n \n diff=bsxfun(@minus,z,mu);\n vals=(2*pi)^(-numDim/2)*(det(Sigma))^(-1/2)*exp(-0.5*invSymQuadForm(diff,Sigma));\nend\n\nfunction vals=logPDF(z,mu,Sigma)\n%%LOGPDF Evaluate the natural logarithm of a scalar or multivariate\n% Gaussian (normal) PDF at a certain points given the mean and the\n% covariance matrix.\n%\n%INPUTS: z The points at which the PDF should be evaluated. If the PDF is\n% multivariate, then this is a column vector. If evaluation at\n% multiple points are desired, then this is a numDimXN matrix with\n% each column being the a point (a vector).\n% mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector. If omitted or an empty matrix is passed,\n% a zero mean is used.\n% Sigma The variance (if scalar) or numDimXnumDim covariance matrix\n% (if multidimensional) of the PDF. The variance cannot be zero\n% and the covariance matrix cannot be singular. If omitted or an\n% empty matrix is passed, the identity matrix is used as the\n% covariance matrix.\n%\n%OUTPUTS: vals The scalar values of the natural logarithm of the normal PDF\n% with mean mu and covariance matrix Sigma evaluated at the\n% points in z. If multiple points are passed (z is a matrix),\n% then val is a row vector.\n%\n%March 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n numDim=size(z,1);\n if(nargin<2||isempty(mu))\n mu=zeros(numDim,1);\n end\n \n if(nargin<3||isempty(Sigma))\n Sigma=eye(numDim,numDim); \n end\n \n diff=bsxfun(@minus,z,mu);\n vals=-(1/2)*log(det(2*pi*Sigma))-(1/2)*invSymQuadForm(diff,Sigma);\nend\n\nfunction vals=PDFI(z,mu,SigmaInv,SigmaInvDet)\n%%PDFI Evaluate a scalar or multivariate Gaussian (normal) PDF at specified\n% points given the mean and the inverse of the covariance matrix.\n%\n%INPUTS: z The points at which the PDF should be evaluated. If the PDF is\n% multivariate, then this is a column vector. If evaluations at\n% multiple points are desired, then this is a numDimXN matrix with\n% each column being the a point (a vector).\n% mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector. If omitted or an empty matrix is passed,\n% a zero mean is used.\n% SigmaInv The inverse variance (if scalar) or numDimXnumDim inverse\n% covariance matrix (if multidimensional) of the PDF. SigmaInv can\n% be singular. If omitted or an empty matrix is passed, the\n% identity matrix is used as the covariance matrix.\n% SigmaInvDet Optionally, a length-N set of determinants of the matrices\n% in SigmaInv can be passed so as to speed up the computation. If\n% omitted or an empty matrix is passed, determinants will be taken\n% as needed.\n%\n%OUTPUTS: val The scalar value of the normal PDF with mean mu and inverse\n% covariance matrix SigmaInv evaluated at the point z. If\n% multiple points are passed (z is a matrix), then val is a row\n% vector.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n numPoints=size(z,2);\n vals=zeros(1,numPoints);\n n=size(z,1);\n if(nargin<2||isempty(mu))\n mu=zeros(numDim,1);\n end\n \n if(nargin<3||isempty(SigmaInv))\n SigmaInv=eye(numDim,numDim); \n end\n \n if(nargin<4||isempty(SigmaInvDet)) \n constVal=sqrt(det(SigmaInv)/(2*pi)^(n));\n else\n constVal=sqrt(SigmaInvDet/(2*pi)^(n));\n end\n for curPoint=1:numPoints\n diff=z(:,curPoint)-mu;\n %Note that det(A^(-1))=1/det(A) and that det(a*A)=a^n*det(A), where\n %a is a scalar and A is an nXn matrix.\n\n vals(curPoint)=constVal*exp(-0.5*(diff'*SigmaInv*diff));\n end\nend\n\nfunction [PDFDerivVal,coeffPolyPart]=PDFIDerivs(mu,SigmaInv,numDerivs,x)\n%%PDFIDERIVS Compute derivatives of the multivariate Gaussian normal PDF at\n% given the mean and the inverse of the covariance matrix.\n% Derivatives are taken with respect to components of the\n% argument of the PDF, x.\n%\n%INPUTS: mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector.\n% SigmaInv The inverse variance (if scalar) or numDimXnumDim inverse\n% covariance matrix (if multidimensional) of the PDF.\n% SigmaInv can be singular.\n% numDerivs A numDimX1 or 1XnumDim vector indicating the number of\n% derivatives to take with respect to each of the dimensions of\n% the state.numDerivs>=0.\n% x The numDimXnumPoints argument of the PDF at which the\n% derivatives of the PDF should be evaluated. If this parameter\n% is omitted or an empty matrix is passed, then a default of\n% x=zeros(numDim,1) is used.\n%\n%OUTPUTS: PDFDerivVal A numPointsX1 vector of the values of the derivatives\n% of the PDF function given at the points in x or at x=0\n% if x is omitted.\n% coeffPolyPart A hypermatrix taking numDim indices that can be\n% evaluated using the polyValMultiDim at different values\n% of x to get the polynomial coefficient that multiplies\n% the exponential term in the given set of derivatives\n% of the PDF.\n%\n%All derivatives of the multivariate normal distribution have the form\n%sqrt((2*pi)^(-2)*det(SigmaInv))*exp(-1/2*((x-mu)'*SigmaInv*(x-mu))*...\n%(polynomial)\n%The polynomial can be found using the chain rule each time a derivative is\n%taken. The derivative of the exponential term with respect to x(i), the\n%ith component of the state is\n%sqrt((2*pi)^(-2)*det(SigmaInv))*exp(-1/2*((x-mu)'*SigmaInv*(x-mu)) times\n%SigmaInv(i,:)*mu-SigmaInv(i,:)*x.\n%This function returns coeffPolyPart, the coefficients of the multivariate\n%polynomial that multiplies\n%sqrt((2*pi)^(-2)*det(SigmaInv))*exp(-1/2*((x-mu)'*SigmaInv*(x-mu)) when\n%computing the derivatives in addition to returning the value of the PDF at\n%any desired points.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\nnumIdx=size(mu,1);\n\ncoeffPolyPart=1;\n\n%i is the current dimension we are differentiating.\nfor i=1:numIdx\n %basePoly shall be the multivariate polynomial that is added every time\n %the exponential term in the moment generating function is\n %differentiated with respect to the ith index. This makes basePoly the\n %derivative with respect to the ith element of t of the argument of the\n %exponent in the multivariate normal PDF.\n \n %Allocate space for the polynomial and make it have the correct shape.\n basePoly=reshape(zeros(2^numIdx,1),2*ones(1,numIdx));\n \n %The additive term\n basePoly(1)=SigmaInv(i,:)*mu;\n \n %The term multiplied by x consists of elements from the inverse\n %covariance matrix. This just consists of terms in the ith row of the\n %inverse covariance matrix (the matrix is symmetric).\n idxVec=ones(numIdx,1);\n %The dimensionalities of all of the variables for the nDim2Index\n %function.\n dims=2*ones(numIdx,1);\n for curDim=1:numIdx\n idxVec(curDim)=2;\n basePoly(nDim2Index(dims,idxVec))=-SigmaInv(i,curDim);\n idxVec(curDim)=1;\n end\n \n %Now, we enter into a loop to evaluate derivatives of the PDF with\n %respect to the current dimension.\n for derivsLeft=numDerivs(i):-1:1\n %The chain rule means that there are two terms to consider (both of\n %which are multiplied by the same exponential term).\n %The first term is the current coeffPolyPart times the derivative \n %of the exponential term with respect to the ith dimensions. This\n %is the product of coeffPolyPart and basePoly. The second term is\n %the exponential term times the derivative of coeffPolyPart. The\n %two terms then must be added.\n term1=convn(basePoly,coeffPolyPart);%Multiply the polynomials.\n term2=polyDerMultiDim(coeffPolyPart,i);\n \n %Add the multivariate polynomials.\n coeffPolyPart=polySumMultiDim(term1,term2);\n end\nend\n\n%Get rid of redundant parts that arose due to the multiplication.\ncoeffPolyPart=shrinkMultiDimPoly2Fit(coeffPolyPart);\n\n%coeffPolyPart now contains the multivariate polynomial that is multiplied\n%by the exponential term. If no value of t is given, then just evaluate it\n%at x=0. In this instance, the exponential term is zero and only the\n%constant term from the polynomial appears.\nif(nargin<4||isempty(x))\n PDFDerivVal=GaussianD.PDFI([0;0],mu,SigmaInv)*coeffPolyPart(1);\nelse\n numPoints=size(x,2);\n PDFDerivVal=zeros(numPoints,1);\n for curPoint=1:numPoints\n xCur=x(:,curPoint);\n PDFDerivVal(curPoint)=GaussianD.PDFI(xCur,mu,SigmaInv)*polyValMultiDim(coeffPolyPart,xCur);\n end\nend\nend\n\nfunction val=PDFS(z,mu,S)\n%%PDFS Evaluate a scalar or multivariate Gaussian (normal) PDF at specifed\n% points given the mean and the lower-triangular square root of the\n% covariance matrix.\n%\n%INPUTS: z The points at which the PDF should be evaluated. If the PDF is\n% multivariate, then this is a column vector. If evaluations at\n% multiple points are desired, then this is a numDimXN matrix with\n% each column being the a point (a vector).\n% mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector.\n% S The square root of the variance (if scalar) or the numDimXnumDim\n% lower-triangular square root of the covariance matrix (if\n% multidimensional) of the PDF such that S*S'=Sigma, where Sigma\n% is the covariance matrix. S cannot be a singular matrix. If\n% omitted or an empty matrix is passed, the identity matrix is\n% used.\n%\n%OUTPUTS: val The scalar value(s) of the normal PDF with mean mu and square\n% root covariance matrix S evaluated at the points in z. If\n% multiple points are passed (z is a matrix), then val is a row\n% vector.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(nargin<2||isempty(mu))\n mu=zeros(numDim,1);\n end\n\n if(nargin<3||isempty(S))\n \tS=eye(numDim,numDim); \n end\n\n%Note that (S*S')^(-1)=(S')^(-1)*S^(-1)\n diff=S\\bsxfun(@minus,z,mu);\n%Note that det(S*S')=det(S)*det(S') and that det(S)=det(S') so\n%det(S*S')=det(S)^2. Also, det(a*S)=a^ndet(S), where a is a scalar and S is\n%an nXn matrix. Thus,\n%det(2*pi*S*S')=det(sqrt(2*pi)*S)^2=(2*pi)^n*det(S)^2\n n=size(z,1);\n %The abs in the determinant is necessary if the main diagonal of S has\n %negative terms. S can still be such that S*S'=Sigma as the sign of\n %those terms is not unique due to the squaring.\n val = (1/((2*pi)^(n/2)*abs(det(S))))*exp(-0.5*sum(diff.*diff,1)); \nend\n\nfunction val=logPDFS(z,mu,S)\n%%LOGPDFS Evaluate the natural logarithm of a scalar or multivariate\n% Gaussian (normal) PDF at specified points given the mean and the\n% lower-triangular square root of the covariance matrix.\n%\n%INPUTS: z The points at which the PDF should be evaluated. If the PDF is\n% multivariate, then this is a column vector. If evaluations at\n% multiple points are desired, then this is a numDimXN matrix with\n% each column being the a point (a vector).\n% mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector.\n% S The square root of the variance (if scalar) or the numDimXnumDim\n% lower-triangular square root of the covariance matrix (if\n% multidimensional) of the PDF such that S*S'=Sigma, where Sigma\n% is the covariance matrix. S cannot be a singular matrix. If\n% omitted or an empty matrix is passed, the identity matrix is\n% used.\n%\n%OUTPUTS: val The scalar value(s) of the natural logarithm of the normal\n% PDF with mean mu and square root covariance matrix S\n% evaluated at the points in z. If multiple points are passed\n% (z is a matrix), then val is a row vector.\n%\n%March 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(nargin<2||isempty(mu))\n mu=zeros(numDim,1);\n end\n\n if(nargin<3||isempty(S))\n \tS=eye(numDim,numDim); \n end\n\n%Note that (S*S')^(-1)=(S')^(-1)*S^(-1)\n diff=S\\bsxfun(@minus,z,mu);\n%Note that det(S*S')=det(S)*det(S') and that det(S)=det(S') so\n%det(S*S')=det(S)^2. Also, det(a*S)=a^ndet(S), where a is a scalar and S is\n%an nXn matrix. Thus,\n%det(2*pi*S*S')=det(sqrt(2*pi)*S)^2=(2*pi)^n*det(S)^2\n n=size(z,1);\n %The abs in the determinant is necessary if the main diagonal of S has\n %negative terms. S can still be such that S*S'=Sigma as the sign of\n %those terms is not unique due to the squaring.\n % val=-(n/2)*log((2*pi))-log(abs(det(S)))-0.5*sum(diff.*diff,1); \n val=log((1/((2*pi)^(n/2)*abs(det(S))))*exp(-0.5*sum(diff.*diff,1)));\nend\n\nfunction [grad,CDetGrad,Hess,CDetHess]=PDFSGradHessVechS(x,mu,C)\n%%PDFGRADHESSVECHS Find the gradient and (if requested Hessian) of the\n% normal (Gaussian) probability density function (PDF), taken\n% with respect to the vech(C), where C is the lower-triangular\n% square root of the covariance matrix of the distribution.\n%\n%INPUTS: x The dXnumPoints points at which the normal PDF is considered.\n% mu The dX1 mean of the normal PDF.\n% C The dXd lower-triangular square root covariance matrix of the\n% normal PDF. This cannot be singular.\n%\n%OUTPUTS: grad The gradient of the normal PDF with respect to vech(C)\n% (vector of first partial derivatives with respect to the\n% elements of vech(C)). This is an (n*(n+1)/2)XnumPoints set\n% of vectors.\n% CDetGrad The (n*(n+1)/2)X1 gradient of 1/sqrt(C*C') with respect to\n% vech(C). This term is needed to compute grad and Hess and is\n% often needed in algorithms using grad and Hess.\n% Hess The Hessian of the normal PDF with respect to vech(C)\n% (vector of second partial derivatives with respect to the\n% elements of vech(C)). This is an\n% (n*(n+1)/2)X(n*(n+1)/2)XnumPoints set of symmetric matrices.\n% Element i,j in a matrix is the second derivative with\n% respect to elements i and j of vech(C).\n% CDetHess The (n*(n+1)/2)X1 Hessian of 1/sqrt(C*C') with respect to\n% vech(C). This term is needed to compute grad and Hess and is\n% often needed in algorithms using grad and Hess.\n%\n%The gradient and Hessian provided by this function play a role in\n%multivariate kernel bandwidth estimation algorithms, such as the\n%cross-validation bandwidth estimation algorithms of [1], which optimize\n%over the components of a lower-triangular square root matrix to avoid\n%obtaining invalid covariance matrix estimates.\n%\n%This function is implemented based on the rules of matrix calculus.\n%\n%A 5-dimensional example.\n% c=[17;23;4;10;11;5;6;12;18;13;19;25;21;2;9];\n% C=vech2Mat(c,0);\n% x=[5;-10;33;24;-18];\n% mu=[0;0;0;0;0];\n% [grad,Hess]=GaussianD.PDFSGradHessVechS(x,mu,C)\n%\n%REFERENCES:\n%[1] T. Duong and M. L. Hazelton, \"Cross-validation bandwidth matrices for\n% multivariate kernel density estimation,\" Scandinavian Journal of\n% Statistics, vol. 32, no. 3, pp. 485-506, Sep. 2005.\n%\n%January 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Since the derivatives are not with respect to x, it does not matter if the\n%distribution is not zero-mean; just shift the value.\nx=bsxfun(@minus,x,mu);\n\n%Problem dimensionality\nd=size(x,1);\nnumPoints=size(x,2);\n\nvechC=vech(C);\nnumVechEls=length(vechC);\n\nCDetRoot=1/sqrt(det(C*C'));\n\n%Find the gradient of 1/sqrt(C*C') with respect to vech(C). Only the\n%derivatives corresponding to the diagonals are non-zero.\nCDetGrad=vech(diag(-CDetRoot./diag(C)));\n\nCInv=inv(C);\n\n%The exponential term\nexpTerm=exp(-0.5*invSymQuadForm(x,C,1));\n\n%Find the gradient of C^(-1) with respect to vech(C).\nCInvGrad=zeros(d,d,numVechEls);\nCDeriv=zeros(d,d);\ncurEl=1;\nfor j=1:d\n for i=j:d\n CDeriv(i,j)=1;\n \n CInvGrad(:,:,curEl)=CInv*CDeriv*CInv;\n curEl=curEl+1;\n CDeriv(i,j)=0;\n end\nend\n\n%Find the gradient of (C*C')^(-1) with respect to vech(C).\nCCpInvGrad=zeros(d,d,numVechEls);\nfor i=1:numVechEls\n temp=CInv'*CInvGrad(:,:,i);\n CCpInvGrad(:,:,i)=temp+temp';\nend\n\n%Find the gradient of the exponential term with respect to vech(C).\nexpTermGrad=zeros(numVechEls,numPoints);\nfor i=1:numVechEls\n expTermGrad(i,:)=(1/2)*expTerm.*sum(bsxfun(@times,x,CCpInvGrad(:,:,i)*x),1);\nend\n\n%Now, find the derivatives of the PDF with respect to every element of\n%of vech(C).\ngrad=zeros(numVechEls,numPoints);\nfor i=1:numVechEls\n grad(i,:)=CDetGrad(i)*expTerm+CDetRoot*expTermGrad(i,:);\nend\ngrad=grad/(2*pi)^(d/2);\n\nif(nargout>2)%If the Hessian is desired.\n Hess=zeros(numVechEls,numVechEls,numPoints);\n CDetHess=zeros(numVechEls,numVechEls);\n for m=1:numVechEls\n CDerivM=zeros(d,d);\n [i,j]=vechInd2Sub(d,m);%--derivative indices\n CDerivM(i,j)=1;\n \n %This term is used in the Hessian of exp((1/2)*x'*inv(C*C')*x)\n term1H=sum(bsxfun(@times,x, CCpInvGrad(:,:,m)*x),1);\n for n=m:numVechEls\n CDerivN=zeros(d,d);\n [k,l]=vechInd2Sub(d,n);%--derivative indices\n CDerivN(k,l)=1;\n\n %The Hessian of inv(C) with respect to indices i,j and k,l.\n CInvHess=CInv*(CDerivN*CInv*CDerivM+CDerivM*CInv*CDerivN)*CInv;\n\n term1=CInv'*CInvHess;\n term2=CInvGrad(:,:,m)'*CInvGrad(:,:,n);\n %The Hessian of inv(C*C') with respect to indices i,j and k,l.\n CCpInvHess=term1+term1'+term2+term2';\n %The Hessian of exp((1/2)*x'*inv(C*C')*x)\n term2=sum(bsxfun(@times,x, CCpInvGrad(:,:,n)*x),1);\n term3=sum(bsxfun(@times,x,CCpInvHess*x),1);\n expTermHess=(expTerm/2).*((1/2)*term1H.*term2-term3);\n \n Hess(m,n,:)=expTermGrad(m,:)*CDetGrad(n)+expTermGrad(n,:)*CDetGrad(m)+CDetRoot*expTermHess;\n if(i==j&&l==k)%The second derivative term of the Hessian\n CDetHess(m,n)=CDetRoot/(C(i,i)*C(k,k));\n if(i==k)\n CDetHess(m,n)=CDetHess(m,n)*2;\n end\n %Due to the symmetry of the Hessian.\n CDetHess(n,m)=CDetHess(m,n);\n \n Hess(m,n,:)=Hess(m,n,:)+reshape(expTerm*CDetHess(m,n),1,1,numPoints);\n end\n\n Hess(m,n,:)=Hess(m,n,:)*(2*pi)^(-d/2);\n %Due to the symmetry of the Hessian, the upper triangular part\n %is also known.\n Hess(n,m,:)=Hess(m,n,:);\n end\n end\nend\n\nend\n\nfunction val=CDF(z,mu,varVal)\n%%CDF Evaluate cumulative distribution function (CDF) of a a scalar\n% Gaussian (normal) distribution at a specified points given the mean\n% and the variance, or for a normal(0,1) distribution if the mean and\n% variance are omitted.\n%\n%INPUTS: z A matrix of the point(s) at which the CDF should be evaluated.\n% mu The mean of the distribution. If omitted or an empty matrix is\n% passed, a mean of 0 is used.\n% varVal The variance of the distribution. If omitted or an empty matrix\n% is passed, a variance of 1 is used.\n%\n%OUTPUTS: val The scalar value(s) of the normal CDF with mean mu and\n% variance varVal evaluated at the point(s) z.\n%\n%This just uses the relation between the normal CDF and the error function\n%along with the erf function in Matlab.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n\tif(nargin<2||isempty(mu))\n mu=0; \n\tend\n\n\tif(nargin<3||isempty(varVal))\n varVal=1; \n\tend\n\n x=(z-mu)/sqrt(varVal);\n val=(1+erf(x/sqrt(2)))/2;\nend\n\nfunction val=invCDF(prob,mu,varVal)\n%%CDF Evaluate the inverse CDF of a scalar Gaussian (normal) distribution\n% at a given point given the mean and the variance, or for a\n% normal(0,1) distribution if the mean and variance are omitted. When\n% considering a normal(0,1) distribution, this is also known as the\n% probit function.\n%\n%INPUTS: prob The probability or probabilities (0<=prob<=1) at which the \n% argument of the CDF is desired.\n% mu The mean of the distribution. If omitted or an empty matrix\n% is passed, a mean of 0 is used.\n% varVal The variance of the distribution. If omitted or an empty\n% matrix is passed, a variance of 1 is used.\n%\n%OUTPUTS: val The argument(s) of the CDF that would give the probability or\n% probabilities in prob.\n%\n%This just uses the relation between the normal CDF and the error function\n%along with the erfinv (inverse error function) command in Matlab.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\n if(nargin<2||isempty(mu))\n mu=0; \n end\n \n if(nargin<3||isempty(varVal))\n varVal=1; \n end\n\n val=sqrt(2*varVal)*erfinv(2*prob-1)+mu;\nend\n\nfunction [mu,SigmaInv,multiConst]=normProdDist(mu1,SigmaInv1,mu2,SigmaInv2)\n%%NORMPRODDIST The product of two multivariate normal distributions is an\n% unnormalized Gaussian distribution. This finds the\n% parameters of the product distribution.\n%\n%INPUTS: mu1,SigmaInv1 The mean and inverse of the covariance matrix\n% (inverse of the variance for a scalar distribution)\n% of the first normal distribution.\n% mu2,SigmaInv2 The mean and inverse of the covariance matrix\n% (inverse of the variance for a scalar distribution)\n% of the second normal distribution.\n%\n%OUTPUTS: mu, SigmaInv The mean and inverse covariance matrix of the\n% product distribution.\n% multiConst The product distribution is not normalized. This is\n% the multiplicative constant that is multiplied by a\n% normalized distribution.\n%\n%The derivation of the product of two normal PDFs is a standard exercise in\n%many statistics classes. The product distribution is also given\n%explicitly in [1].\n%\n%Note that while SigmaInv1 and SigmaInv2 can each be singular, the sum must\n%be non-singular. Note that for products involving distributions with\n%distant means and small variances, multiConst might be numerically zero.\n%\n%REFERENCES:\n%[1] K. B. Petersen and M. S. Pedersen, \"The matrix cookbook,\" Technical\n% University of Denmark, Tech. Rep., 15 Nov. 2012. [Online]. Available:\n% http://www2.imm.dtu.dk/pubdb/views/publication details.php?id=3274\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\nSigmaInv=SigmaInv1+SigmaInv2;\nmu=SigmaInv\\(SigmaInv1*mu1+SigmaInv2*mu2);\n\nmultiConst=GaussianD.PDFI(mu1,mu2,SigmaInv);\nend\n\nfunction [mu,Sigma]=normConvDist(mu1,Sigma1,mu2,Sigma2)\n%%NORMCONVDIST The convolution of two scalar normal distributions is also a\n% normal distribution. This provides the parameters for the\n% convoluted distribution.\n%\n%INPUTS: mu1,Sigma1 The mean and variance of the first scalar normal\n% distribution.\n% mu2,Sigma2 The mean and variance of the second scalar normal\n% distribution.\n%\n%OUTPUTS: mu, SigmaInv The mean and variance of the product distribution.\n%\n%Note that the product distribution is normalized. The derivation of the\n%product distribution is straightforward nothing that the Fourier transform\n%of a normal distribution is also a fully-normalized (integrates to one) \n%normal distribution.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\nmu=mu1+mu2;\nSigma=Sigma1+Sigma2;\n\nend\n\nfunction [momentVal,coeffPolyPart]=momentGenFun(mu,Sigma,numDerivs,t)\n%%MOMENTGENFUN Evaluate the moment generating function (or one of its\n% derivatives) of the multivariate normal distribution. Taking\n% the ith, jth, kth... derivative of the moment generating\n% function with respect to the first, second, third...\n% components of the argument and evaluating it at t=0 provides\n% the noncentral moment of the multivariate normal\n% distribution involving the ith, jth, kth power of the first\n% second, third... components of the random vector.\n%\n%INPUTS: mu The mean of the PDF. If the PDF is multivariate, then this is a\n% numDimX1 column vector.\n% Sigma The variance (if scalar) or numDimXnumDim covariance matrix \n% (if multidimensional) of the PDF.\n% numDerivs A numDimX1 or 1XnumDim vector indicating the number of\n% derivatives to take with respect to each of the components of\n% the argument of the moment generating function. numDerivs>=0.\n% t The numDimXnumPoints argument of the moment generating\n% function at which the derivatives of the moment generating\n% function should be evaluated. If this parameter is omitted or\n% an empty matrix is passed, then a default of\n% t=zeros(numDim,1) is used.\n%\n%OUTPUTS: momentVal A numPointsX1 vector of the values of the derivatives\n% of the moment generating function given at the points\n% in t or at t=0 if t is omitted.\n% coeffPolyPart A hypermatrix taking numDim indices that can be\n% evaluated using the polyValMultiDim at different values\n% of t to get the polynomial coefficient that multiplies\n% the exponential term in the given set of derivatives\n% of the moment generating function.\n%\n%The moment generating function of a random vector is defined to be\n%E(exp(t'*x)) where E is the expected value operator, x is the random\n%variable and t is a real parameter having the same dimensionality as the\n%random variable. It can be shown that the moment generating function of a\n%multivariate normal distribution is \n%E(exp(t'*x))=exp(t'*mu+(1/2)*t'*Sigma*t)\n%Derivatives of this can be evaluated systematically. First,\n%differentiating the exponential with respect to the ith component of t\n%leads to the original exponential term times\n%mu(i)+sum(Sigma(:,i).*t(:))\n%Thus, all derivatives include the original exponential term times a\n%multivariate polynomial. This function keeps track of the polynomial\n%through all of the derivatives, using the chain rule, the fact that\n%multivariate polynomial multiplication can be performed using the convn\n%function, and using polyDerMultiDim and polySumMultiDim for\n%multidimensional polynomial differentiation and addition.\n%\n%As an example, consider finding the noncentral third moment E(x1*x2*x3) of\n%a 3D multivariate normal distribution. This can be done using\n%If one solves for it by hand, one gets\n%mu(1)*Sigma(2,3)+mu(2)*Sigma(1,3)+mu(3)*Sigma(1,2)+prod(mu)\n%However, the moment can also be found by evaluating the derivatives of the\n%moment generating function with respect to the first, second and third\n%variables at t=[0;0;0]. For example, consider\n% mu=[1;2;3];\n% Sigma=[8, 3, 2;\n% 3,11, 9;\n% 2, 9,18];\n% numDerivs=[1;1;1];\n% momentVal=GaussianD.momentGenFun(mu,Sigma,numDerivs)\n%One will find the value of the noncentral moment to be 28, which is\n%correct.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n%The number of dimensions.\nnumIdx=length(mu);\n\n%Derivative of the moment generating function produce a polynomial times\n%the original exponential term. We shall keep track of that polynomial\n%while differentiating. The loops below take successive derivatives with\n%respect to the different dimensions of the argument vector of the moment\n%generating function. Each component is differentiated for the required\n%number of derivatives. coeffPolyPart holds the accumulated polynomial that\n%multiplies the exponential part of the differentiated moment generating\n%function. Initially, coeffPolyPart=1 to signify that no derivatives have\n%been taken. It is initially implemented with more elements than necessary\n%to simplify the addition of the terms after the use of the polyDerMultiDim\n%function below.\ncoeffPolyPart=1;\n\n%i is the current dimension we are differentiating.\nfor i=1:numIdx\n %basePoly shall be the multivariate polynomial that is added every time\n %the exponential term in the moment generating function is\n %differentiated with respect to the ith index. This makes basePoly the\n %derivative with respect to the ith element of t of the argument of the\n %exponent in the multivariate normal moment generating function\n \n %Allocate space for the polynomial and make it have the correct shape.\n if(numIdx>1)\n basePoly=reshape(zeros(2^numIdx,1),2*ones(1,numIdx));\n else\n basePoly=zeros(2^numIdx,1);\n end\n \n %The additive term is the component of the mean that was multiplied by \n basePoly(1)=mu(i);\n \n %The term multiplied by x consists of elements from the covariance\n %matrix. This just consists of terms in the ith row of the\n %covariance matrix (the matrix is symmetric).\n idxVec=ones(numIdx,1);\n %The dimensionalities of all of the variables for the nDim2Index\n %function.\n dims=2*ones(numIdx,1);\n for curDim=1:numIdx\n idxVec(curDim)=2;\n basePoly(nDim2Index(dims,idxVec))=Sigma(i,curDim);\n idxVec(curDim)=1;\n end\n \n %Now, we enter into a loop to evaluate derivatives of the moment\n %generating function with respect to the current dimension.\n for derivsLeft=numDerivs(i):-1:1\n %The chain rule means that there are two terms to consider (both of\n %which are multiplied by the same exponential term).\n %The first term is the current coeffPolyPart times the derivative \n %of the exponential term with respect to the ith dimensions. This\n %is the product of coeffPolyPart and basePoly. The second term is\n %the exponential term times the derivative of coeffPolyPart. The\n %two terms then must be added.\n term1=convn(basePoly,coeffPolyPart);%Multiply the polynomials.\n term2=polyDerMultiDim(coeffPolyPart,i);\n \n %Add the multivariate polynomials.\n coeffPolyPart=polySumMultiDim(term1,term2);\n end\nend\n\n%coeffPolyPart now contains the multivariate polynomial that is multiplied\n%by the exponential term. If no value of t is given, then just evaluate it\n%at t=0. In this instance, the exponential term is zero and only the\n%constant term from the polynomial appears.\nif(nargin<4||isempty(t))\n momentVal=coeffPolyPart(1);\nelse\n numPoints=size(t,2);\n momentVal=zeros(numPoints,1);\n for curPoint=1:numPoints\n tCur=t(:,curPoint);\n momentVal(curPoint)=exp(tCur'*mu+tCur'*Sigma*tCur)*polyValMultiDim(coeffPolyPart,tCur);\n end\nend\n\nend\n\nfunction cumVal=cumGenFun(mu,Sigma,numDerivs,t)\n%%CUMGENFUN Evaluate the cumulant generating function (or one of its\n% derivatives) of the multivariate normal distribution. Taking\n% the ith, jth, kth... derivative of the cumulant generating\n% function with respect to the first, second, third...\n% components of the argument and evaluating it at t=0 provides\n% the cumulant of the multivariate normal distribution involving\n% the ith, jth, kth power of the first second, third...\n% components of the random vector. The cumulant generating\n% function is the natural logarithm of the moment generating\n% function.\n%\n%INPUTS: mu The mean of the PDF. If the PDF is multivariate, then this\n% is a numDimX1 column vector.\n% Sigma The variance (if scalar) or numDimXnumDim covariance matrix \n% (if multidimensional) of the PDF.\n% numDerivs A numDimX1 or 1XnumDim vector indicating the number of\n% derivatives to take with respect to each of the components of\n% the argument of the cumulant generating function.\n% numDerivs>=0.\n% t The numDimXnumPoints argument of the cumulant generating\n% function at which the derivatives of the cumulant generating\n% function should be evaluated. If this parameter is omitted or\n% an empty matrix is passed, then a default of\n% t=zeros(numDim,1) is used.\n%\n%OUTPUTS: cumVal A numPointsX1 vector of the values of the derivatives\n% of the cumulant generating function given at the points\n% in t or at t=0 if t is omitted.\n%\n%Cumulants are useful in interpolating probability distributions through\n%the use of, for example, an Edgeworth series. The cumulant generating\n%function is defined as the natural logarithm of the moment generating\n%function. It can be shown that the moment generating function of the\n%multivariate normal distribution is \n%E(exp(t'*x))=exp(t'*mu+(1/2)*t'*Sigma*t)\n%Thus, the cumulant generating function is just\n%t'*mu+(1/2)*t'*Sigma*t\n%Consequently, for derivatives higher than two, the cumulant generating\n%function (and hence the cumulants) of the multivariate normal distribution\n%are all zero.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(nargin<4||isempty(t))\n numDim=length(mu);\n t=zeros(numDim,1);\nend\n\nnumPoints=size(t,2);\ncumVal=zeros(numPoints,1);\n\nsumVal=sum(numDerivs);\nswitch(sumVal)\n case 0%No derivatives.\n for curPoint=1:numPoints\n tCur=t(:,curPoint);\n cumVal(curPoint)=tCur'*mu+(1/2)*tCur'*Sigma*tCur;\n end\n case 1\n %Find the nonzero term.\n derivIdx=find(numDerivs);\n for curPoint=1:numPoints\n tCur=t(:,curPoint);\n cumVal(curPoint)=mu(derivIdx)+sum(Sigma(:,derivIdx).*tCur(:));\n end\n case 2\n derivIdx=find(numDerivs);\n cumVal(:)=Sigma(derivIdx(1),derivIdx(2));%The same for all t.\n otherwise%No third or higher order cumulants.\n cumVal(:)=0; \nend\nend\n\nfunction x=rand(N,mu,P)\n%%RAND Generate multivariate Gaussian random variables with a given mean\n% vector and covariance matrix.\n%\n%INPUTS: N The number of random variables to generate.\n% mu The xDim X1 mean of the multivariate Gaussian to generate.\n% P The xDim X xDim positive definite covariance matrix of the\n% multivariate Gaussian to generate. If this parameter is omitted\n% or an empty matrix is passed, then the identity matrix will be\n% used.\n%\n%OUTPUTS: x An xDimXN matrix of random instances of the multivariate\n% Gaussian distribution.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n xDim=size(mu,1);\n if(nargin<3||isempty(P))\n P=zeros(xDim,xDim);\n end\n\n xDim=size(mu,1);\n x=bsxfun(@plus,mu,chol(P,'lower')*randn(xDim,N));\nend\n\nfunction x=randS(N,mu,S)\n%%RANDS Generate multivariate Gaussian random variables with a given mean\n% vector and lower-triangular square root covariance matrix.\n%\n%INPUTS: N The number of random variables to generate.\n% mu The xDim X1 mean of the multivariate Gaussian to generate.\n% S The xDim X xDim lower triangular square root covariance matrix\n% of the multivariate Gaussian to generate.\n%\n%OUTPUTS: x An xDimXN matrix of random instances of the multivariate\n% Gaussian distribution.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n xDim=size(mu,1);\n x=bsxfun(@plus,mu,S*randn(xDim,N));\nend\n\nfunction [P,error,curIter]=integralOverRegion(mu, Sigma,minVals,maxVals,epsVal,alpha,maxIter)\n%%INTEGRALOPVERREGION Compute the probability of a Gaussian probability\n% density function (PDF) within a (hyper-)rectangular\n% region. The probability is computed using a transformed\n% Monte Carlo method designed for this specific integral\n% that converges significantly faster than generic,\n% textbook Monte Carlo integration techniques.\n%\n%INPUTS: mu The NX1 mean vector of the multivariate normal distribution.\n% Sigma The NXN positive definite covariance matrix of the\n% distribution.\n% minVals An NX1 or 1XN vector of the lower integration bounds for all\n% of the dimensions.\n% maxVals An NX1 or 1XN vector of the upper integration bounds. Note\n% that minVals(i)' )\n ylabel ( '<--- J(n,a,b,x) --->' )\n title ( 'Jacobi polynomials J(n,a,b,x)' )\n hold off\n print ( '-dpng', filename )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/jacobi_polynomial/j_polynomial_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7666576280673405}} {"text": "function varargout = levi13(X)\n% Levi function, #13\n%\n% LEVI13([x1, x2]) returns the value of the value of the 13th Levi\n% function at the specified points. [x1] and [x2] may be vectors.\n% The search domain is\n%\n% -10 < x_i < 10\n%\n% The global minimum is \n%\n% f(x1, x2) = f(1, 1) = 0.\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-10, -10]; % LB\n varargout{3} = [+10, +10]; % UB\n varargout{4} = [1,1]; % solution\n varargout{5} = 0; % function value at solution\n \n % otherwise, output function value\n else\n \n % keep values in teh search domain\n X(X < -10) = inf; X(X > 10) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = sin(3*pi*x1).^2 + (x1-1).^2.*(1 + sin(3*pi*x2).^2) + ...\n (x2-1).^2.*(1 + sin(2*pi*x2).^2);\n \n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23147-many-testfunctions-for-global-optimizers/single-objective/levi13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7666529808701632}} {"text": "function [M,MU,N,B,C,prm,iprm] = msns_pre(M,N,B,C)\n%\n% Preprocessing of the system\n% .\n% M x = N x + B u \n% (1)\n% y = C x,\n%\n% where both M and N are REAL, SYMMETRIC and SPARSE. Moreover, M must be \n% positive definite and N must be negative definite.\n%\n% The preprocessing consists of a double transformation of the state: \n%\n% x <-- MU * P * x .\n%\n% The first transformation with the permutation matrix P for bandwidth \n% reduction results in \"overwriting\" the system matrices as\n%\n% M <-- P * M * P', N <-- P * N * P', B <-- P * B, C <-- C * P'.\n%\n% The bandwidth of the reordered matrices M and N is often much smaller \n% than that of the original matrices. \n%\n% By the second transformation, the generalized system (1) is transformed\n% into a standard system\n% .\n% x = A x + B u \n% (2)\n% y = C x.\n%\n% To this end, the Cholesky factorization of M is computed: M = MU'*MU,\n% where MU is upper triangular. This results in:\n% \n% A := inv(MU')*N*inv(MU), B <-- inv(MU')*B, C <-- C*inv(MU).\n%\n% The matrix A, which is dense in general, is not formed explicitely. \n% It is implicitely given by N and MU.\n%\n% Note that the systems (1) and (2) have an identical input-output\n% mapping.\n%\n% Calling sequence:\n%\n% [M,MU,N,B,C,prm,iprm] = msns_pre(M,N,B,C)\n%\n% Input:\n%\n% M, N n-x-n system matrices; \n% B n-x-m system matrix;\n% C q-x-n system matrix.\n%\n% Output:\n%\n% M permuted matrix M;\n% MU Cholesky factor of (permuted) matrix M;\n% N permuted matrix N;\n% B, C transformed system matrices;\n% prm the permutation that has been used in the first \n% transformation step;\n% iprm the inverse permutation (needed to re-reorder certain data\n% in postprocessing).\n%\n%\n% LYAPACK 1.0 (Thilo Penzl, May 1999)\n\n% Input data not completely checked!\n\nif any(any(imag(M))) | any(any(imag(N))) | any(any(imag(B))) | ...\n any(any(imag(C)))\n disp('WARNING in ''msns_pre'': M, N, B, and C must be real matrices.');\n pause(10);\nend \n\nif norm(M-M','fro')~=0\n error('M is not symmetric!');\nend\n\nif norm(N-N','fro')~=0\n error('N is not symmetric!');\nend\n\n[prm,iprm] = lp_prm(M,N);\n\nM = M(prm,prm);\nN = N(prm,prm);\n\n[MU,t] = chol(M);\n\nif t~=0\n error('M is not (numerically) positive definite!');\nend\n\nif length(B)\n B = MU'\\B(prm,:);\nend\n\nif length(C)\n C = C(:,prm)/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/21-lyapack/lyapack/usfs/msns_pre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7666529767282401}} {"text": "function [xPred, PPred] = KalmanFilterX_PredictState(x,P,F,Q,u,B,Qu)\n% KALMANFILTERX_PREDICTSTATE Perform the discrete-time KF state prediction \n% step, under the assumption of additive process noise.\n%\n% Parameters\n% ----------\n% x: column vector\n% The (xDim x 1) state estimate at the previous time-step.\n% P: matrix\n% The (xDim x xDim) state covariance matrix at the previous\n% time-step.\n% F: matrix\n% An (xDim x xDim) state transition matrix.\n% Q: matrix\n% The (xDim x xDim) process noise covariance matrix.\n% u: column vector, optional\n% An optional (xDim x 1) control input.\n% If omitted, no control input is used.\n% B: matrix, optional\n% An optional (xDim x xDim) control gain matrix.\n% If omitted, B is assumed to be 1.\n% O: matrix, optional\n% An optional (xDim x xDim) control noise covariance\n% matrix. If omitted, Q is assumed to be 0.\n%\n% Returns\n% -------\n% xPred: column vector\n% The (xDim x 1) predicted state estimate.\n% PPred: matrix\n% The (xDim x xDim) predicted state covariance matrix.\n%\n%October 2017 Lyudmil Vladimirov, University of Liverpool.\n \n switch(nargin)\n case(4) \n u = 0;\n B = 0;\n Qu = 0;\n case(5)\n B = 1;\n Qu = 0;\n case(6)\n Qu = 0;\n end\n \n % Compute predicted state mean and covariance\n xPred = F*x + B*u;\n PPred =F*P*F' + Q + B*Qu*B';\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/Kalman/KalmanFilterX/Functions/Prediction/KalmanFilterX_PredictState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7666529731536156}} {"text": "function H=MDexact(M,x0,y0,z0,x,y,z,er,mr,sigma,f)\n%\n% function H=MDexact(M,x0,y0,z0,x,y,z,er,mr,sigma,f)\n%\n% Function MDEXACT calculates the magnetic field in position (x,y,z) for a\n% impulsive source M=I*Am placed in the point (x0,y0,z0). The source is\n% inserted in a medium characterized by dielectric permettivity er,\n% magnetic permeability mr and conductivity sigma. The temporal rule is\n% exp(-i*omega*t).\n%\n% INPUT\n% M = M*l, impulsive value of the magnetic dipole [A*m^2]\n% x0,y0,z0 = coordinates of the dipole [m]\n% x,y,z = point where the field is calculated [m]\n% er = relative dialectric permettivity\n% mr = relative magnetic permeability\n% sigma = conductivity [S/m]\n% f = frequency [Hz]\n%\n% OUTPUT\n% H(1:3,1) = Hx, Hy and Hz with dipole directed along x\n% H(1:3,2) = Hx, Hy and Hz with dipole directed along y\n% H(1:3,3) = Hx, Hy and Hz with dipole directed along z\n\n% change the reference system (index 0 refers to the system in which the\n% dipole is placed in the origin): the script was originally written for a\n% dipole placed in (0,0,0).\nx=x-x0;\ny=y-y0;\nz=z-z0;\n\n% constant\nv0=2.997925e8;\nmu0=pi*4e-7;\neps0=1/(v0^2*mu0);\neps=eps0*er;\nmu=mu0*mr;\nomega=2*pi*f;\ngammaq=j*omega*mu.*(sigma+j*omega*eps);\ngamma=sqrt(gammaq);\n\nH=zeros(3,3);\n\n% dipole along x\nrho=sqrt(y^2+z^2);\nr=sqrt(rho^2+x^2);\nif rho<1e-10,\n cosphi=1;\n sinphi=0;\nelse\n cosphi=z/rho;\n sinphi=-y/rho;\nend\ncostheta=x/r;\nsintheta=sqrt(1-costheta^2);\n\nHr_exact=-j*(M/(2*pi*omega*mu*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;\nHtheta_exact=-j*(M/(4*pi*omega*mu*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;\nHrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;\n\nHx_exact=Hr_exact*costheta-Htheta_exact*sintheta;\nHz_exact=Hrho_exact*cosphi;\nHy_exact=-Hrho_exact*sinphi;\n\nH(1,1)=Hx_exact;\nH(2,1)=Hy_exact;\nH(3,1)=Hz_exact;\n\n% dipole along y\nrho=sqrt(x^2+z^2);\nr=sqrt(rho^2+y^2);\nif rho<1e-10,\n cosphi=1;\n sinphi=0;\nelse\n cosphi=x/rho;\n sinphi=z/rho;\nend\ncostheta=y/r;\nsintheta=sqrt(1-costheta^2);\n\nHr_exact=(M/(2*pi*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;\nHtheta_exact=(M/(4*pi*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;\nHrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;\n\nHy_exact=Hr_exact*costheta-Htheta_exact*sintheta;\nHx_exact=Hrho_exact*cosphi;\nHz_exact=Hrho_exact*sinphi;\n\nH(1,2)=Hx_exact;\nH(2,2)=Hy_exact;\nH(3,2)=Hz_exact;\n\n% dipole along z\nrho=sqrt(x^2+y^2);\nr=sqrt(rho^2+z^2);\nif rho<1e-10,\n cosphi=1;\n sinphi=0;\nelse\n cosphi= x/rho;\n sinphi= y/rho;\nend\ncostheta=z/r;\nsintheta=sqrt(1-costheta^2);\n\nHr_exact=(M/(2*pi*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;\nHtheta_exact=(M/(4*pi*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;\nHrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;\n\nHz_exact=Hr_exact*costheta-Htheta_exact*sintheta;\nHx_exact=Hrho_exact*cosphi;\nHy_exact=Hrho_exact*sinphi;\n\nH(1,3)=Hx_exact;\nH(2,3)=Hy_exact;\nH(3,3)=Hz_exact;\n\n% switch to exp(-i*omega*t)\nH = conj(H);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27558-magnetic-dipole-radiation-through-a-multilayered-structure/MDexact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7666529731536156}} {"text": "function [ element_area, mesh_area ] = area_q4_mesh ( node_num, element_num, ...\n node_xy, element_node )\n\n%*****************************************************************************80\n%\n%% AREA_Q4_MESH computes areas of elements in a Q4 mesh.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 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% Input, real NODE_XY(2,NODE_NUM), the node coordinates.\n%\n% Input, integer ELEMENT_NODE(4,ELEMENT_NUM), lists the\n% nodes that make up each element, in counterclockwise order.\n%\n% Output, real ELEMENT_AREA(ELEMENT_NUM), the element areas.\n%\n% Output, real MESH_AREA, the mesh area.\n%\n for element = 1 : element_num\n for node = 1 : 4\n q4(1:2,node) = node_xy(1:2,element_node(node,element));\n end\n element_area(element) = area_quad ( q4 );\n end\n\n mesh_area = sum ( element_area(1:element_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/quad_mesh/area_q4_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7665534692124898}} {"text": "%Author: Moeti Ncube\n% This code uses the Schwartz-Smith model to calibrate and simulate multiple assets such that:\n% \n% 1. The Calibration and simulation is consistent with the observable forward curve, adjusted for seasonality, at any given date\n% 2. The Calibration and simulation is consistent with the observable ATM volatility at a given date\n% 3. The Calibration and simulation is consistent with the observable correlation structure between the forward curve vectors at \n% a given date\n% \n% \n% In this example, I use four assets: 5x16,2x16,7x8 PJM forward prices and ATM volatilities along with natural gas forward prices \n% and ATM volatilities\n% \n% Calibration of the parameters is done in Excel. By inputing the vectors of Forward and ATM volatilites for each commodity, I \n% can compute the theoretical Schwartz Smith Forward Prices and Standard Deviations for a given maturity. I then use Excel solver \n% to minimize the difference between the observed market values and their theoretical values to obtain the Schwartz-Smith \n% parameters for each commodity. Note this methodology is drastically different from the one described in \"Short Term Variation \n% and Long-Term Dynamics in Commodity Prices\" in which Schwartz and Smith calibrate their model to historical futures prices. \n% Here I calibrate the model to the current forward and volatility curve as well as adjust for seasonality. This procedure is \n% much more practical pricing methodology.\n% \n% The more difficult step was insuring that the correlation between and asset(i) and asset(j) at maturity (t) was consistent \n% with the implied correlation between the forward price vectors. This was done by adjusting the correlation between the \n% short-term factors of commodities at each maturity. The matlab code factors in this adjustment and simulates the 4 commodities \n% in this example to show that the theoretical prices, volatilities, and correlations match up with the observed market data.\n% \n% There is not, to my knowledge, a commodities methodology that incoporates so many market factors across multible commodities \n% into one simulation. The advantages of such a model allows for more accurate modeling of spark spreads and pricing of deals \n% that are dependent on multiple commodities prices. I have included all files, including excel, associated with this calibration \n% and simulation.\n\n\nclear all; close all\n\nfilename = 'SchwartzSmithCalibration.xls';\n\nsim=1000;\nstr={'Fit 5x16';'Fit 2x16';'Fit 7x8';'Fit Fuel'};\niter=length(str);\n\nfor i=1:iter\ndata{i} = xlsread(filename, str{i}, 'B3:M86');\nfwd(:,i)=data{i}(:,1);\n\nkappa(i)=data{i}(1,end);\nsigmax(i)=data{i}(3,end);\nsigmae(i)=data{i}(4,end);\npxe(i)=data{i}(7,end);\nT(:,i)=data{i}(:,3);\nx0(i)=data{i}(8,end);\ne0(i)=data{i}(9,end);\nfor j=1:length(T(:,i))\nve(j,i)=sigmae(i)^2*T(j,i); \nvx(j,i)=(1-exp(-2*kappa(i)*T(j,i)))*(.5*sigmax(i)^2)/kappa(i);\ncovxe(j,i)=(1-exp(-kappa(i)*T(j,i)))*pxe(i)*sigmax(i)*sigmae(i)/kappa(i);\nend\ncorxet(:,i)=covxe(:,i)./sqrt(ve(:,i).*vx(:,i));\nend\n\n%Compute Correlation matrix from observed forward curves\ncmatrix=corrcoef(log(fwd));\n\n\n%Find correlation structures needed to keep observed correlation structure\n%during simulation\nrho(:,1:1)=ones(length(T(:,1)),1);\nfor i=2:iter\nfor j=1:length(T(:,i))\natop1(j,1)=(1-exp(-(kappa(1)+kappa(i))*T(j,i)))*sigmax(1)*sigmax(i)/(kappa(1)+kappa(i));\natop2(j,1)=(1-exp(-kappa(1)*T(j,i)))*pxe(i)*sigmax(1)*sigmae(i)/kappa(1);\natop3(j,1)=(1-exp(-kappa(i)*T(j,i)))*pxe(1)*sigmax(i)*sigmae(1)/kappa(i);\natop4(j,1)=pxe(1)*pxe(i)*sigmae(1)*sigmae(i)*T(j,i);\nabot1(j,1)=sqrt(vx(j,1)+ve(j,1)+2*covxe(j,1));\nabot2(j,1)=sqrt(vx(j,i)+ve(j,i)+2*covxe(j,i));\nacorxy(j,i)=(atop1(j,1)+atop2(j,1)+atop3(j,1)+atop4(j,1))/(abot1(j,1)*abot2(j,1));\nend\nrho(:,i)=cmatrix(1,i)./acorxy(:,i);\nrho=min(rho,1);\nend\n\n\niter2=1;\nrmatrix0=randn(sim,length(data{1}(:,1)));\nfor j=1:iter\n\nfor k=1:length(data{1}(:,1))\n rmatrix{j}(:,k)=rho(k,j)*rmatrix0(:,k)+sqrt(1-rho(k,j)^2)*randn(sim,1);\nend\n\n[tspath,tmpath,tstdpath,tefwd,testdfwd,xpath1,epath1,r1,r2]=schwartzsmithsim(data{j}(22,end),data{j}(1:9,end),data{j}(10:21,end),data{j}(:,3),rmatrix{j},sim);\nspath{j}=tspath;\nmpath{j}=tmpath;\nstdpath{j}=tstdpath;\nefwd{j}=tefwd;\nestdfwd{j}=testdfwd;\nepath{j}=epath1;\nxpath{j}=xpath1;\nlnpath{j}=epath1+xpath1;\nr1path{j}=r1;\nr2path{j}=r2;\n\n\nsubplot(length(str),2,iter2)\ntitle('Market Fwd (blue) vs Sim Fwd (red)')\nhold on\nplot(fwd(:,j))\nplot(mpath{j},'r')\n\nsubplot(length(str),2,iter2+1)\ntitle('Market Vol (blue) vs Sim Vol (red)')\nhold on\nplot(estdfwd{j})\nplot(stdpath{j},'r')\niter2=iter2+2;\nend\n\n\n%Estimate empirical correlation matrix\nfor j=2:iter\nfor i=1:length(data{1}(:,1))\nc(i)=corr(log(spath{1}(:,i)),log(spath{j}(:,i)));\nend\nempc(j)=mean(c);\nend\n\nMarketCorrelations=cmatrix(1,2:end)\nSimCorrelations=empc(2: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/31381-calibration-of-forward-price-volatility-and-correlations-across-multiple-assets/MultiAsset Calibration/MultiAsset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7665519849864239}} {"text": "function points = randomPointInBox3d(box, N, varargin)\n%RANDOMPOINTINBOX3D Generate random point(s) within a 3D box.\n%\n% PTS = randomPointInBox3d(BOX)\n% Generate a random point within the 3D box BOX. The result is a 1-by-3\n% row vector.\n%\n% PTS = randomPointInBox3d(BOX, N)\n% Generates N points within the box. The result is a N-by-3 array.\n%\n% BOX has the format:\n% BOX = [XMIN XMAX YMIN YMAX ZMIN ZMAX].\n%\n% Example\n% % draw points within a box\n% box = [10 40 20 60 30 50];\n% pts = randomPointInBox3d(box, 500);\n% figure(1); hold on;\n% drawBox3d(box);\n% drawPoint3d(pts, '.');\n% axis('equal');\n% axis([0 100 0 100 0 100]);\n% view(3);\n%\n% See also \n% points3d, boxes3d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-06-27, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\nif nargin < 2\n N = 1;\nend\n\n% extract box bounds\nxmin = box(1);\nymin = box(3);\nzmin = box(5);\n\n% compute size of box\ndx = box(2) - xmin;\ndy = box(4) - ymin;\ndz = box(6) - zmin;\n\n% compute point coordinates\npoints = [rand(N, 1)*dx+xmin , rand(N, 1)*dy+ymin , rand(N, 1)*dz+zmin];\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/randomPointInBox3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7664936862721787}} {"text": "function ng = tetrahedron_grid_count ( n )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_GRID_COUNT counts the grid points inside a tetrahedron.\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 N, the number of subintervals.\n%\n% Output, integer NG, the number of grid points.\n%\n ng = ( ( n + 1 ) * ( n + 2 ) * ( n + 3 ) ) / 6;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tetrahedron_grid/tetrahedron_grid_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7664936794556596}} {"text": "function [cost grad] = svmCost(w, X, y, lambda) \n% cost = HingeLoss^2 + lambda*||w||^2 \n% 1 2 3 4 5 step \nyp = X*w; \nidx = find(yp.*y<1); \nerr = yp(idx)-y(idx); \ncost = err'*err + lambda*w'*w; \ngrad = 2*X(idx,:)'*err + 2*lambda*w; \nend ", "meta": {"author": "Grootzz", "repo": "GLCM-SVM", "sha": "51b441d16f8b88040488a846ccaaffa7b9918c82", "save_path": "github-repos/MATLAB/Grootzz-GLCM-SVM", "path": "github-repos/MATLAB/Grootzz-GLCM-SVM/GLCM-SVM-51b441d16f8b88040488a846ccaaffa7b9918c82/src/svmCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.766484678583431}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\n\nfor i = 1:length(lambda_vec)\n lambda = lambda_vec(i);\n theta = trainLinearReg(X, y, lambda);\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nend\n\n% =========================================================================\n\nend\n", "meta": {"author": "xjwhhh", "repo": "AndrewNgMachineLearning", "sha": "d9d8491b315755ea3726bc366d72ba069712c363", "save_path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning", "path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning/AndrewNgMachineLearning-d9d8491b315755ea3726bc366d72ba069712c363/code/machine-learning-ex5/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.9059898210180106, "lm_q1q2_score": 0.766415251443967}} {"text": "function center = triangle_incenter_2d ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_INCENTER_2D computes the incenter of a triangle in 2D.\n%\n% Discussion:\n%\n% The incenter of a triangle is the center of the inscribed circle.\n%\n% The inscribed circle of a triangle is the largest circle that can\n% be drawn inside the triangle.\n%\n% The inscribed circle is tangent to all three sides of the triangle.\n%\n% The angle bisectors of the triangle intersect at the center of the\n% inscribed circle.\n%\n% In geometry, the incenter is often represented by \"I\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983.\n%\n% Parameters:\n%\n% Input, real T(2,3), the triangle vertices.\n%\n% Output, real CENTER(2,1), the incenter.\n%\n dim_num = 2;\n%\n% Compute the length of each side.\n%\n a = sqrt ( sum ( ( t(1:dim_num,1) - t(1:dim_num,2) ).^2 ) );\n b = sqrt ( sum ( ( t(1:dim_num,2) - t(1:dim_num,3) ).^2 ) );\n c = sqrt ( sum ( ( t(1:dim_num,3) - t(1:dim_num,1) ).^2 ) );\n\n perimeter = a + b + c;\n\n if ( perimeter == 0.0 )\n center(1:dim_num,1) = t(1:dim_num,1);\n else\n center(1:dim_num,1) = ( b * t(1:dim_num,1) ...\n + c * t(1:dim_num,2) ...\n + a * t(1:dim_num,3) ) / perimeter;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/triangle_incenter_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7664152464046569}} {"text": "function A = bezout(p,q)\n%BEZOUT Bezout matrix of two univariate polynomials p and q\n%\n% A = bezout(p,q)\n%\n%Both polynomials must be univariate with the same independent variable.\n%The (symmetric) Bezout matrix is singular iff p and q have a root in common.\n%For p or q being interval polynomials, A is an interval matrix.\n%The call\n%\n% A = bezout(p)\n%\n%is the same as A = bezout(p,p') .\n%The definition follows Fiedler, Special matrices and their applications.\n%\n\n% written 02/03/04 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 if nargin==1\n q = p';\n end\n\n if ( size(p.v)>1 ) | ( size(q.v)>1 )\n error('both polynomials must be univariate')\n end\n if p.v~=q.v\n error('both polynomials must depend on the same variable')\n end\n \n np = p.e;\n nq = q.e;\n n = max(np,nq);\n\n A = toeplitz([p.c(np+1) zeros(1,n-1)],[fliplr(p.c) zeros(1,2*n-np-1)]);\n B = toeplitz([q.c(nq+1) zeros(1,n-1)],[fliplr(q.c) zeros(1,2*n-nq-1)]);\n A = flipud( A(:,n+1:end)*B(:,1:n) - B(:,n+1:end)*A(:,1:n) );\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/bezout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7664152325372957}} {"text": "function crf = tapas_physio_crf(t)\n% cardiac response function, as described in \n% \n% Chang, Catie, and Gary H. Glover. �Effects of Model-based Physiological \n% Noise Correction on Default Mode Network Anti-correlations and Correlations.� \n% NeuroImage 47, no. 4 (October 1, 2009): 1448�1459. doi:10.1016/j.neuroimage.2009.05.012.\n%\n% following:\n% Chang, C., Cunningham, J.P., Glover, G.H., 2009. Influence of heart rate \n% on the BOLD signal: the cardiac response function. Neuroimage 44, 857�869.%\n%\n% crf = tapas_physio_crf(t)\n%\n% IN\n% t vector of timepoints\n% OUT\n% crf cardiac response function at sampled time points\n%\n% EXAMPLE\n% % just for visualization\n% t = 0:0.1:100;\n% crf = tapas_physio_crf(t);\n% figure;plot(t,crf);\n%\n% See also tapas_physio_rrf\n\n% Author: Lars Kasper\n% Created: 2013-07-26\n% Copyright (C) 2013 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.\n%\n% This file is part of the 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 .\n\ncrf = 0.6*t.^2.7.*exp(-t/1.6) - 16/sqrt(2*pi*9).*exp(-1/2.*(t-12).^2/9);\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_crf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7664152300021418}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\n\nfor i = 1:length(lambda_vec),\n lambda = lambda_vec(i);\n theta = trainLinearReg(X, y, lambda);\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nend;\n\n% =========================================================================\n\nend\n", "meta": {"author": "rieder91", "repo": "MachineLearning", "sha": "f6708f216326cb5c9e9e5c3afc912060bfa10486", "save_path": "github-repos/MATLAB/rieder91-MachineLearning", "path": "github-repos/MATLAB/rieder91-MachineLearning/MachineLearning-f6708f216326cb5c9e9e5c3afc912060bfa10486/Exercise 5/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.9059898121338505, "lm_q1q2_score": 0.7664152157779055}} {"text": "function R = rotx(alpha)\n\n % ROTX computes a rotation along the x axis (rotation matrix).\n %\n % FORMAT: R = rotx(alpha) \n %\n % INPUT: - alpha = angle in radians\n %\n % OUTPUT: - R = [3 * 3] rotation matrix along x axis\n %\n % Authors: Daniele Pucci, Marie Charbonneau, Gabriele Nava\n % \n % all authors are with the Italian Istitute of Technology (IIT)\n % email: name.surname@iit.it\n %\n % Genoa, Dec 2017\n %\n\n %% --- Initialization ---\n\n\n R = [1, 0, 0;\n 0, cos(alpha), -sin(alpha);\n 0, sin(alpha), cos(alpha)];\n\nend\n", "meta": {"author": "robotology", "repo": "whole-body-controllers", "sha": "90ff965a523f0a120e6a8981b71326c1485e7742", "save_path": "github-repos/MATLAB/robotology-whole-body-controllers", "path": "github-repos/MATLAB/robotology-whole-body-controllers/whole-body-controllers-90ff965a523f0a120e6a8981b71326c1485e7742/library/matlab-wbc/+wbc/rotx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7663607532449}} {"text": "function [newnodes, len]=polylinesimplify(nodes, minangle)\n%\n% [newnodes, len]=polylinesimplify(nodes, minangle)\n%\n% Calculate a simplified polyline by removing nodes where two adjacent\n% segment have an angle less than a specified limit\n%\n% author: Qianqian Fang (q.fang at neu.edu)\n%\n% input:\n% node: an N x 3 array defining each vertex of the polyline in\n% sequential order\n% minangle:(optional) minimum segment angle in radian, if not given, use\n% 0.75*pi\n%\n% output:\n% newnodes: the updated node list; start/end will not be removed\n% len: the length of each segment between the start and the end points\n%\n%\n% -- this function is part of brain2mesh toolbox (http://mcx.space/brain2mesh)\n% License: GPL v3 or later, see LICENSE.txt for details\n%\n\nif(nargin<2)\n minangle=0.75*pi;\nend\n\nv=segvec(nodes(1:end-1,:), nodes(2:end,:));\nang=acos(max(min(sum(-v(1:end-1,:).*(v(2:end,:)),2),1),-1));\n\nnewnodes=nodes;\nnewv=v;\nnewang=ang;\n\nidx=find(newang1);\n newang(idx0-1)=acos(sum(-newv(idx0-1,:).*(newv(idx0,:)),2));\n idx=find(newang1)\n len=newnodes(1:end-1,:) - newnodes(2:end,:);\n len=sqrt(sum(len.*len,2));\nend\n\nfunction v=segvec(n1, n2)\n\nv=n2-n1;\nnormals=sqrt(sum(v.*v,2));\nv=v./repmat(normals,1,size(v,2));", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/polylinesimplify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7663607346875929}} {"text": "function [ x, seed ] = sphere_unit_sample_3d_2 ( seed )\n\n%*****************************************************************************80\n%\n%% SPHERE_UNIT_SAMPLE_3D_2 is a BAD method for sampling the unit sphere in 3D.\n%\n% Discussion:\n%\n% The unit sphere in 3D satisfies:\n%\n% X * X + Y * Y + Z * Z = 1\n%\n% Points on the unit sphere have coordinates ( PHI, THETA ) where\n% PHI varies from 0 to PI, and THETA from 0 to 2 PI, so that:\n%\n% x = cos ( theta ) * sin ( phi )\n% y = sin ( theta ) * sin ( phi )\n% z = cos ( phi )\n%\n% This routine implements a sampling of the sphere that simply\n% picks PHI and THETA uniformly at random from their ranges.\n% This is a uniform sampling on the cylinder, but it is NOT\n% a uniform sampling on the sphere. I implement it here just\n% so I can run some tests against the code in SPHERE_UNIT_SAMPLE_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(3), the sample point.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n dim_num = 3;\n\n [ phi, seed ] = r8_uniform_01 ( seed );\n phi = pi * phi;\n\n [ theta, seed ] = r8_uniform_01 ( seed );\n theta = 2.0 * pi * theta;\n\n x(1) = cos ( theta ) * sin ( phi );\n x(2) = sin ( theta ) * sin ( phi );\n x(3) = cos ( phi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_unit_sample_3d_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7663393177118348}} {"text": "function Ic = adjacency2incidence(A)\n\n% adjacency2incidence - convert an adjacency matrix to an incidence matrix\n%\n% Ic = adjacency2incidence(A);\n%\n% A(i,j) = 1 iff (i,j) is an edge of the graph.\n% For each edge number k of the graph linking (i,j)\n% Ic(i,k)=1 and Ic(j,k)=-1 \n%\n% Ic is a sparse matrix.\n% Ic is also known as the graph gradient.\n%\n% Copyright (c) 2006 Gabriel Peyre\n\n%% compute list of edges\n[i,j,s] = find(sparse(A));\nI = find(i<=j);\ni = i(I);\nj = j(I);\n% number of edges\nn = length(i);\n% number of vertices\nnverts = size(A,1);\n\n%% build sparse matrix\ns = [ones(n,1); -ones(n,1)];\nis = [(1:n)'; (1:n)'];\njs = [i(:); j(:)];\nIc = sparse(is,js,s,n,nverts);\nIc = Ic';\n\n% fix self-linking problem (0)\na = find(i==j);\nif not(isempty(a))\n for t=a'\n Ic(i(t),t) = 1;\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_graph/adjacency2incidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.766339311791906}} {"text": "%% Example 4.5: Solution of the Ornstein–Uhlenbeck process\n%\n% Copyright: \n% 2018 - Simo Särkkä and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%% Simulate trajectories from the OU process\n\n if exist('rng') % Octave doesn't have rng\n rng(10,'twister')\n else\n randn('state',1)\n end\n \n lambda = 0.5;\n q = 1;\n dt = 0.01;\n T = (0:dt:1);\n x0 = 4;\n M = exp(-lambda*T)*x0;\n P = q/(2*lambda)*(1 - exp(-2*lambda*T));\n\n XX = zeros(50,length(T));\n for n=1:size(XX,1)\n x = x0;\n for k=1:length(T)\n XX(n,k) = x;\n x = x - lambda * x * dt + sqrt(dt)*randn;\n end\n end\n \n \n figure(1); clf; hold on\n \n % Shade the 95% quantiles\n fill([T fliplr(T)],[M+1.96*sqrt(P) fliplr(M-1.96*sqrt(P))],1, ...\n 'FaceColor',[.9 .9 .9],'EdgeColor',[.9 .9 .9])\n \n % Plot realizations\n h1 = plot(T,XX,'-','Color',[.5 .5 .5],'LineWidth',0.5);\n \n % Plot mean and quantiles\n h2 = plot(T,M,'k-','LineWidth',1);\n h34 = plot(T,M+1.96*sqrt(P),'--k', ...\n T,M-1.96*sqrt(P),'--k','LineWidth',0.7);\n \n %set(h(1:3),'Linewidth',2)\n \n legend([h2(1) h34(1) h1(1)],'Mean','95\\% quantiles','Realizations')\n xlabel('Time, $t$'); ylabel('$x(t)$')\n \n ylim([0 5])\n box on\n set(gca,'Layer','Top')\n ", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch04_ex05_ou_process.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7663393008448173}} {"text": "close all; clear all; clc;\nrng('default');\nresize_images = true;\n\ntarget.psnr = 35;\n% target mean square error\ntarget.mse = 255^2 * 10^(-target.psnr/10);\nimage_width = 42;\nimage_height = 48;\nnum_pixels = image_width * image_height;\n% target sum of squared errors\ntarget.sse = num_pixels * target.mse;\n% target residual norm\ntarget.rnorm = sqrt(target.sse);\nfprintf('Target PSNR: %.2f dB\\n', target.psnr);\nfprintf('Target Mean Square Error: %.2f\\n', target.mse);\nfprintf('Target Root Mean Square Error: %.2f\\n', sqrt(target.mse));\nfprintf('Target Residual Norm: %.2f\\n', target.rnorm);\n\nN = num_pixels;\nredundancy_factor = 8;\nD = redundancy_factor * N;\n\nA = spx.dict.simple.gaussian_mtx(N, D);\ndc_atom = (1/sqrt(N)) * ones(N, 1);\n% throw away one original atom and replace with DC.\nA = [dc_atom A(:, 1:D-1)];\ndictionary = spx.dict.MatrixOperator(A);\n\n\nyf = spx.data.image.YaleFaces();\nyf.load();\nfprintf('\\n Resizing images:\\n');\ntstart = tic;\nyf.resize_all(42, 48);\nimages = yf.ImageData;\n[~, S] = size(images);\n%images = yf.get_subject_images_resized(1, 42, 48);\nelapsed = toc(tstart);\nfprintf('Time taken: %.2f seconds \\n', elapsed);\nrepresentations = zeros(D, S);\nelapsed_times = zeros(1, S);\nsupport_sizes = zeros(1, S);\nres_norms = zeros(1, S);\npsnrs = zeros(1, S);\nfprintf('Total images: %d\\n', S);\nfor s=1:S\n Y = images(:, s);\n solver = spx.pursuit.single.OrthogonalMatchingPursuit(dictionary);\n solver.MaxResNorm = target.rnorm;\n solver.Verbose = true;\n fprintf('sparsifying image: %d\\n', s);\n tstart = tic;\n result = solver.solve_qr(Y);\n elapsed = toc(tstart);\n fprintf('Time taken: %.2f seconds \\n', elapsed);\n fprintf('Support size: %d\\n', result.iterations);\n support_sizes(s) = result.iterations;\n elapsed_times(s) = elapsed;\n representations(:, s) = result.z;\n res_norms(s) = result.rnorm;\n sse = result.rnorm^2;\n mse = sse / num_pixels;\n psnr = 10 * log10(255^2 / mse);\n psnrs(s) = psnr;\n fprintf('PSNR : %.3f dB\\n', psnr);\n if mod(s, 100) == 0\n % We wish to save intermediate data too\n save('omp_representations', 'representations');\n save('omp_stats', 'elapsed_times', 'support_sizes', 'res_norms', 'psnrs', 's');\n end\nend\n% final saving of all data.\nsave('bin/omp_dictionary', 'dictionary', 'N', 'D');\nsave('bin/omp_images', 'images');\nsave('bin/omp_representations', 'representations');\nsave('bin/omp_stats', 'elapsed_times', 'support_sizes', 'res_norms', 'psnrs', 'S');\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/data/yale_faces/ex_omp_approx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7663393004877093}} {"text": "function [x, funVal, ValueL]=LeastC(A, y, z, opts)\n%\n%%\n% Function LeastC\n% Least Squares Loss with the L1 ball constraint (also known as Lasso)\n%\n%% Problem\n%\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2\n% s.t. ||x||_1 <= z\n%\n% By default, rsL2=0.\n% When rsL2 is nonzero, this correspons the well-know elastic net.\n%\n%% Input parameters:\n%\n% A- Matrix of size m x n\n% A can be a dense matrix\n% a sparse matrix\n% or a DCT matrix\n% y - Response vector (of size mx1)\n% z - Radius of the L1 ball (z >0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- Solution\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 Jun Liu, and Jieping Ye\n%\n% You are suggested to first read the Manual.\n%\n% For any problem, please contact with Jun Liu via j.liu@asu.edu\n%\n% Last modified on February 18, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Efficient Euclidean Projections\n% in Linear Time, ICML 2009.\n%\n% [2] Jun Liu and Jieping Ye, Sparse Learning with Efficient Euclidean\n% Projections onto the L1 Ball, Technical Report ASU, 2008.\n%\n%% Related functions\n%\n% sll_opts, initFactor, pathSolutionLeast,\n% LeastR, nnLeastR, nnLeastC,\n% eplb\n%\n%%\n\n%% Verify and initialize the parameters\n%%\n\n% Verify the number of input parameters\nif (nargin <3)\n error('\\n Inputs: A, y and z should be specified!\\n');\nelseif (nargin==3)\n opts=[];\nend\n\n% Get the size of the matrix A\n[m,n]=size(A);\n\n% Verify the length of y\nif (length(y) ~=m)\n error('\\n Check the length of y!\\n');\nend\n\n% Verify the value of z\nif (z<=0)\n error('\\n z should be positive!\\n');\nend\n\n% run sll_opts to set default values (flags)\nopts=sll_opts(opts);\n\n%% Detailed initialization\n%% Normalization\n\n% Please refer to sll_opts for the definitions of mu, nu and nFlag\n%\n% If .nFlag =1, the input matrix A is normalized to\n% A= ( A- repmat(mu, m,1) ) * diag(nu)^{-1}\n%\n% If .nFlag =2, the input matrix A is normalized to\n% A= diag(nu)^{-1} * ( A- repmat(mu, m,1) )\n%\n% Such normalization is done implicitly\n% This implicit normalization is suggested for the sparse matrix\n% but not for the dense matrix\n%\n\nif (opts.nFlag~=0)\n if (isfield(opts,'mu'))\n mu=opts.mu;\n if(size(mu,2)~=n)\n error('\\n Check the input .mu');\n end\n else\n mu=mean(A,1);\n end\n\n if (opts.nFlag==1)\n if (isfield(opts,'nu'))\n nu=opts.nu;\n if(size(nu,1)~=n)\n error('\\n Check the input .nu!');\n end\n else\n nu=(sum(A.^2,1)/m).^(0.5); nu=nu';\n end\n else % .nFlag=2\n if (isfield(opts,'nu'))\n nu=opts.nu;\n if(size(nu,1)~=m)\n error('\\n Check the input .nu!');\n end\n else\n nu=(sum(A.^2,2)/n).^(0.5);\n end\n end\n\n ind_zero=find(abs(nu)<= 1e-10); nu(ind_zero)=1;\n % If some values in nu is typically small, it might be that,\n % the entries in a given row or column in A are all close to zero.\n % For numerical stability, we set the corresponding value to 1.\nend\n\nif (~issparse(A)) && (opts.nFlag~=0)\n fprintf('\\n -----------------------------------------------------');\n fprintf('\\n The data is not sparse or not stored in sparse format');\n fprintf('\\n The code still works.');\n fprintf('\\n But we suggest you to normalize the data directly,');\n fprintf('\\n for achieving better efficiency.');\n fprintf('\\n -----------------------------------------------------');\nend\n\n%% Starting point initialization\n\n% compute AT y\nif (opts.nFlag==0)\n ATy=A'*y;\nelseif (opts.nFlag==1)\n ATy=A'*y - sum(y) * mu'; ATy=ATy./nu;\nelse\n invNu=y./nu; ATy=A'*invNu-sum(invNu)*mu';\nend\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1);\nelse\n if isfield(opts,'x0')\n x=opts.x0;\n if (length(x)~=n)\n error('\\n Check the input .x0');\n end\n else\n x=ATy; % if .x0 is not specified, we use ratio*ATy,\n % where ratio is a positive value\n end\nend\n\n% compute A x\nif (opts.nFlag==0)\n Ax=A* x;\nelseif (opts.nFlag==1)\n invNu=x./nu; mu_invNu=mu * invNu;\n Ax=A*invNu -repmat(mu_invNu, m, 1);\nelse\n Ax=A*x-repmat(mu*x, m, 1); Ax=Ax./nu;\nend\n\nif (opts.init==0) % If .init=0, we set x=ratio*x by \"initFactor\"\n % Please refer to the function initFactor for detail\n\n x_norm=sum(abs(x)); % L1 norm of x\n x_2norm=x'*x; % squared two norm of x\n if x_norm>=1e-6\n ratio=initFactor(x_norm, Ax, y, z,'LeastC', rsL2, x_2norm);\n x=ratio*x; Ax=ratio*Ax;\n end\nend\n\n%% The main program\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\n%% The Armijo Goldstein line search schemes\nif (opts.lFlag==0)\n\n L=1 + rsL2;\n % We assume that the maximum eigenvalue of A'A is over 1\n\n % assign xp with x, and Axp with Ax.\n % xxp=x - xp\n xp=x; Axp=Ax; xxp=zeros(n,1);\n\n % alphap and alpha are used for computing the weight in forming search point\n alphap=0; alpha=1;\n\n % lambda0 is a guess of the root in the Euclidean projection\n lambda0=0;\n\n for iterStep=1:opts.maxIter\n % --------------------------- step 1 ---------------------------\n % compute search point s based on xp and x (with beta)\n beta=(alphap-1)/alpha; s=x + beta* xxp;\n\n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n\n % compute the gradient (g) at s\n As=Ax + beta* (Ax-Axp);\n\n % compute AT As\n if (opts.nFlag==0)\n ATAs=A'*As;\n elseif (opts.nFlag==1)\n ATAs=A'*As - sum(As) * mu'; ATAs=ATAs./nu;\n else\n invNu=As./nu; ATAs=A'*invNu-sum(invNu)*mu';\n end\n\n % obtain the gradient g\n g=ATAs-ATy + rsL2 * s;\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and project v onto the L1 ball\n v=s-g/L;\n\n % projection\n [x, lambda, zf_step]=eplb(v, n, z, lambda0);\n lambda0=lambda;\n\n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n\n % compute A x\n if (opts.nFlag==0)\n Ax=A* x;\n elseif (opts.nFlag==1)\n invNu=x./nu; mu_invNu=mu * invNu;\n Ax=A*invNu -repmat(mu_invNu, m, 1);\n else\n Ax=A*x-repmat(mu*x, m, 1); Ax=Ax./nu;\n end\n\n Av=Ax -As;\n r_sum=v'*v; l_sum=Av'*Av;\n \n if (r_sum <=1e-20)\n bFlag=1; % this shows that, the gradient step makes little improvement\n break;\n end\n\n % the condition is ||Av||_2^2 <= (L - rsL2) * ||v||_2^2\n if(l_sum <= r_sum * (L-rsL2))\n break;\n else\n L=max(2*L, l_sum/r_sum + rsL2);\n % fprintf('\\n L=%5.6f',L);\n end\n end\n\n ValueL(iterStep)=L;\n\n % --------------------------- step 3 ---------------------------\n % update alpha and alphap, and check whether converge\n alphap=alpha; alpha= (1+ sqrt(4*alpha*alpha +1))/2;\n\n xxp=x-xp; Axy=Ax-y;\n funVal(iterStep)=Axy' * Axy/2 + rsL2/2 * x'*x;\n \n if (bFlag)\n % fprintf('\\n The program terminates as the gradient step changes the solution very small.');\n break;\n end\n\n switch(opts.tFlag)\n case 0\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <= opts.tol)\n break;\n end\n end\n case 1\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <=...\n opts.tol* funVal(iterStep-1))\n break;\n end\n end\n case 2\n if ( funVal(iterStep)<= opts.tol)\n break;\n end\n case 3\n norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp); norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol * max(norm_xp,1))\n break;\n end\n case 5\n if iterStep>=opts.maxIter\n break;\n end\n end\n end % end of .lFlag=0\nend\n\n\n%% Adaptive Line Search\n\n% we set gamma_0 to the L that is appropriate for the starting point\n% opts.x0\n\nif (opts.lFlag==1)\n\n L=1 + rsL2;\n % We assume that the maximum eigenvalue of A'A is over 1\n\n lambda0=0;\n % lambda0 is a guess of the root in the Euclidean projection\n\n gamma=1;\n % we shall set the value of gamma = L,\n % and L is appropriate for the starting point\n\n xp=x; Axp=Ax;\n % store x and Ax\n xxp=zeros(n,1);\n % the difference of x and xp\n\n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n\n % We begin the adaptive line search in the following\n %\n % Note that, in the line search, L and beta are changing\n\n for iterStep=1:opts.maxIter\n\n ATAxp=ATAx;\n % store ATAx to ATAxp\n\n if (iterStep~=1)\n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n end\n\n %--------- Line Search for L begins\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp;\n As=Ax + beta* (Ax-Axp);\n ATAs=ATAx + beta* (ATAx-ATAxp);\n % compute the search point s, A * s, and A' * A * s\n else\n alpha= (-1+ sqrt(5)) / 2;\n beta=0; s=x; As=Ax; ATAs=ATAx;\n end\n\n g=ATAs-ATy + rsL2 * s;\n % compute the gradient g\n\n v=s-g/L;\n % a gradient step based on the search point s\n\n % projection\n [xnew, lambda, zf_step]=eplb(v, n, z, lambda0);\n lambda0=lambda;\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n\n % compute A xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n\n Av=Axnew -As;\n r_sum=v'*v; l_sum=Av'*Av + v'*v * rsL2;\n \n if (r_sum <=1e-20)\n bFlag=1; % this shows that, the gradient step makes little improvement\n break;\n end\n\n % the condition is ||Av||_2^2 + rsL2 * ||v||_2^2<= L* ||v||_2^2\n if(l_sum <= r_sum * L)\n break;\n else\n L=max(2*L, l_sum/r_sum);\n % fprintf('\\n L=%5.6f',L);\n end\n end\n %--------- Line Search for L ends\n\n gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n\n ValueL(iterStep)=L;\n % store values for L\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; x=xnew; xxp=x-xp;\n Axp=Ax; Ax=Axnew;\n % update x and Ax with xnew and Axnew\n\n Axy=Ax-y;\n funVal(iterStep)=Axy' * Axy/2 + rsL2/2 * x'*x;\n % compute function value\n \n if (bFlag)\n % fprintf('\\n The program terminates as the gradient step changes the solution very small.');\n break;\n end\n\n switch(opts.tFlag)\n case 0\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <= opts.tol)\n break;\n end\n end\n case 1\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <=...\n opts.tol* funVal(iterStep-1))\n break;\n end\n end\n case 2\n if ( funVal(iterStep)<= opts.tol)\n break;\n end\n case 3\n norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp); norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol * max(norm_xp,1))\n break;\n end\n case 5\n if iterStep>=opts.maxIter\n break;\n end\n end\n end\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_SLEP/SLEP/functions/L1/L1C/LeastC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.766288231399816}} {"text": "clear all; close all; clc\n\nn=100;\nL=20; x=linspace(-L,L,n); y=x;\n[X,Y]=meshgrid(x,y);\n\nXd=[];\nfor j=1:100\nu=tanh(sqrt(X.^2+Y.^2)).*cos(angle(X+i*Y)-(sqrt(X.^2+Y.^2))+j/10);\nf=exp(-0.01*(X.^2+Y.^2));\nuf=u.*f;\nXd(:,j)=reshape(uf,n^2,1);\npcolor(x,y,uf), shading interp, colormap(hot), caxis([-1 1]), drawnow \nend\n\n\n\n%%\n[U,S,V]=svd(Xd,0);\n\nfigure(2)\nsubplot(4,1,3)\nplot(100*diag(S)/sum(diag(S)),'ko','Linewidth',[2])\nsubplot(4,1,4)\nsemilogy(100*diag(S)/sum(diag(S)),'ko','Linewidth',[2])\nsubplot(2,1,1)\nplot(V(:,1:4),'Linewidth',[2])\nlegend('mode1','mode2','mode3','mode4')\nset(gca,'Fontsize',[15],'Xtick',[0 20 40 60 80 100])\nsubplot(4,1,3), set(gca,'Fontsize',[15],'Ylim',[0 60],'Ytick',[0 20 40 60],'Xlim',[0 40],'Xtick',[0 10 20 30 40])\nsubplot(4,1,4), set(gca,'Fontsize',[15],'Ylim',[10^(-20) 10^2],'Ytick',[10^(-20) 10^(-10) 10^2],'Xlim',[0 40],'Xtick',[0 10 20 30 40])\n\nfigure(3)\nfor j=1:4\n subplot(4,4,j)\n mode=reshape(U(:,j),n,n);\n pcolor(X,Y,mode), shading interp,caxis([-0.03 0.03]), colormap(gray)\n axis off\nend\n\n%%\n\nfigure(11)\nu=tanh(sqrt(X.^2+Y.^2)).*cos(angle(X+i*Y)-(sqrt(X.^2+Y.^2)));\nf=exp(-0.01*(X.^2+Y.^2));\nuf=u.*f;\nsubplot(3,3,1),pcolor(x,y,uf), shading interp, caxis([-1 1]), axis off\nsubplot(3,3,2),pcolor(x,y,abs(uf)), shading interp, caxis([-1 1]), axis off \nsubplot(3,3,3),pcolor(x,y,uf.^5), shading interp, caxis([-1 1]), axis off \ncolormap(gray)\n\n\n\n\n%% TRANSLATION\nfigure(5)\nn=200; L=20; x=linspace(-L,L,n); y=x; % space\nm=41; T=10; t=linspace(0,T,m); % time\nc=3; % wave speed\n\nX=[]; \nfor j=1:m\n X(:,j)=exp(-(x+15-c*t(j)).^2).'; % data snapshots\nend\n[U,S,V]=svd(X); % SVD decomposition\n\n\n%%\nfigure(6)\nsubplot(2,2,1)\nwaterfall(x,t,X.'),colormap([0 0 0])\nview(20,75)\nset(gca,'Xlim',[-20 20],'Xtick',[-20 -10 0 10 20],'Ylim',[0 10], ...\n 'Ytick',[0 5 10],'Zlim',[0 1],'Ztick',[0 1],'Fontsize',[12])\n\n\n[U2,S2,V2]=svd(X);\n\nsubplot(4,2,2)\nplot(100*diag(S2)/sum(diag(S2)),'ko','Linewidth',[2])\nset(gca,'Xlim',[0 40],'Xtick',0:10:40,'Ylim',[0 8],'Ytick',[0 4 8])\nsubplot(4,2,4)\nsemilogy(100*diag(S2)/sum(diag(S2)),'ko','Linewidth',[2])\ngrid on\nset(gca,'Xlim',[0 40],'Xtick',0:10:40,'Ylim',[10^(-3) 2*10^1],'Ytick',[10^(-3) 10^(-2) 10^(-1) 10^0 10^1])\n\nfigure(8)\nsubplot(2,1,1)\nplot(x,U2(:,1:4),'Linewidth',[2]);\nlegend('mode1','mode2','mode3','mode4','Location','SouthEast')\nset(gca,'Fontsize',[15],'Ylim',[-0.15 0.15],'Ytick',[-0.15 0 0.15])\nsubplot(2,1,2)\nplot(t,V2(:,1:4),'Linewidth',[2])\nset(gca,'Fontsize',[15],'Ylim',[-.3 0.3],'Ytick',[-0.3 0 0.3])\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/CH12/old_extra/POD_invariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.76628822939542}} {"text": "function C=HestonCall(St,K,r,T,vt,kap,th,sig,rho,lda)\n%--------------------------------------------------------------------------\n%PURPOSE: computes the option price using Heston's model.\n%--------------------------------------------------------------------------\n%USAGE: C=HestonCall(St,K,r,sig,T,vt,kap,th,lda,rho)\n%--------------------------------------------------------------------------\n%INPUT: St - scalar or vector, price of underlying at time t\n% K - scalar or vector, strike price\n% r - scalar or vector, continuously compound risk free rate expressed as a\n% positive decimal number.\n% sig- scalar or vector, volatility of the volatility of the\n% underlying(same time units as for r) \n% T - scalar or vector, time to maturity (same time units as for r)\n% vt - scalar or vector, instantaneous volatility\n% kap - scalar or vector, is the rate at which vt reverts to th\n% th - scalar or vector, is the long vol, or long run average price\n% volatility; as t tends to infinity, the expected value of ?t tends to ? \n% lda - scalar or vector, risk premium for volatility\n% rho - scalar or vector, correlation between underlying and\n% volatility (rho<0 generates the leverage effect)\n%--------------------------------------------------------------------------\n%OUTPUT: C - scalar or vector, Heston's model call option price\n%--------------------------------------------------------------------------\n\n\ndphi=0.01;\nmaxphi=50;\nphi=(eps:dphi:maxphi)';\n\n%f1 = CF_SVj(log(St),vt,T,r,kap*th,0.5,kap+lda-rho*sig,rho,sig,phi);\n%P1 = 0.5+(1/pi)*sum(real(exp(-i*phi*log(K)).*f1./(i*phi))*dphi);\n%f2 = CF_SVj(log(St),vt,T,r,kap*th,-0.5,kap+lda,rho,sig,phi);\n%P2 = 0.5+(1/pi)*sum(real(exp(-i*phi*log(K)).*f2./(i*phi))*dphi);\n%C = St*P1 -K*exp(-r*T)*P2;\n\n\nf1 = CF_SVj(log(St),vt,T,0,kap*th,0.5,kap+lda-rho*sig,rho,sig,phi);\nP1 = 0.5+(1/pi)*sum(real(exp(-i*phi*log(K)).*f1./(i*phi))*dphi);\nf2 = CF_SVj(log(St),vt,T,0,kap*th,-0.5,kap+lda,rho,sig,phi);\nP2 = 0.5+(1/pi)*sum(real(exp(-i*phi*log(K)).*f2./(i*phi))*dphi);\nC = St*P1 -K*exp(-r*T)*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/29446-heston-model-calibration-and-simulation/HestonCalibration/HestonCall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7662707942919615}} {"text": "function [X_t,Mu_t,Sig_t]=OUstep(X_0,t,Mu,Th,Sig)\n\n[NumSimul,N]=size(X_0);\n\n% location\nExpM=expm(-Th*t);\n\nMu_t = repmat((Mu-ExpM*Mu)',NumSimul,1) + X_0*ExpM';\n\n% scatter\nTsT=kron(Th,eye(N))+kron(eye(N),Th);\n\nVecSig=reshape(Sig,N^2,1);\nVecSig_t=inv(TsT)*(eye(N^2)-expm(-TsT*t))*VecSig;\nSig_t=reshape(VecSig_t,N,N);\nSig_t=(Sig_t+Sig_t')/2;\n\nEps=mvnrnd(zeros(N,1),Sig_t,NumSimul);\n\nX_t=Mu_t+Eps;\nMu_t=mean(Mu_t,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/24120-review-of-statistical-arbitrage-cointegration-and-multivariate-ornstein-uhlenbeck/MultivariateOUnCointegration/Theory/OUstep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.766270789853252}} {"text": "#!/usr/bin/env octave\n%% Machine Learning Online Class - Exercise 2: Logistic Regression\n%\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the second part\n% of the exercise which covers regularization with logistic regression.\n%\n% You will need to complete the following functions in this exericse:\n%\n% sigmoid.m\n% costFunction.m\n% predict.m\n% costFunctionReg.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%% Load Data\n% The first two columns contains the exam scores and the third column\n% contains the label.\n\ndata = load('ex2data2.txt');\nX = data(:, [1, 2]); y = data(:, 3);\n\nplotData(X, y);\n\n% Put some labels \nhold on;\n\n% Labels and Legend\nxlabel('Microchip Test 1')\nylabel('Microchip Test 2')\n\n% Specified in plot order\nlegend('y = 1', 'y = 0')\nhold off;\n\n\n%% =========== Part 1: Regularized Logistic Regression ============\n% In this part, you are given a dataset with data points that are not\n% linearly separable. However, you would still like to use logistic \n% regression to classify the data points. \n%\n% To do so, you introduce more features to use -- in particular, you add\n% polynomial features to our data matrix (similar to polynomial\n% regression).\n%\n\n% Add Polynomial Features\n\n% Note that mapFeature also adds a column of ones for us, so the intercept\n% term is handled\nX = mapFeature(X(:,1), X(:,2));\n\n% Initialize fitting parameters\ninitial_theta = zeros(size(X, 2), 1);\n\n% Set regularization parameter lambda to 1\nlambda = 1;\n\n% Compute and display initial cost and gradient for regularized logistic\n% regression\n[cost, grad] = costFunctionReg(initial_theta, X, y, lambda);\n\nfprintf('Cost at initial theta (zeros): %f\\n', cost);\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n%% ============= Part 2: Regularization and Accuracies =============\n% Optional Exercise:\n% In this part, you will get to try different values of lambda and \n% see how regularization affects the decision coundart\n%\n% Try the following values of lambda (0, 1, 10, 100).\n%\n% How does the decision boundary change when you vary lambda? How does\n% the training set accuracy vary?\n%\n\n% Initialize fitting parameters\ninitial_theta = zeros(size(X, 2), 1);\n\n% Set regularization parameter lambda to 1 (you should vary this)\nlambda = 1;\n\n% Set Options\noptions = optimset('GradObj', 'on', 'MaxIter', 400);\n\n% Optimize\n[theta, J, exit_flag] = ...\n\tfminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);\n\n% Plot Boundary\nplotDecisionBoundary(theta, X, y);\nhold on;\ntitle(sprintf('lambda = %g', lambda))\n\n% Labels and Legend\nxlabel('Microchip Test 1')\nylabel('Microchip Test 2')\n\nlegend('y = 1', 'y = 0', 'Decision boundary')\nhold off;\n\n% Compute accuracy on our training set\np = predict(theta, X);\n\nfprintf('Train Accuracy: %f\\n', mean(double(p == y)) * 100);\n\npause;\n", "meta": {"author": "SaveTheRbtz", "repo": "ml-class", "sha": "74ce689e21e9f3ca184e60313351b31112e5dd56", "save_path": "github-repos/MATLAB/SaveTheRbtz-ml-class", "path": "github-repos/MATLAB/SaveTheRbtz-ml-class/ml-class-74ce689e21e9f3ca184e60313351b31112e5dd56/ex2/ex2_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8856314783461302, "lm_q1q2_score": 0.7662696771977292}} {"text": "% Sympoly demos\n\n%% Various ways to create a sympoly\n\n% A scalar (zero) sympoly\nz = sympoly;\n\n% Scalar sympolys 'x', 'y', 'u', 'v' created in the current workspace\nsympoly x y u v\n\n% A sympoly (identity matrix) array. The numeric element format is\n% specified by the command window format style.\nformat short g\nayuh = sympoly(eye(3));\n\n% Use deal to replicate a sympoly into several \n[a,b] = deal(sympoly);\n\n% Deal can also create a sympoly array\nS(1:2) = deal(sympoly('x'));\n\n% As can repmat\nR = repmat(sympoly('x'),2,3);\n\nwhos\n\n%% Arithmetic between sympolys, add, subtract, multiply, divide.\n\n% add 1 to x\n1 + x\n\n%%\n\n% double times a sympoly\n2*y\n\n%%\n\n% subtraction, and a simple power\n(x - y)^2\n\n%%\n\n% More complex expressions\n(x - 2*y)^3/x + sqrt(y^3)\n\n%% Synthetic division\n[quotient,remainder] = syndivide(x^2+2*x-1,x+1)\n\n%% Arrays of sympolys\n[x , y ; 1 , x+y]\n\n%%\n\n% Arrays of sympolys\nv = [1 x y x+y]\n\n%% matrix multiplication\nA = v*v'\nB = v'*v\n%% Selective extraction of terms\n% The second term\nterms(A,2)\n\n%%\nterms(A,x^2,'extract')\n\n%%\n% Delete a term\np = (1 + x^2 + x^7)^3\nterms(p,x^2,'delete')\n\n%% Selective deletion of terms\nB = terms(A,x,'extract')\n\n%%\n% Operations on arrays\nsympoly lambda\n(rand(3) - lambda*eye(3))\n\n%% Even eigenvalues, using det, then roots \nroots(det(hilb(4) - lambda*eye(4)))\n\n%% Sum on any dimension\nsum(v,2)\n\n%% And prod\nprod(A(:))\n\n%% Orthogonal polynomials from a variety of familes\n\n% 3rd and 4th order Legendre polynomials\np3 = orthpoly(3,'legendre')\np4 = orthpoly(4,'legendre')\n\n%% \n\n% Orthogonal polynomials are orthogonal over the proper domain\ndefint(p3*p4,'x',[-1,1])\n\n%%\n\n% 2nd and 5th order Jacobi polynomials\np2 = orthpoly(2,'jacobi',2,3)\np5 = orthpoly(5,'jacobi',2,3)\n\n%% \n\n% Orthogonal polynomials are orthogonal over the proper domain.\n% Numerical issures left this just eps shy from zero.\ndefint(p2*p5*(1-x)^2*(1+x)^5,'x',[-1,1])\n\n%% Roots of the derivative of a sympoly\nsort(roots(diff(orthpoly(6,'cheby2'))))\n\n%% Error propagation through a sympoly\n\n% Given a unit Normal N(0,1) random variable, compute the\n% mean and variance of p(x) = 3*x + 2*x^2 - x^3\n \nsympoly x\n[polymean, polyvar] = polyerrorprop(3*x + 2*x^2 - x^3,'x',0,1)\n\n%%\n\n% Compute the mean and variance of x*y + 3*y^3, where x and y are\n% respectively N(mux,sx^2), and N(muy,sy^2)\n\nsympoly x y mux muy sx sy\n[polymean,polyvar] = polyerrorprop(x*y+3*y^3,{'x' 'y'},[mux,muy],[sx,sy])\n\n%% A simple construction for a Newton-Cotes integration rule\n% Here I'll generate Simpson's 3/8 rule.\n%\n% \n%\nM = vander(0:3);\nsympoly x f0 f1 f2 f3\n% an interpolating polynomial on this set of points\n% { (0,f0), (1,f1), (2,f2), (3,f3) }\nP_of_x = [x^3, x^2, x, 1]*pinv(M)*[f0;f1;f2;f3];\n\n%% sympoly uses the command window format style to write out the coefficients\n% Here, I'll force it to be in rational form\nformat rat\n\n%%\n% integrate the polynomial over its support\ndefint(P_of_x,'x',[0 3])\n\n%%\n% Or here, a 4 point open Newton-Cotes rule\nM = vander(1:4);\nsympoly x f1 f2 f3 f4\n% an interpolating polynomial on this set of points\n% { (1,f1), (2,f2), (3,f3) (4,f4) }\nP_of_x = [x^3, x^2, x, 1]*pinv(M)*[f1;f2;f3;f4]\n\n%%\n% integrate the polynomial over the full domain of the rule\ndefint(P_of_x,'x',[0 5])\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/9577-symbolic-polynomial-manipulation/SymbolicPolynomials/Sympoly_demos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.766252307467872}} {"text": "function [nll,g,H,T] = LogisticLoss(w,X,y)\n% w(feature,1)\n% X(instance,feature)\n% y(instance,1)\n\n[n,p] = size(X);\n\nXw = X*w;\nyXw = y.*Xw;\n\nnll = sum(mylogsumexp([zeros(n,1) -yXw]));\n\nif nargout > 1\n if nargout > 2\n sig = 1./(1+exp(-yXw));\n g = -X.'*(y.*(1-sig));\n else\n %g = -X.'*(y./(1+exp(yXw)));\n g = -(X.'*(y./(1+exp(yXw))));\n end\nend\n\nif nargout > 2\n H = X.'*diag(sparse(sig.*(1-sig)))*X;\nend\n\nif nargout > 3\n T = zeros(p,p,p);\n for j1 = 1:p\n for j2 = 1:p\n for j3 = 1:p\n T(j1,j2,j3) = sum(y(:).^3.*X(:,j1).*X(:,j2).*X(:,j3).*sig.*(1-sig).*(1-2*sig));\n end\n end\n end\nend\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/minFunc/logistic/LogisticLoss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7662478936248037}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\nH = X*theta;\nJ = sum((H - y).^2) / (2 * m) + lambda*sum(theta(2:end).^2) / (2 * m);\n\ngrad = X'*(H - y) / m + lambda*[0;theta(2:end)] / m;\n\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "zhouxc", "repo": "Stanford-Machine-Learning-Course", "sha": "cb1002771b33ac3af4a14be2afa0431212a66ea5", "save_path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course", "path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course/Stanford-Machine-Learning-Course-cb1002771b33ac3af4a14be2afa0431212a66ea5/Regularized linear regression and bias-variance/mlclass-ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7662396199170787}} {"text": "function variance = normal_truncated_a_variance ( mu, s, a )\n\n%*****************************************************************************80\n%\n%% NORMAL_TRUNCATED_A_VARIANCE: variance of the lower truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real MU, S, the mean and standard deviation of the\n% parent Normal distribution.\n%\n% Input, real A, the lower truncation limit.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n alpha = ( a - mu ) / s;\n% beta = Inf;\n\n alpha_pdf = normal_01_pdf ( alpha );\n\n alpha_cdf = normal_01_cdf ( alpha );\n\n variance = s * s * ( 1.0 ...\n + ( alpha * alpha_pdf ) / ( 1.0 - alpha_cdf ) ...\n - ( alpha_pdf / ( 1.0 - alpha_cdf ) ) ^ 2 );\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/normal_truncated_a_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7662396106649858}} {"text": "% bpExampleScript\n\nctol = 0.000001; % convergence tolerance\nT = 0.1; % annealing temperature\nmaxiter = Inf; % max iter for maxBeliefPropBethe\n\n\n% factor for P(x1 | x2)\nfactor2var{1} = [1 2]; % which variables the factor involves\nfactors{1} = [0.9 0.5 ; ...\n 0.1 0.5]; % P(x1=1|x2=1) = 0.9, P(x1=2|x2=1)=0.1\n% factor for P(x2 | x3)\nfactor2var{2} = [2 3]; \nfactors{2} = [0.25 0.01 ; ...\n 0.75 0.99];\n% factor for P(x3)\nfactor2var{3} = [3]; \nfactors{3} = [0.25 ; ...\n 0.75]; % P(x1=1)=0.25, P(x1=2)=0.75\n\nnvals = [2 ; 2 ; 2]; % number of states for each node (variable)\n\n[vals_max, bel_max] = maxBeliefPropBethe(factors, factor2var, nvals, ctol, T, maxiter);\nbel_max = reshape(cell2mat(bel_max), [nvals(1) numel(nvals)])';\n\nbel_marg = marginalBeliefPropBethe(factors, factor2var, nvals, ctol);\nbel_marg = reshape(cell2mat(bel_marg), [nvals(1) numel(nvals)])';\n\n% marginal answer should be:\n% P(x3=1) = 0.25; \n% P(x2=1) = (0.25)*P(x3=1) + (0.01)*P(x3=2) = 0.07\n% P(x1=1) = (0.9)*P(x2=1) + 0.5*P(x2=2) = 0.528 \nbel_marg\n\n% max solution should be:\n% x1 = 2;\n% x2 = 2;\n% x3 = 1 or 2; (equally likely)\nbel_max", "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/bp/bpExampleScript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7660570215883333}} {"text": "%% Parzen Probabilistic Neural Networks\n% The Parzen Probabilistic Neural Networks (PPNN) are a simple type of\n% neural network used to classify data vectors. This classifiers are based\n% on the Bayesian theory where the a posteriori probability density\n% function (apo-pdf) is estimated from data using the Parzen window\n% technique.\n\n%% A brief overview on the theory of the Parzen window and PPNN\n% The Bayesian classifiers use the Bayesian equation:\n%\n% P(x|wi)P(wi)\n% P(wi|x) = ----------------------\n% SUM_j P(x|wj)P(wj)\n%\n% to estimate the apo-pdf P(wi|x). Obviously to be usefull, this method\n% needs the probabilities P(x|wi) and P(wi) to be known. A technique is to\n% parametrize this pdfs, another is to estimate them from data.\n% The Parzen window technique estimates the probability defining a window\n% (given the winow size) and a function on this window (i.e. an hypersphere\n% with the gaussian function truncated inside). The computes the estimation\n% of the probability function convolving the window function with the\n% samples function. This obviously requires that the window function must\n% have the integral (the hypervolume under the funciton) equal to 1 to\n% mantain the scale in the estimated pdf.\n% The PPNN is a simple tool that is the composition of the pdf estimation\n% with the Parzen window and the Bayesian classification selecting for a\n% feature vector x the class wi where P(wi|x) is maximum.\n% In this quick explanation the particular derivations aren't reported but\n% can be found in [1].\n% \n% A PPNN is a two layer neural network (NN) where the input data are fully\n% connected with the first neuron layer and the first layer is sparsely\n% connected with the second (and ouput) layer. The output layer is composed\n% of c neurons where c is the number of classes of the classifier. \n% The wheights on the first layer are trained as follows: each sample data\n% is normalized so that its length becames unitary, each sample data\n% becames a neuron with the normalized values as weights w. The input data\n% x is so dot-multiplied by the weights obtaining the network activation\n% signal net=w^Tx. Then the exponential nonlinearity:\n%\n% net - 1\n% ---------\n% 2\n% sigm\n% act = e\n%\n% is computed to obtain the synaptic activation signals. During the\n% learning process each first layer neuron is connected to the output layer\n% neuron related to its class with wheight 1. During the classification\n% process the output neuron of each class sums the activation signals from\n% all the neurons of the neurons of the first layer. Simply the highest\n% output value selects the class of the input data.\n%\n% (w1) (w2) ... OUTPUT\n% \\ \\ \\__\n% | | \\\n% ( ) ( ) ( ) internal layer\n% /|\\ /|\\ /|\\\n% INPUT\n%\n% [1] \"Pattern Classification\", second edition,\n% by Richard O. Duda, Peter E. Hart. and David G. Stork\n\n%% A first simple example with 2D data\n% In this simple example three set of points in the plane are selected in\n% the region [1:100;1:100]. A PPNN is trained with this samples and then\n% an image of the classification regions is produced.\n\n% A training set for the class 'a' and 'b':\nimg=ones(100);\nf=figure; imshow(img); [X,Y]=getpts; sa=[X,Y]'; close(f);\nf=figure; imshow(img); [X,Y]=getpts; sb=[X,Y]'; close(f);\nf=figure; imshow(img); [X,Y]=getpts; sc=[X,Y]'; close(f);\n% The samples matrix:\nS = [sa,sb,sc];\n% The classification vector:\nC = [repmat('a',[1,size(sa,2)]),repmat('b',[1,size(sb,2)]),repmat('c',[1,size(sc,2)])];\n% Generating the network:\nnet = parzenPNNlearn(S,C);\n\n% Generating the whole grid:\n[X,Y] = meshgrid(1:100,1:100);\nD = [X(:),Y(:)]';\n% Classification of all points:\nclass = parzenPNNclassify(net,D);\nclass = reshape(class,[100,100]);\n% Plotting:\nsep = double(class=='a') + 2*double(class=='c');\nfigure; imshow(sep/2); hold on;\nplot(sa(1,:),sa(2,:),'r.');\nplot(sb(1,:),sb(2,:),'g.');\nplot(sc(1,:),sc(2,:),'b.');\n\n%% Adding samples to the network to increase the training\n% A PPNN can be simply improved adding new samples to it, the new samples\n% generates new neurons in the internal layer that so can grow. Here an\n% example of improving of the generated neural network.\n\n% Getting new samples:\nf=figure; imshow(img); hold on; plot(sa(1,:),sa(2,:),'r.');\n[X,Y]=getpts; nsa=[X,Y]'; close(f);\nf=figure; imshow(img); hold on; plot(sb(1,:),sb(2,:),'g.');\n[X,Y]=getpts; nsb=[X,Y]'; close(f);\nf=figure; imshow(img); hold on; plot(sc(1,:),sc(2,:),'b.');\n[X,Y]=getpts; nsc=[X,Y]'; close(f);\nSa = [sa,nsa];\nSb = [sb,nsb];\nSc = [sc,nsc];\n\n% The samples matrix:\nnS = [nsa,nsb,nsc];\n% The classification vector:\nnC = [repmat('a',[1,size(nsa,2)]),repmat('b',[1,size(nsb,2)]),repmat('c',[1,size(nsc,2)])];\n% Improving the network:\nnet = parzenPNNimprove(net,nS,nC);\n\n% Classification of all points:\nclass = parzenPNNclassify(net,D);\nclass = reshape(class,[100,100]);\n% Plotting:\nsep = double(class=='a') + 2*double(class=='c');\nfigure; imshow(sep/2); hold on;\nplot(Sa(1,:),Sa(2,:),'r.');\nplot(Sb(1,:),Sb(2,:),'g.');\nplot(Sc(1,:),Sc(2,:),'b.');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11880-parzen-pnn/ParzenPNN/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7660570176829588}} {"text": "function [EC,ec,degij] = edge_nei_overlap_bd(CIJ)\n% EDGE_NEI_OVERLAP_BD Overlap amongst neighbors of two adjacent nodes\n%\n% [EC,ec,degij] = edge_nei_bd(CIJ);\n%\n% This function determines the neighbors of two nodes that are linked by \n% an edge, and then computes their overlap. Connection matrix must be\n% binary and directed. Entries of 'EC' that are 'inf' indicate that no\n% edge is present. Entries of 'EC' that are 0 denote \"local bridges\",\n% i.e. edges that link completely non-overlapping neighborhoods. Low\n% values of EC indicate edges that are \"weak ties\".\n%\n% If CIJ is weighted, the weights are ignored. Neighbors of a node can be\n% linked by incoming, outgoing, or reciprocal connections.\n%\n% Inputs: CIJ, directed (binary/weighted) connection matrix\n% \n% Outputs: EC, edge neighborhood overlap matrix\n% ec, edge neighborhood overlap per edge, in vector format\n% degij, degrees of node pairs connected by each edge\n%\n% Reference:\n%\n% Easley and Kleinberg (2010) Networks, Crowds, and Markets. \n% Cambridge University Press, Chapter 3\n%\n% Olaf Sporns, Indiana University, 2012\n\n[ik,jk,ck] = find(CIJ);\nlel = length(ck);\nN = size(CIJ,1);\n\n[~,~,deg] = degrees_dir(CIJ);\n\nec = zeros(1,lel);\ndegij = zeros(2,lel);\nfor e=1:lel\n neiik = setdiff(union(find(CIJ(ik(e),:)),find(CIJ(:,ik(e))')),[ik(e) jk(e)]);\n neijk = setdiff(union(find(CIJ(jk(e),:)),find(CIJ(:,jk(e))')),[ik(e) jk(e)]);\n ec(e) = length(intersect(neiik,neijk))/length(union(neiik,neijk));\n degij(:,e) = [deg(ik(e)) deg(jk(e))];\nend;\n\nff = find(CIJ);\nEC = 1./zeros(N);\nEC(ff) = ec; %#ok\n\n\n", "meta": {"author": "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/edge_nei_overlap_bd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7660089749848613}} {"text": "function gx = p01_gx ( x )\n\n%*****************************************************************************80\n%\n%% P01_GX evaluates the underlying function for problem 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(2), the point at which the function is to\n% be evaluated.\n%\n% Output, real GX(2), the value of the function at X.\n%\n gx(1) = x(1) - ( ( x(2) - 5.0 ) * x(2) + 2.0 ) * x(2) - 13.0;\n gx(2) = x(1) + ( ( x(2) + 1.0 ) * x(2) - 14.0 ) * x(2) - 29.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_con/p01_gx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7660049989548932}} {"text": "function [ cc_est, r_min, r_max ] = cube3d_grid_centralize ( ng, oc )\n\n%*****************************************************************************80\n%\n%% CUBE3D_GRID_CENTRALIZE centralizes grid data from the surface of a 3D cube.\n%\n% Discussion:\n%\n% We generate a hypersphere grid of 1D index NG, with origin at OC,\n% and project these points onto the 3D cube of center [0,0,0]\n% and radius 1.\n%\n% The cube is aligned with the coordinate axes.\n%\n% We seek to estimate the value of the center.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NG, the grid index. The hypersphere grid will have\n% order N = (2*NG+1) * (NG+1)^(M-2).\n%\n% Input, real OC(M,1), the observation point, the original of the\n% hypersphere coordinate system. OC should be inside the cube.\n%\n% Output, real CC_EST(M,1), the estimated cube center.\n%\n% Output, real R_MIN, R_MAX, the minimum and maximum distances\n% between the observation point and sample points on the cube surface.\n%\n m = 3;\n n = ( 2 * ng + 1 ) * ( ng + 1 ) ^ ( m - 2 );\n%\n% Destroy all row vectors!\n%\n oc = oc(:);\n%\n% Compute sample points on the cube surface.\n%\n [ x1, x2, x3 ] = cube3d_grid ( ng, oc );\n%\n% \"Flatten\" the data into vectors.\n%\n x1 = reshape ( x1, n, 1 );\n x2 = reshape ( x2, n, 1 );\n x3 = reshape ( x3, n, 1 );\n%\n% The center estimate is simply the average.\n%\n cc_est = zeros ( 3, 1 );\n cc_est(1,1) = sum ( x1 ) / n;\n cc_est(2,1) = sum ( x2 ) / n;\n cc_est(3,1) = sum ( x3 ) / n;\n%\n% For each point on the cube surface, the \"radius\" ROC is the norm of X - OC.\n%\n roc = [ x1, x2, x3 ]' - repmat ( oc, 1, n );\n roc = roc.^2;\n roc = sum ( roc, 1 );\n roc = sqrt ( roc );\n%\n% Return the minimum and maximum radiuses.\n%\n r_min = min ( roc );\n r_max = max ( roc );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/centralize/cube3d_grid_centralize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7660049983397103}} {"text": "function result = is_orthogonal_matrix(P)\n%\n% Orthogonal Matrices\n% \n% is_orthogonal_matrix(P) determines if the matrix P is an orthogonal\n% matrix. An error is returned if a matrix that is not square is attempted\n% to be determined for orthogonality.\n%\n% Function written by Anthony Russo, downloaded from MatlabCentral.\n%\n\nmatrix_size = size(P);\n\nm = matrix_size(1,1);\nn = matrix_size(1,2);\n\ntolerance = 10^-10;\n\nif m ~= n\n error('Only square matrices can be orthogonal.');\nelse\n count = 0;\n\n identity_matrix = P*P';\n\n if det(P) ~= 0\n for i = 1:m\n if abs(identity_matrix(i,i) - 1) <= tolerance\n count = count + 1;\n else\n break\n end\n end\n end\n\n if count == m\n result = 1;\n else\n result = 0;\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/is_orthogonal_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7659830463213598}} {"text": "%% Demo of *plot_littlewood_paley_1d*\n\n%% Usage\n% littlewood = *plot_littlewood_paley_1d*(filters) (see\n% ).\n%\n%% Description\n% *plot_littlewood_paley* computes, at every frequency, the \n% Littlewood-Paley sum of a filter bank, i.e. the total power spectral\n% density\n% \\sum_{j, \\theta} |\\hat{\\psi_j} (\\omega)|^2 + |\\hat{\\phi_J}(\\omega)|^2\n% If this sum is between $(1-epsilon)$ and $1$ for small $epsilon,\n% the associated wavelet transform is proved to be contractive and\n% almost unitary.\n\n% In this demo, we display the Littlewood-Paley sum of a dyadic Morlet\n% wavelet filter bank, with a very low averaging size of 8 samples. The\n% Littlewood-Paley sum is shown in red, while the lowpass filter phi and\n% the bandpass filters psi are respectively shown in green and blue.\n\nfigure;\nT = 2^3;\ninterpolation = 2^10;\nfilt_opt.Q = 1;\nfilt_opt.J = T_to_J(T,filt_opt);\ndyadic_filters = morlet_filter_bank_1d(T*interpolation,filt_opt);\n\nplot_littlewood_paley_1d(dyadic_filters);\ntitle('Q = 1 ; T = 8 samples (interpolated)');\n\n% A more realistic example is constructed with an averaging size of 4096\n% samples and a quality factor of 8. These values are typical in audio\n% signal processing. The lowpass filter has such a narrow bandwidth that it\n% is almost not visible in this second plot.\n\nfigure;\nT = 2^12;\nfilt_opt.Q = 8;\nfilt_opt.J = T_to_J(T,filt_opt);\naudio_filters = morlet_filter_bank_1d(T,filt_opt);\n\nplot_littlewood_paley_1d(audio_filters);\ntitle('Q = 8 ; T = 4096 samples');", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/demo/display/demo_plot_littlewood_paley_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7659643618791048}} {"text": "function [ fea, out ] = ex_heattransfer7( varargin )\n%EX_HEATTRANSFER7 1D Transient heat diffusion with analytic solution.\n%\n% [ FEA, OUT ] = EX_HEATTRANSFER7( VARARGIN ) Transient heat\n% diffusion problem with analytic solution. A 1 m rod is kept at\n% fixed temperature on one end and constant outward heat flux at the\n% other end as in the following illustration.\n%\n% +---------- L=1m ----------+ T = 25\n% q_n = 1 T(t=0) = 25\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% hmax scalar {0.1} Grid cell size\n% sfun string {sflag1} Finite element shape function\n% solver string fenics/{} Use FEniCS or default solver\n% ischeme scalar {2}/1/3 Time stepping scheme\n% tmax scalar {0.2} Maximum time\n% tstep scalar {0.01} Time step size\n% iplot scalar {1}/0 Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n%\n% See also EX_HEATTRANSFER8.\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { 'hmax', 0.1;\n 'sfun', 'sflag1';\n 'solver', '';\n 'ischeme', 2;\n 'tmax', 0.2;\n 'tstep', 0.01;\n 'nstbwe', 0;\n 'iplot', 1;\n 'tol', 1e-3;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\n\n\n% Grid generation.\nfea.grid = linegrid( round(1/opt.hmax), 0, 1 );\n\n\n% Problem definition.\nfea.sdim = { 'x' }; % Space coordinate name.\nfea = addphys( fea, @heattransfer ); % Add heat transfer physics mode.\nfea.phys.ht.sfun = { opt.sfun }; % Set shape function.\n\n% Equation coefficients.\nfea.phys.ht.eqn.coef{1,end} = 1; % Density.\nfea.phys.ht.eqn.coef{2,end} = 1; % Heat capacity.\nfea.phys.ht.eqn.coef{3,end} = 1; % Thermal conductivity.\nfea.phys.ht.eqn.coef{6,end} = { 25 }; % Initial temperature.\n\n% Boundary conditions.\nfea.phys.ht.bdr.sel = [ 4 1 ];\nfea.phys.ht.bdr.coef{1,end} = { [] 25 };\nfea.phys.ht.bdr.coef{4,end}{1}{1} = -1;\n\n\n% Parse physics modes and problem struct.\nfea = parsephys(fea);\nfea = parseprob(fea);\n\n\n% Compute solution.\nif( strcmp(opt.solver,'fenics') )\n fea = fenics( fea, 'fid', opt.fid, ...\n 'tstep', opt.tstep, 'tmax', opt.tmax, 'ischeme', opt.ischeme );\n tlist = fea.sol.t;\nelse\n [fea.sol.u, tlist] = solvetime( fea, 'fid', opt.fid, 'init', {'T0_ht'}, 'ischeme', opt.ischeme, ...\n 'tmax', opt.tmax, 'tstep', opt.tstep, 'nstbwe', opt.nstbwe );\nend\n\n% Postprocessing.\nT_ref = refsol( fea.grid.p', tlist(end) );\nif( opt.iplot>0 )\n postplot( fea, 'surfexpr', 'T', 'axequal', 0 )\n title(['Temperature at t=',num2str(tlist(end))])\n xlabel('x')\n ylabel('T')\n\n hold on\n plot( fea.grid.p, T_ref, 'r--' )\nend\n\n\n% Error checking.\nT_sol = evalexpr( 'T', fea.grid.p, fea );\nout.err = norm( abs(T_sol-T_ref)/T_ref );\nout.pass = out.err dtol );\n u0 = u;\n\n if( n>1e3 )\n warning( ['Reference solution did not converge to tolerance ',num2str(dtol)] )\n break\n end\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_heattransfer7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7659643614068111}} {"text": "function [Ht,weights] = riskmetrics2006(data,tau0,tau1,kmax,rho)\n% Computes the Riskmetrics 2006 covariance, which is a weighted average of\n% EWMA covariances\n%\n% USAGE:\n% [HT,WEIGHTS] = riskmetrics2006(DATA,TAU0,TAU1,KMAX,RHO)\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% TAU0 - [OPTIONAL] Half-life of slowest EWMA\n% TAU1 - [OPTIONAL] Half-life of fastest EWMA\n% KMAX - [OPTIONAL] Number of EWMA components to use\n% RHO - [OPTIONAL] Decay factor to use in half-lives. The\n% half-lives used are TAU1, TAU1*RHO, TAU1*RHO^2, ...\n%\n% OUTPUTS:\n% HT - A [K K T] dimension matrix of conditional covariances\n% WEIGHTS - A T by T matrix which contains the final weights used\n% computing all conditional covariances. WEIGHT(i,j)\n% contains the weight of the outer-product in time period j\n% in the covariance forecast at period i+1\n%\n% COMMENTS:\n% The conditional variance, H(t), of a RM2006 covariance model\n%\n% H(t) = w(i)*Htilde(t,i)\n%\n% where Htilde(t,i) is an EWMA covariance, i=1,2,..., and \n%\n% w(i) = 1-log(TAU1^((i-1)*RHO))/log(TAU0)\n%\n% where the weights have been normalized so that they sum to 1. All\n% EWMAs are initialized using a backward EWMA with the same decay.\n%\n% EXAMPLES:\n% RiskMetrics 2006 methodology using the suggested reference values\n% tau0 = 1560;\n% tau1 = 4;\n% taumax = 512;\n% rho = sqrt(2);\n% kmax = round(log(taumax/tau1)/log(rho)); % 14\n% Ht = riskmetrics2006(data,tau0,tau1,kmax,rho)\n%\n% RiskMetrics 1994 methodology using .94 as a special case of RM2006\n% tau0 = 1560; % Does not matter\n% rho = 1; % Does not matter\n% tau1 = -1/log(.94);\n% kmax = 1;\n% Ht = riskmetrics2006(data,tau0,tau1,kmax,rho)\n\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 03/10/2011\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n case 1\n tau0=[];\n tau1=[];\n kmax=[];\n rho =[];\n case 2\n tau1=[];\n kmax=[];\n rho =[];\n case 3\n kmax=[];\n rho =[];\n case 4\n rho =[];\n case 5\n % Nothing\n otherwise\n error('1 to 5 inputs required.')\nend\n\nif isempty(tau0)\n tau0 = 1560;\nend\nif isempty(tau1)\n tau1 = 4;\nend\nif isempty(kmax)\n kmax = 14;\nend\nif isempty(rho)\n rho = sqrt(2);\nend\n\nif tau1*rho^(kmax-1)>tau0\n error('The inputs must satisfy: TAU1*RHO^(KMAX-1)1\n weights = zeros(T,T);\n for k=1:kmax\n tauk = tauks(k);\n mu = exp(-1/tauk);\n weightMatrix = [mu.^(0:T-1)' zeros(T,T-1)];\n weightMatrix(T,T) = (1-mu);\n for j=1:(T-2);\n weightMatrix(T,T-j) = mu * weightMatrix(T,T-j+1);\n end\n for t=2:T-1\n weightMatrix(t,2:t) = weightMatrix(T,T+(-t+2:0));\n end\n weights = weights + w(k) * weightMatrix;\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/riskmetrics2006.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7658982900394666}} {"text": "% Reduce polygon to a given number of vertices\n%\n% poly = reduce_poly(poly, num)\n%\n% Inputs: poly Polygon (2 rows, n columns)\n% num Required number of vertices\n%\n% Outputs: poly Final polygon\n%\n% Description: This code reduces the number of vertices in a closed polygon\n% to the number specified by 'num'. It does this by calculating the\n% importance of each vertex based on angle and segment length and then\n% removing the least important. The process is repeated until the desired\n% number of vertices is reached.\n%\n% Example:\n% t = 0:0.1:2*pi;\n% poly1 = [sin(t); cos(t)];\n% poly2 = reduce_poly(poly1, 21);\n% poly_draw = [poly2 poly2(:,1)];\n% plot(poly_draw(1,:), poly_draw(2,:), '.-')\n% axis equal\n%\n% Coded by: Peter Bone (peterbone@hotmail.com)\n%------------------------------------------------------------------------\nfunction poly = reduce_poly(poly, num)\n\nnumv = length(poly);\n\n% Calculate initial importance of each vertex\nimp = zeros(1,numv);\nfor v = 1 : numv\n imp(v) = vertex_importance(v, poly, numv);\nend\n\n% Iterate until desired number of vertices is reached\nwhile numv > num\n \n [~, i] = min(imp(1:numv));\n \n % Remove vertex with least importance\n if i < numv\n poly(:,i:numv-1) = poly(:,i+1:numv);\n imp(i:numv-1) = imp(i+1:numv);\n vp = i;\n else\n vp = 1;\n end\n numv = numv - 1;\n \n % Recalculate importance for vertices neighbouring the removed one\n vm = 1 + mod(i - 2, numv);\n imp(vp) = vertex_importance(vp, poly, numv);\n imp(vm) = vertex_importance(vm, poly, numv);\n \nend\n\n% Clip polygon to the final length\npoly = poly(:,1:num);\n\n\nfunction a = vertex_importance(v, poly, numv)\n\n% Find adjacent vertices\nvp = 1 + mod(v, numv);\nvm = 1 + mod(v - 2, numv);\n\n% Obtain adjacent line segments and their lengths\ndir1 = poly(:,v) - poly(:,vm);\ndir2 = poly(:,vp) - poly(:,v);\nlen1 = norm(dir1);\nlen2 = norm(dir2);\n\n% Calculate angle between vectors and multiply by segment lengths\n% This is the importance of the vertex.\n% Vertices with large angle and large segments attached are less\n% likely to be removed\nlen1len2 = len1 * len2;\na = abs(acos((dir1' * dir2) / len1len2)) * len1len2;\n%a = abs(1 - ((dir1' * dir2) / len1len2)) * len1len2;\n ", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/imtool3D_td/External/reduce_poly/reduce_poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.76583835793386}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% \n% \n% problem 2- Evaluate the Laplace Transform of y''(t) and then replace y(t) by sin(t)u(t) \n\nsym 'y(t)' ; \nsyms t s\nz=laplace( diff('y(t)',2),s)\n\nz=subs(z,'y(t)',sin(t))\n\nz=subs(z,'y(0)',0)\nz=subs(z,'D(y)(0)',1)\nsimplify(z)\n\n%verification\nx=sin(t);\nx2=diff(x,2,t)\nlaplace(x2,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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/9/c99b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7658383477880779}} {"text": "function y = pow_p( x, p )\n\n%POW_P Positive branch of the power function.\n% POW_P(X,P) computes a convex or concave branch of the power function:\n% P < 0: POW_P(X,P) = X.^P if X > 0, +Inf otherwise\n% 0 <= P < 1: POW_P(X,P) = X.^P if X >= 0, -Inf otherwise\n% 1 <= P : POW_P(X,P) = X.^P if X >= 0, +Inf otherwise\n% Both P and X must be real.\n%\n% Disciplined convex programming information:\n% The geometry of POW_P(X,P) depends on the precise value of P,\n% which must be a real constant:\n% P < 0: convex and nonincreasing; X must be concave.\n% 0 <= P < 1: concave and nondecreasing; X must be concave.\n% 1 <= P : convex and nonmonotonic; X must be affine.\n% In all cases, X must be real.\n\ny = power( pdom( x ), p );\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/pow_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7657862212940757}} {"text": "function [mls,row,col] = mls(n)\n\n%[mls,row,col] = mls(n);\n%\n%Generates a Maximum Length Sequence of n bits by utilizing a \n%linear feedback shift register with an XOR gate on the tap bits\n%Also given are the permutation vector row and col, used by prior and after\n%the autocorreltion calculation via FHT.\n%\n%Function can accept bit lengths of between 2 and 24\n%\n%y is a vector of 1's & -1's that is (2^n)-1 in length.\n%\n%reference:\n%\tDavies, W.D.T. (June, July, August, 1966). Generation and \n%properties of maximum-length sequences. Control, 302-4, 364-5,431-3.\n%\n%Spring 2001, Christopher Brown, cbrown@phi.luc.edu\n\nswitch n\t\t\t\t\t\t\t%assign taps which will yeild a maximum\ncase 2\t\t\t\t\t\t\t\t%length sequence for a given bit length\n taps=2;\t\t\t\t\t\t\t%I forget the reference I used, but theres\n tap1=1;\t\t\t\t\t\t\t%a list of appropriate tap values in\n tap2=2;\t\t\t\t\t\t\t%Vanderkooy, JAES, 42(4), 1994.\ncase 3\n taps=2;\n tap1=1;\n tap2=3;\ncase 4\n taps=2;\n tap1=1;\n tap2=4;\ncase 5\n taps=2;\n tap1=2;\n tap2=5;\ncase 6\n taps=2;\n tap1=1;\n tap2=6;\ncase 7\n taps=2;\n tap1=1;\n tap2=7;\ncase 8\n taps=4;\n tap1=1;\n tap2=5;\n tap3=6;\n tap4=8;\ncase 9\n taps=2;\n tap1=4;\n tap2=9;\ncase 10\n taps=2;\n tap1=3;\n tap2=10;\ncase 11\n taps=2;\n tap1=2;\n tap2=11;\ncase 12\n taps=4;\n tap1=3;\n tap2=4;\n tap3=7;\n tap4=12;\ncase 13\n taps=4;\n tap1=1;\n tap2=3;\n tap3=4;\n tap4=13;\ncase 14\n taps=4;\n tap1=1;\n tap2=11;\n tap3=12;\n tap4=14;\ncase 15\n taps=2;\n tap1=1;\n tap2=15;\ncase 16\n taps=4;\n tap1=2;\n tap2=3;\n tap3=5;\n tap4=16;\ncase 17\n taps=2;\n tap1=3;\n tap2=17;\ncase 18\n taps=2;\n tap1=7;\n tap2=18;\ncase 19\n taps=4;\n tap1=1;\n tap2=5;\n tap3=6;\n tap4=19;\ncase 20\n taps=2;\n tap1=3;\n tap2=20;\ncase 21\n taps=2;\n tap1=2;\n tap2=21;\ncase 22\n taps=2;\n tap1=1;\n tap2=22;\ncase 23\n taps=2;\n tap1=5;\n tap2=23;\ncase 24\n taps=4;\n tap1=1;\n tap2=3;\n tap3=4;\n tap4=24;\ncase 25\n taps=2;\n tap1=3;\n tap2=25;\ncase 26\n taps=4;\n tap1=1;\n tap2=7;\n tap3=8;\n tap4=26;\ncase 27\n taps=4;\n tap1=1;\n tap2=7;\n tap3=8;\n tap4=27;\ncase 28\n taps=2;\n tap1=3;\n tap2=28;\ncase 29\n taps=2;\n tap1=2;\n tap2=29;\ncase 30\n taps=4;\n tap1=1;\n tap2=15;\n tap3=16;\n tap4=30;\ncase 31\n taps=2;\n tap1=3;\n tap2=31;\ncase 32\n taps=4;\n tap1=1;\n tap2=27;\n tap3=28;\n tap4=32;\notherwise\n disp(' ');\n error('input bits must be between 2 and 32');\nend\n\nif taps == 2\n [mls,row,col]=mls2tap(tap2,tap1,tap2);\nelseif taps == 4\n [mls,row,col]=mls4tap(tap4,tap1,tap2,tap3,tap4);\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/11392-acmus-room-acoustic-parameters/mls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7657862201120831}} {"text": "% Chapter 2 - Nonlinear Discrete Dynamical Systems.\n% Program 2g - Computing the Lyapunov Exponents of the Henon map.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\nitermax=500;\na=1.2;b=0.4;x=0;y=0;\nvec1=[1;0];vec2=[0;1];\nfor i=1:itermax \n x1=1-a*x^2+y;y1=b*x;\n x=x1;y=y1;\n J=[-2*a*x 1;b 0];\n vec1=J*vec1;\n vec2=J*vec2;\n dotprod1=dot(vec1,vec1);\n dotprod2=dot(vec1,vec2);\n vec2=vec2-(dotprod2/dotprod1)*vec1;\n lengthv1=sqrt(dotprod1);\n area=vec1(1)*vec2(2)-vec1(2)*vec2(1);\n h1=log(lengthv1)/i;\n h2=log(area)/i-h1;\nend\nfprintf('h1= %12.10f\\n',h1)\nfprintf('h2= %12.10f\\n',h2)\n\n% End of Program 2g.", "meta": {"author": "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_2g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7656816814575659}} {"text": "% X = NGROUPSK(N, K)\n%\n% The number of ways N*K objects can be divided into N groups of equal size\n% (K objects per group).\n%\n% N = number of groups\n% K = size of the groups\n%\n% X = number of different group division combinations\n\n% Last modified 2011-01-28\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction x = groupsk(n, k)\n\nx = factorial(n.*k) ./ ( factorial(n) .* factorial(k).^n );", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/discrete/ngroupsk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7656455361981553}} {"text": "clear;\n% some integration experiments\n\n% Example 1: E[p(x)], x~N(0,1), p(x) polynomial\ndegree = 10;\np = rand(1,degree+1); % make some polynomial\nfprintf('adaptive quad, tol %.1g = %.10g\\n', ...\n 1e-10, quad(@(x) polyval(p,x).*normpdf(x), ...\n -30,30,1e-10));\n\nfprintf(' gauss-hermite quadrature\\n');\nfor n=1:((degree+1)/2+4)\n % use hermite -- will be exact for n>=(degree+1)/2\n int = gaussHermite(n);\n % notice the change of variables!\n ep = polyval(p,int.x*sqrt(2))'*int.w/sqrt(pi);\n if (n==round((degree+1)/2))\n fprintf('--- the rest should be exact ----\\n');\n end\n fprintf('n=%2d E[p(x)] = %.10g\\n',n,ep);\nend\n\nfprintf('\\n monte carlo integration\\n')\nfor n=1:6\n fprintf('n=10^%d E[p(x)] = %.10g\\n',n, ...\n mean(polyval(p,randn(10^n,1))));\nend\n\npause();\n\n% Example 2: E[p(x)|x>-0.1], x~N(0,1)\nfprintf('adaptive quad, tol %.1g = %.10g\\n', ...\n 1e-10, quad(@(x) polyval(p,x).*normpdf(x), ...\n -0.1,30,1e-10) / ...\n quad(@(x) normpdf(x),-0.1,30,1e-10));\n\nfprintf('\\n gauss-hermite quadrature (not the right rule)\\n');\nfor n=1:2:60\n int = gaussHermite(n);\n m = int.x>-0.1;\n ep = polyval(p,int.x(m)*sqrt(2))'* ...\n int.w(m)/sqrt(pi) ...\n * sum(int.w)/sum(int.w(m));\n fprintf('n=%2d E[p(x)] = %.10g\\n',sum(m),ep);\nend\n\nfprintf('\\n monte carlo integration\\n')\nfor n=1:6\n x = randn(10^n,1);\n x = x(x>-0.1);\n fprintf('n=10^%d E[p(x)] = %.10g\\n',numel(x), ...\n mean(polyval(p,x)));\nend\npause();\n\n% Example 2: E[p(x)|x>-0.1], x~N(0,1)\n% Example 2: E[p(x)|x>-0.1], x~N(0,1)\nfprintf('adaptive quad, tol %.1g = %.10g\\n', ...\n 1e-10, quad(@(x) exp(x).*normpdf(x), ...\n -30,30,1e-10));\n\nfprintf('\\n gauss-hermite quadrature (not the right rule)\\n');\nfor n=1:20\n int = gaussHermite(n);\n ep = exp(int.x*sqrt(2))'*int.w/sqrt(pi);\n fprintf('n=%2d E[p(x)] = %.10g\\n',n,ep);\nend\n\nfprintf('\\n monte carlo integration\\n')\nfor n=1:6\n x = randn(10^n,1);\n fprintf('n=10^%d E[p(x)] = %.10g\\n',numel(x), ...\n mean(exp(x)));\nend\npause();", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/QuadratureMethods/Integration_Experiments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7655475703099668}} {"text": "%inPoints = getPolygonGrid(xv,yv,ppa) returns points that are within a \n%concave or convex polygon using the inpolygon function.\n\n%xv and yv are columns representing the vertices of the polygon, as used in\n%the Matlab function inpolygon\n\n%ppa refers to the points per unit area you would like inside the polygon. \n%Here unit area refers to a 1.0 X 1.0 square in the axes. \n\n%Example: \n% L = linspace(0,2.*pi,6); xv = cos(L)';yv = sin(L)'; %from the inpolygon documentation\n% inPoints = getPolygonGrid(xv, yv, 10^5)\n% plot(inPoints(:, 1),inPoints(:,2), '.k');\n\nfunction [inPoints] = polygrid( xv, yv, ppa)\n\n\tN = sqrt(ppa);\n%Find the bounding rectangle\n\tlower_x = min(xv);\n\thigher_x = max(xv);\n\n\tlower_y = min(yv);\n\thigher_y = max(yv);\n%Create a grid of points within the bounding rectangle\n\tinc_x = 1/N;\n\tinc_y = 1/N;\n\t\n\tinterval_x = lower_x:inc_x:higher_x;\n\tinterval_y = lower_y:inc_y:higher_y;\n\t[bigGridX, bigGridY] = meshgrid(interval_x, interval_y);\n\t\n%Filter grid to get only points in polygon\n\tin = inpolygon(bigGridX(:), bigGridY(:), xv, yv);\n%Return the co-ordinates of the points that are in the polygon\n\tinPoints = [bigGridX(in), bigGridY(in)];\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/41454-grid-of-points-within-a-polygon/polygrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7655235408247426}} {"text": "%% Optimal Kernel Selection\n%\n%%\n% In the section we have seen\n% that the correct choice of the kernel halfwidth is essential for creating a good\n% match between the true density function and the reconstructed density\n% function. If the halfwidth is set too small the reconstructed density\n% function is usually oscillating and the indiviudual sampling points are\n% visible as sharp peaks. If the halfwidth is too large the resulting\n% density function is usually too smooth and does not reproduce the\n% features of the original density function. \n%\n% Finding an optimal kernel halfwidth is a hard problem as the optimal\n% kernel halfwidth depends not only on the number of sampling points but also\n% on the smoothness of the true but unknown density function. \n% MTEX offers several options set by flags during the kernel calculation operation. A very\n% conserative choice for the kernel halfwidth that takes into account only\n% the number of sampling points is implemented in MTEX with the flag |'magicRule'|. The flag\n% |'RuleOfThumb'| considers both the number of sampling\n% points and the variance of the sampling points as an estimate of the\n% smoothness of the true density function. The most advanced (and default)\n% method for estimating the optimal kernel halfwidth is\n% .\n% This method tests different kernel halfwidths on a subset of the\n% random sample and selects the halfwidth which best reproduces the\n% ommited points of the random sample.\n%\n% In order to demonstrate this functionality let's start with the following\n% orientation density function\n\n% Define trigonal crystal symmetry using Enantiomorphic Point Group notation\ncs = crystalSymmetry('32');\n\n% Build a density function by combining a uniform texture with two pre-defined texture components\nodf = 0.25*uniformODF(cs) + 0.25*unimodalODF(orientation.brass(cs)) + ...\n 0.5*fibreODF(fibre.alpha(cs),'halfwidth',10*degree);\n\n% plot the density function as six sigma sections \nplot(odf,'sections',6,'silent','sigma')\nmtexColorbar\n\n%%\n% and compute $10000$ random orientations representing this density function using the command\n% ||\n\nori = odf.discreteSample(10000)\n\n%%\n% Next we estimate the optimal using the\n% command || with the default settings.\n\npsi = calcKernel(ori)\n\n%%\n% This kernel can now be used to reconstruct the original ODF from the sampled points using the command\n% \n\nodf_rec = calcDensity(ori,'kernel',psi)\n\n% plot the reconstructed ODF and compare it to the plot of the original function. The results are similar but not identical.\nfigure;plot(odf_rec,'sections',6,'silent','sigma')\nmtexColorbar\n\n%% Exploration of the relationship between estimation error and number of single orientations\n%\n% In this section we want to compare the different methods for estimating\n% the optimal kernel halfwidth. To this end we simulate 10, 100, ...,\n% 1000000 single orientations from the model ODF |odf|, compute optimal\n% kernels according to the |'magicRule'|, the |'RuleOfThumb'| and\n% and then\n% compute the fit between the reconstructed |odf_rec| and the original\n% |odf|.\n\n% define a variable to hold the calculated error values\ne = [];\nfor i = 1:6\n\n % calculate a sample of orientations from the model ODF\n ori = discreteSample(odf,10^i,'silent');\n \n % calculate the kernel using the function defaults, reconstruct the odf, and calculate error between this and the original ODF\n psi1 = calcKernel(ori,'SamplingSize',10000,'silent');\n odf_rec = calcDensity(ori,'kernel',psi1,'silent');\n e(i,1) = calcError(odf_rec,odf,'resolution',2.5*degree);\n \n % calculate the kernel using the RuleOfThumb, reconstruct the odf, and calculate error between this and the original ODF\n psi2 = calcKernel(ori,'method','RuleOfThumb','silent');\n odf_rec = calcDensity(ori,'kernel',psi2,'silent');\n e(i,2) = calcError(odf_rec,odf,'resolution',2.5*degree); \n \n % calculate the kernel using the magicRule, reconstruct the odf, and calculate error between this and the original ODF\n psi3 = calcKernel(ori,'method','magicRule','silent');\n odf_rec = calcDensity(ori,'kernel',psi3,'silent');\n e(i,3) = calcError(odf_rec,odf,'resolution',2.5*degree); \n\n % generate text showing the kernel size calculated with each method in each loop\n disp(['RuleOfThumb: ' int2str(psi2.halfwidth/degree) mtexdegchar ...\n ' KLCV: ' int2str(psi1.halfwidth/degree) mtexdegchar ...\n ' magicRule: ' int2str(psi3.halfwidth/degree) mtexdegchar ...\n ]);\n \nend\n\n%% \n% Plot the error to the number of single orientations sampled from the original ODF.\n\nclose all;\nloglog(10.^(1:length(e)),e,'LineWidth',2)\nlegend('Default','RuleOfThumb','magicRule')\nxlabel('Number of orientations (log scale)')\nylabel('Estimation Error in degrees')\ntitle('Error between original ODF model and the reconstructed ODF','FontWeight','bold')\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/GeneralConcepts/OptimalKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.7655054636346481}} {"text": "function [X,Y,Z] = EquinNdes3D(N)\n\n% function [X,Y,Z] = EquinNdes3D(N)\n% Purpose: compute the equidistributed nodes on the reference tetrahedron\n\n% total number of nodes\nNp = (N+1)*(N+2)*(N+3)/6;\n\n% 2) create equidistributed nodes on equilateral triangle\nX = zeros(Np,1); Y = zeros(Np,1); Z = zeros(Np,1); \n\nsk = 1;\nfor n=1:N+1\n for m=1:N+2-n\n for q=1:N+3-n-m\n X(sk) = -1 + (q-1)*2/N; Y(sk) = -1 + (m-1)*2/N; Z(sk) = -1 + (n-1)*2/N;\n sk = sk+1;\n end\n end\nend\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/EquiNodes3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7654827329193588}} {"text": "function m = sqdist(p, q, A)\n% SQDIST Squared Euclidean or Mahalanobis distance.\n% SQDIST(p,q) returns m(i,j) = (p(:,i) - q(:,j))'*(p(:,i) - q(:,j)).\n% SQDIST(p,q,A) returns m(i,j) = (p(:,i) - q(:,j))'*A*(p(:,i) - q(:,j)).\n% The Lightspeed Matlab toolbox\n% Written by Tom Minka\n\n[d, pn] = size(p);\n[d, qn] = size(q);\n\nif pn == 0 || qn == 0\n m = zeros(pn,qn);\n return\nend\n\nif nargin == 2\n \n pmag = col_sum(p .* p);\n qmag = col_sum(q .* q);\n m = repmat(qmag, pn, 1) + repmat(pmag', 1, qn) - 2*p'*q;\n %m = ones(pn,1)*qmag + pmag'*ones(1,qn) - 2*p'*q;\n \nelse\n\n Ap = A*p;\n Aq = A*q;\n pmag = col_sum(p .* Ap);\n qmag = col_sum(q .* Aq);\n m = repmat(qmag, pn, 1) + repmat(pmag', 1, qn) - 2*p'*Aq;\n \nend\n", "meta": {"author": "layumi", "repo": "Image-Text-Embedding", "sha": "58f858da887f12ca94301c4f44113e2464d414ee", "save_path": "github-repos/MATLAB/layumi-Image-Text-Embedding", "path": "github-repos/MATLAB/layumi-Image-Text-Embedding/Image-Text-Embedding-58f858da887f12ca94301c4f44113e2464d414ee/test_coco/sqdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7654827247948707}} {"text": "function eps = leviCivita\n% the Levi Civita permutation tensor\n%\n% Syntax\n% eps = tensor.leviCivita\n%\n\neps = zeros(3,3,3);\neps(1,2,3) = 1;\neps(3,1,2) = 1;\neps(2,3,1) = 1;\n\neps(1,3,2) = -1;\neps(3,2,1) = -1;\neps(2,1,3) = -1;\n \neps = tensor(eps,'rank',3,'name','Levi Cevita');\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/@tensor/leviCivita.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7654827216888715}} {"text": "function value = r8mat_norm_fro_affine ( m, n, a1, a2 )\n\n%*****************************************************************************80\n%\n%% R8MAT_NORM_FRO_AFFINE returns the Frobenius norm of an R8MAT difference.\n%\n% Discussion:\n%\n% The Frobenius norm is defined as\n%\n% value = sqrt ( sum ( 1 <= I <= M ) sum ( 1 <= j <= N ) A(I,J)^2 )\n%\n% The matrix Frobenius norm is not derived from a vector norm, but\n% is compatible with the vector L2 norm, so that:\n%\n% vec_norm_l2 ( A * x ) <= mat_norm_fro ( A ) * vec_norm_l2 ( x ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows.\n%\n% Input, integer N, the number of columns.\n%\n% Input, real A1(M,N), A2(M,N), the matrices for whose difference \n% the Frobenius norm is desired.\n%\n% Output, real VALUE, the Frobenius norm of A1 - A2.\n%\n value = sqrt ( sum ( sum ( ( a1(1:m,1:n) - a2(1:m,1:n) ).^2 ) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_norm_fro_affine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.765437701269357}} {"text": "function mbasis = basis_matrix_beta_uni ( beta1, beta2 )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_BETA_UNI sets up the uniform beta spline basis matrix.\n%\n% Discussion:\n%\n% If BETA1 = 1 and BETA2 = 0, then the beta spline reduces to\n% the B spline.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Foley, van Dam, Feiner, Hughes,\n% Computer Graphics: Principles and Practice,\n% page 505.\n%\n% Parameters:\n%\n% Input, real BETA1, the skew or bias parameter.\n% BETA1 = 1 for no skew or bias.\n%\n% Input, real BETA2, the tension parameter.\n% BETA2 = 0 for no tension.\n%\n% Output, real MBASIS(4,4), the basis matrix.\n%\n mbasis = zeros(4,4);\n\n mbasis(1,1) = - 2.0 * beta1 * beta1 * beta1;\n mbasis(1,2) = 2.0 * beta2 ...\n + 2.0 * beta1 * ( beta1 * beta1 + beta1 + 1.0 );\n mbasis(1,3) = - 2.0 * ( beta2 + beta1 * beta1 + beta1 + 1.0 );\n mbasis(1,4) = 2.0;\n\n mbasis(2,1) = 6.0 * beta1 * beta1 * beta1;\n mbasis(2,2) = - 3.0 * beta2 ...\n - 6.0 * beta1 * beta1 * ( beta1 + 1.0 );\n mbasis(2,3) = 3.0 * beta2 + 6.0 * beta1 * beta1;\n mbasis(2,4) = 0.0;\n\n mbasis(3,1) = - 6.0 * beta1 * beta1 * beta1;\n mbasis(3,2) = 6.0 * beta1 * ( beta1 - 1.0 ) * ( beta1 + 1.0 );\n mbasis(3,3) = 6.0 * beta1;\n mbasis(3,4) = 0.0;\n\n mbasis(4,1) = 2.0 * beta1 * beta1 * beta1;\n mbasis(4,2) = 4.0 * beta1 * ( beta1 + 1.0 ) + beta2;\n mbasis(4,3) = 2.0;\n mbasis(4,4) = 0.0;\n\n delta = ( ( 2.0 ...\n * beta1 + 4.0 ) ...\n * beta1 + 4.0 ) ...\n * beta1 + 2.0 + beta2;\n\n mbasis(1:4,1:4) = mbasis(1:4,1:4) / delta;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/basis_matrix_beta_uni.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7654243695396469}} {"text": "function [pval, k, K] = circ_kuipertest(alpha1, alpha2, res, vis_on)\n\n% [pval, k, K] = circ_kuipertest(sample1, sample2, res, vis_on)\n%\n% The Kuiper two-sample test tests whether the two samples differ \n% significantly.The difference can be in any property, such as mean \n% location and dispersion. It is a circular analogue of the \n% Kolmogorov-Smirnov test. \n% \n% H0: The two distributions are identical.\n% HA: The two distributions are different.\n%\n% Input: \n% alpha1 fist sample (in radians)\n% alpha2 second sample (in radians)\n% res resolution at which the cdf is evaluated\n% vis_on display graph\n%\n% Output:\n% pval p-value; the smallest of .10, .05, .02, .01, .005, .002,\n% .001, for which the test statistic is still higher\n% than the respective critical value. this is due to\n% the use of tabulated values. if p>.1, pval is set to 1.\n% k test statistic\n% K critical value\n% \n% References:\n% Batschelet, 1980, p. 112\n%\n% Circular Statistics Toolbox for Matlab\n\n% Update 2012\n% By Marc J. Velasco and Philipp Berens, 2009\n% velasco@ccs.fau.edu\n\n\nif nargin < 3\n res = 100;\nend\nif nargin < 4\n vis_on = 0;\nend\n\nn = length(alpha1(:));\nm = length(alpha2(:));\n\n% create cdfs of both samples\n[phis1 cdf1 phiplot1 cdfplot1] = circ_samplecdf(alpha1, res);\n[foo, cdf2 phiplot2 cdfplot2] = circ_samplecdf(alpha2, res); %#ok\n\n% maximal difference between sample cdfs\n[dplus, gdpi] = max([0 cdf1-cdf2]);\n[dminus, gdmi] = max([0 cdf2-cdf1]);\n\n% calculate k-statistic\nk = n * m * (dplus + dminus);\n\n% find p-value\n[pval K] = kuiperlookup(min(n,m),k/sqrt(n*m*(n+m)));\nK = K * sqrt(n*m*(n+m));\n\n\n% visualize\nif vis_on\n figure \n plot(phiplot1, cdfplot1, 'b', phiplot2, cdfplot2, 'r');\n hold on\n plot([phis1(gdpi-1), phis1(gdpi-1)], [cdf1(gdpi-1) cdf2(gdpi-1)], 'o:g');\n plot([phis1(gdmi-1), phis1(gdmi-1)], [cdf1(gdmi-1) cdf2(gdmi-1)], 'o:g');\n hold off\n set(gca, 'XLim', [0, 2*pi]);\n set(gca, 'YLim', [0, 1.1]);\n xlabel('Circular Location')\n ylabel('Sample CDF')\n title('CircStat: Kuiper test')\n h = legend('Sample 1', 'Sample 2', 'Location', 'Southeast');\n set(h,'box','off')\n set(gca, 'XTick', pi*(0:.25:2))\n set(gca, 'XTickLabel', {'0', '', '', '', 'pi', '', '', '', '2pi'}) \nend\n\n\n\nend\n\nfunction [p K] = kuiperlookup(n, k)\n\nload kuipertable.mat;\nalpha = [.10, .05, .02, .01, .005, .002, .001];\nnn = ktable(:,1); %#ok\n\n% find correct row of the table\n[easy row] = ismember(n, nn);\nif ~easy\n % find closest value if no entry is present)\n row = length(nn) - sum(n\n end\nend\n\n% find minimal p-value and test-statistic\nidx = find(ktable(row,2:end)= 2);\nif b(1)+b(2)+b(3)+b(4) < 2\n degen = 1;\n p1ext = [0 0];\n p2ext = [0 0];\n return;\nelse\n degen = 0;\nend\n\n% b = find(b);\n% p1ext = intp{b(1)};\n% p2ext = intp{b(2)};\n\np = cat(1, intp{logical(b)});\n% p = unique(p, 'rows');\n% assert(size(p,1)==2);\np1ext = p(1,:);\np2ext = p(2,:);\n\n\n%%\nfunction flag = isinimage(p, imgwidth, imgheight)\nif p(1)>=1 && p(1)<=imgwidth && p(2)>=1 && p(2)<=imgheight\n flag = 1;\nelse\n flag = 0;\nend\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/VP/vanishingpoint/extline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7653945040516292}} {"text": "function r = msmoothboxrnd(a,b,sigma,n)\n%MSMOOTHBOXRND Random arrays from the multivariate smooth-box distribution.\n% R = MSMOOTHBOXRND(A,B,SIGMA) returns an N-by-D matrix R of random \n% vectors chosen from the multivariate smooth-box distribution \n% with pivots A and B and scale SIGMA. A, B and SIGMA are N-by-D matrices, \n% and MSMOOTHBOXRND generates each row of R using the corresponding row \n% of A, B and SIGMA.\n%\n% R = MSMOOTHBOXRND(A,B,SIGMA,N) returns a N-by-D matrix R of random \n% vectors chosen from the multivariate smooth-box distribution \n% with pivots A and B and scale SIGMA.\n%\n% See also MSMOOTHBOXPDF.\n\n% Luigi Acerbi 2022\n\n[Na,Da] = size(a);\n[Nb,Db] = size(b);\n[Nsigma,Dsigma] = size(sigma);\n\nif any(sigma(:) <= 0)\n error('msmoothboxrnd:NonPositiveSigma', ...\n 'All elements of SIGMA should be positive.'); \nend\n\nif nargin < 4 || isempty(n)\n n = max([Na,Nb,Nsigma]);\nelse\n if (Na ~= 1 && Na ~= n) || (Nb ~= 1 && Nb ~= n) || ...\n (Nsigma ~= 1 && Nsigma ~= n)\n error('msmoothboxrnd:SizeError', ...\n 'A, B, SIGMA should be 1-by-D or N-by-D arrays.');\n end \nend\nif Na ~= Nb || Da ~= Db || Na ~= Nsigma || Da ~= Dsigma\n error('msmoothboxrnd:SizeError', ...\n 'A, B, SIGMA should be arrays of the same size.');\nend\n\nD = Da;\n\nif size(a,1) == 1; a = repmat(a,[n,1]); end\nif size(b,1) == 1; b = repmat(b,[n,1]); end\nif size(sigma,1) == 1; sigma = repmat(sigma,[n,1]); end\n\nr = zeros(n,D);\n\nnf = 1 + 1/sqrt(2*pi)./sigma.*(b - a);\n\n% Sample one dimension at a time\nfor d = 1:D \n % Draw component (left/right tails or plateau)\n u = nf(:,d) .* rand(n,1);\n \n % Left Gaussian tails\n idx = u < 0.5;\n if any(idx)\n z1 = abs(randn(sum(idx),1).*sigma(idx,d)); \n r(idx,d) = a(idx) - z1;\n end\n \n % Right Gaussian tails\n idx = (u >= 0.5 & u < 1);\n if any(idx)\n z1 = abs(randn(sum(idx),1).*sigma(idx,d));\n r(idx,d) = b(idx) + z1;\n end\n \n % Plateau\n idx = u >= 1;\n if any(idx)\n r(idx,d) = a(idx,d) + (b(idx,d) - a(idx,d)).*rand(sum(idx),1);\n end\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/shared/msmoothboxrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7653944946326282}} {"text": "function c = i4_division ( a, b )\n\n%*****************************************************************************80\n%\n%% I4_DIVISION returns the result of integer division.\n%\n% Discussion:\n%\n% This routine computes C = A / B, where the result is rounded to the\n% integer value nearest 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer A, B, the number to be divided,\n% and the divisor.\n%\n% Output, integer C, the rounded result of the division.\n%\n if ( a * b < 0.0 )\n s = -1;\n else\n s = +1;\n end\n\n a = abs ( a );\n b = abs ( b );\n c = s * floor ( a / b );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4_division.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7653827684204362}} {"text": " function xs = alg_art1(x, At, y, varargin)\n%|function xs = alg_art1(x, At, y, [options])\n%| classical ART algorithm, aka, Kaczmarz algorithm; tries to solve y=Ax\n%|\n%| in\n%|\tx\t[np 1]\t\tinitial guess, possibly empty\n%|\tCaution: x must be in the range of A' for convergence!\n%|\tAt\t[np nd]\t\t(hermitian) *transpose* of system matrix\n%|\ty\t[nb na]\t\tmeasurement\n%|\n%| option\n%|\twi\t[nb na]\t\tweights\n%|\tniter\t\t\t# of iterations\n%|\tisave\t\t\tdefault: [] 'last'\n%|\tpixmin\n%|\tpixmax\n%|\tanorms\t[nd 1]\t\tsee below\n%|\teps\n%|\n%| out\n%|\txs\t[np niter]\titerates\n%|\n%| Copyright 2006-4-2, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(x, 'test'), alg_art1_test, return, end\nif nargin < 3, ir_usage, end\nif isempty(x), x = zeros(nrow(A),1); end\n\n% defaults\narg.niter = 1;\narg.isave = [];\narg.anorms = [];\narg.eps = eps;\n%arg.pixmax = inf;\n%arg.pixmin = -inf;\n\n% options \narg = vararg_pair(arg, varargin);\n\narg.isave = iter_saver(arg.isave, arg.niter);\n\n[nb na] = size(y);\nstarts = subset_start(na);\n\n% For WLS, premultiply y and postmultiply At by W^{1/2}\n%Wh = spdiag(sqrt(wi(:)), 'nowarn');\n%y = Wh * y(:);\n%At = At * Wh;\n\n% weighted row norms\nif isempty(arg.anorms)\n\targ.anorms = sum(At.^2); % | e_i' A |^2\nend\n\niglist = col(outer_sum(1:nb, (starts-1)*nb));\niglist = iglist(arg.anorms(iglist) ~= 0);\n\nadenom = arg.anorms + eps; % trick:\n\nnp = length(x);\nxs = zeros(np, length(arg.isave));\nif any(arg.isave == 0)\n\txs(:, arg.isave == 0) = x;\nend\n\nticker(mfilename, 1, arg.niter)\n\nfor iter=1:arg.niter\n\tticker(mfilename, iter, arg.niter)\n\n\tfor ii=iglist'\n\t\tai = At(:,ii);\n\t\tstep = (y(ii) - ai' * x) / adenom(ii);\n\t\tx = x + ai * step;\n\n%\t\ttodo: try following approach to see if faster\n%\t\t[j ignore ai] = find(At(:,ii));\n%\t\txj = x(j);\n%\t\tstep = (y(ii) - ai' * xj) / adenom(ii);\n%\t\tx(j) = xj - step * ai;\n\tend\n\n\tif any(arg.isave == iter)\n\t\txs(:, arg.isave == iter) = x;\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/general/alg_art1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7653827682254203}} {"text": "function result = graph_adj_is_node_connected ( adj, nnode )\n\n%*****************************************************************************80\n%\n%% GRAPH_ADJ_IS_NODE_CONNECTED determines if a graph is nodewise connected.\n%\n% Definition:\n%\n% A graph is nodewise connected if, from every node, there is a path\n% to any other node.\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 ADJ(NNODE,NNODE), the adjacency matrix for the \n% graph. ADJ(I,J) is nonzero if there is an edge from node I to node J.\n%\n% Input, integer NNODE, the number of nodes.\n%\n% Output, integer RESULT.\n% 0, the graph is not nodewise connected.\n% 1, the graph is nodewise connected.\n%\n\n%\n% FOUND(I) is 1 if node I has been reached.\n% LIST(I) contains a list of the nodes as they are reached.\n%\n list(1:nnode) = 0;\n found(1:nnode) = 0;\n%\n% Start at node 1.\n%\n found(1) = 1;\n list(1) = 1;\n ilo = 1;\n ihi = 1;\n%\n% From the batch of nodes found last time, LIST(ILO:IHI),\n% look for unfound neighbors, and store their indices in LIST(JLO:JHI).\n%\n while ( 1 )\n\n jlo = ihi + 1;\n jhi = ihi;\n\n for ii = ilo : ihi\n\n i = list(ii);\n\n for j = 1 : nnode\n\n if ( adj(i,j) ~= 0 || adj(j,i) ~= 0 )\n\n if ( found(j) == 0 )\n jhi = jhi + 1;\n list(jhi) = j;\n found(j) = 1;\n end\n\n end\n\n end\n\n end\n%\n% If no neighbors were found, exit.\n%\n if ( jhi < jlo )\n break\n end\n%\n% If neighbors were found, then go back and find THEIR neighbors.\n%\n ilo = jlo;\n ihi = jhi;\n \n end\n%\n% No more neighbors were found. Have we reached all nodes?\n%\n if ( ihi == nnode )\n result = 1;\n else\n result = 0;\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/treepack/graph_adj_is_node_connected.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7653536866956162}} {"text": "function integral = sphere01_monomial_integral ( e )\n\n%*****************************************************************************80\n%\n%% SPHERE01_MONOMIAL_INTEGRAL returns monomial integrals on the unit sphere.\n%\n% Discussion:\n%\n% The integration region is\n%\n% X^2 + Y^2 + Z^2 = 1.\n%\n% The monomial is F(X,Y,Z) = X^E(1) * Y^E(2) * Z^E(3).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Academic Press, 1984, page 263.\n%\n% Parameters:\n%\n% Input, integer E(3), the exponents of X, Y and Z in the\n% monomial. Each exponent must be nonnegative.\n%\n% Output, real INTEGRAL, the integral.\n%\n if ( any ( e(1:3) < 0 ) )\n integral = - Inf;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE01_MONOMIAL_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' All exponents must be nonnegative.\\n' );\n fprintf ( 1, ' E(1) = %d\\n', e(1) );\n fprintf ( 1, ' E(2) = %d\\n', e(2) );\n fprintf ( 1, ' E(3) = %d\\n', e(3) );\n error ( 'SPHERE01_MONOMIAL_INTEGRAL - Fatal error!' );\n end\n\n if ( all ( e(1:3) == 0 ) )\n\n integral = 2.0 * sqrt ( pi^3 ) / gamma ( 1.5 );\n\n elseif ( any ( mod ( e(1:3), 2 ) == 1 ) )\n\n integral = 0.0;\n\n else\n\n integral = 2.0;\n\n for i = 1 : 3\n integral = integral * gamma ( 0.5 * ( e(i) + 1 ) );\n end\n\n integral = integral / gamma ( 0.5 * sum ( e(1:3) + 1 ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_quad/sphere01_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7653204804359371}} {"text": "function [R Rx Ry Rz] = angles2rotmat(angles)\n% [R Rx Ry Rz] = angles2rotmat(angles)\n%\n% Convert 3 euler angles into a rotation matrix\n%\n% angles is a 3x1 vector in radians\n% angles(1) - pitch - rotation about x or LR (gamma)\n% angles(2) - yaw - rotation about y or AP (beta)\n% angles(3) - roll - rotation about z or SI (alpha)\n% R = Rz*Ry*Rx;\n%\n% See also: rotmat2angles\n% Ref: Craig, Intro to Robotics\n%\n% $Id: angles2rotmat.m,v 1.4 2011/03/02 00:04:12 nicks Exp $\n\n%\n% angles2rotmat.m\n%\n% Original Author: Doug Greve\n% CVS Revision Info:\n% $Author: nicks $\n% $Date: 2011/03/02 00:04:12 $\n% $Revision: 1.4 $\n%\n% Copyright © 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\nR = [];\nRx = [];\nRy = [];\nRz = [];\nif(nargin ~= 1)\n fprintf('R = angles2rotmat(angles)\\n');\n return;\nend\n\ngamma = angles(1);\nbeta = angles(2);\nalpha = angles(3);\n\nRx = zeros(3,3);\nRx(1,1) = +1;\nRx(2,2) = +cos(gamma);\nRx(2,3) = -sin(gamma);\nRx(3,2) = +sin(gamma);\nRx(3,3) = +cos(gamma);\n\nRy = zeros(3,3);\nRy(1,1) = +cos(beta);\nRy(1,3) = +sin(beta);\nRy(2,2) = +1;\nRy(3,1) = -sin(beta);\nRy(3,3) = +cos(beta);\n\nRz = zeros(3,3);\nRz(1,1) = +cos(alpha);\nRz(1,2) = -sin(alpha);\nRz(2,1) = +sin(alpha);\nRz(2,2) = +cos(alpha);\nRz(3,3) = +1;\n\nR = Rz*Ry*Rx;\n\nreturn;\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/external/freesurfer/angles2rotmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7653204771039313}} {"text": "function [ pp, normal ] = plane_exp2normal_3d ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% PLANE_EXP2NORMAL_3D converts an explicit plane to normal form in 3D.\n%\n% Discussion:\n%\n% The explicit form of a plane in 3D is\n%\n% the plane through P1, P2 and P3.\n%\n% The normal form of a plane in 3D is\n%\n% PP, a point on the plane, and\n% N, the unit normal to the plane.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(3), P2(3), P3(3), three points on the plane.\n%\n% Output, real PP(3), a point on the plane.\n%\n% Output, real NORMAL(3), a unit normal vector to the plane.\n%\n dim_num = 3;\n\n pp(1:dim_num) = p1(1:dim_num);\n\n normal(1) = ( p2(2) - p1(2) ) * ( p3(3) - p1(3) ) ...\n - ( p2(3) - p1(3) ) * ( p3(2) - p1(2) );\n\n normal(2) = ( p2(3) - p1(3) ) * ( p3(1) - p1(1) ) ...\n - ( p2(1) - p1(1) ) * ( p3(3) - p1(3) );\n\n normal(3) = ( p2(1) - p1(1) ) * ( p3(2) - p1(2) ) ...\n - ( p2(2) - p1(2) ) * ( p3(1) - p1(1) );\n\n norm = sqrt ( sum ( normal(1:dim_num).^2 ) );\n\n if ( norm == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_EXP2NORMAL_3D - Fatal error!\\n' );\n fprintf ( 1, ' The normal vector is null.\\n' );\n fprintf ( 1, ' Two points coincide, or nearly so.\\n' );\n error ( 'PLANE_EXP2NORMAL_3D - Fatal error!' );\n end\n\n normal(1:dim_num) = normal(1:dim_num) / norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_exp2normal_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7653204743026123}} {"text": "clc\nclear\nhold on\n\nn=100; % number of intervals (i.e. parametric curve would be evaluted n+1 times)\nk=0.5522847498; % kappa (See documentation how this value is obtained)\n\n% First Quadrant\nPx=[1 1 k 0];\t\nPy=[0 k 1 1];\n\nPlotBezier1(Px,Py,n);\n\n% Second Quadrant\nPx=[0 -k -1 -1];\t\nPy=[1 1 k 0];\nPlotBezier1(Px,Py,n)\n\n% Third Quadrant\nPx=[-1 -1 -k 0];\t\nPy=[ 0 -k -1 -1];\nPlotBezier1(Px,Py,n)\n\n% Fourth Quadrant \nPx=[ 0 k 1 1];\t\nPy=[-1 -1 -k 0];\nPlotBezier1(Px,Py,n)\n\ntitle('Approximation of Circle using Cubic Bezier');\n\nhold off\n\n% % % --------------------------------\n% % % Author: Dr. Murtaza Khan\n% % % Email : drkhanmurtaza@gmail.com\n% % % --------------------------------", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6844-approximation-of-circle-using-cubic-bezier-curve/circleaproxbezier/TestCircleApproxByCubicBezier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7653136904849189}} {"text": "function y = testfunctions(varargin)\n% TESTFUNCTIONS Integration test functions of A. Genz\n% Y = TESTFUNCTIONS(X1, X2, ..., XD, TYPE, C, W) Evaluates test\n% function TYPE at the point (X1,...,XN). C and W are arrays of\n% constants defining the test function (see below). The test\n% functions are defined according to A. Genz: A package for\n% testing multiple integration subroutines, in Numerical\n% Integration, P. Keast and G. Fairweather (Eds.), D. Riedel,\n% pp. 337-340, 1987. The functions are defined on [0 1]^d.\n%\n% TYPE = 'oscillatory' | TYPE = 1:\n% f(x) = cos(2*pi*w_1 + sum_{i=1}^d ( c_i * x_i ) )\n%\n% TYPE = 'product peak' | TYPE = 2:\n% f(x) = prod_{i=1}^d ( c_i^{-2} + (x_i - w_i)^2 )^{-1}\n%\n% TYPE = 'corner peak' | TYPE = 3:\n% f(x) = ( 1 + sum_{i=1}^d (c_i * x_i) )^(-(d+1))\n%\n% TYPE = 'gaussian' | TYPE = 4:\n% f(x) = exp( - sum_{i=1}^d c_i^2 * (x_i - w_i)^2 )\n%\n% TYPE = 'continuous' | TYPE = 5:\n% f(x) = exp( - sum_{i=1}^d c_i * abs(x_i - w_i) )\n%\n% TYPE = 'discontinuous' | TYPE = 6:\n% f(x) = { 0 , if x_1>w_1 or x_2>w_2,\n% { exp( sum_{i=1}^d c_i * x_i ) , otherwise\n%\n% With the parameters c = (c_1, ..., c_d) and w = (w_1, ..., w_d).\n% d denotes the dimension of the function.\n%\n% Examples:\n% testfunctions(0.5, 0.5, 'product peak', [2, 5.25], [0.2, 0.7])\n% testfunctions(0.5, 0.5, 2, [2, 5.25], [0.2, 0.7])\n%\n% x = linspace(0,1,20);\n% [X,Y] = meshgrid(x,x);\n% surf(X,Y, ...\n% testfunctions(X, Y, 'product peak', [2, 5.25], [0.2 0.7]));\n \n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.0\n% Date : August 2, 2003\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\ntype = varargin{end-2};\nc = varargin{end-1};\nw = varargin{end};\n\t\nif isa(type, 'char')\n\tfnames = {'oscillatory', 'product peak', 'corner peak', 'gaussian', ...\n\t\t\t\t\t\t'continuous', 'discontinuous'};\t\n\tfor k = 1:length(fnames)\n\t\tif strcmp(fnames{k},type)\n\t\t\ttype = k;\n\t\t\tbreak\n\t\tend\n\tend\nend\n\nd = length(c);\n\nswitch type\n case 1 % oscillatory\n\ttemp = 2*pi*w(1);\n\tfor i = 1:d\n\t\ttemp = temp + c(i).*varargin{i};\n\tend\n\ty = cos(temp);\n \n case 2 % product peak\n\ttemp = 1;\n\tfor i = 1:d\n\t\ttemp = temp .* (c(i)^(-2)+(varargin{i}-w(i)).^2);\n\tend\n\ty = 1./temp;\n\t\n case 3 % corner peak\n\ttemp = 1;\n\tfor i = 1:d\n\t\ttemp = temp + c(i).*varargin{i};\n\tend\n\ty = temp .^ (-(d+1));\n\t\n case 4 % gaussian\n\ttemp = 0;\n\tfor i = 1:d\n\t\ttemp = temp + c(i)^2 .* (varargin{i} - w(i)).^2;\n\tend\n\ty = exp(-temp);\n\t\n case 5 % continuous\n\ttemp = 0;\n\tfor i = 1:d\n\t\ttemp = temp + c(i) .* abs(varargin{i} - w(i));\n\tend\n\ty = exp(-temp);\n\t\n case 6 % discontinuous\n\ttemp = 0;\n\tif d >= 2\n\t\tmask = varargin{1} > w(1) | varargin{2} > w(2);\n\telse\n\t\tmask = varargin{1} > w(1);\n\tend\n\tfor i = 1:d\n\t\ttemp = temp + (c(i) .* varargin{i});\n\tend\n\ty = exp(temp) .* (~mask);\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spinterp/examples/testfunctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7653136883989576}} {"text": "function [normed_traindata,normed_testdata ] = normalization(traindata,testdata)\n% Calculating mean and standard deviation of train samples on each band\n% Using calculated mean and standard deviation to perform normalization on\n% both train samples and test samples\n\nmean_val=mean(traindata,1);\nsigma_val=std(traindata,0,1);\n \ntraindata=bsxfun(@minus,traindata,mean_val);\nnormed_traindata=bsxfun(@rdivide,traindata,sigma_val);\n \ntestdata=bsxfun(@minus,testdata,mean_val);\nnormed_testdata=bsxfun(@rdivide,testdata,sigma_val);\n\n%selTrainData=bsxfun(@rdivide,selTrainData,sum(selTrainData,2));\n%selTestData=bsxfun(@rdivide,selTestData,sum(selTestData,2)); \n\n% mean_val = mean(traindata,1);\n% normed_traindata = bsxfun(@minus,traindata,mean_val);\n% \n% sigma_val = std(normed_traindata,0,1);\n% normed_traindata = bsxfun(@rdivide,normed_traindata,sigma_val);\n% normed_testdata = bsxfun(@minus,testdata,mean_val);\n% normed_testdata = bsxfun(@rdivide,normed_testdata,sigma_val);\n \n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/common tool/normalization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7653079246530727}} {"text": "function [ n_data, x, fx ] = cinh_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CINH_VALUES returns some values of the alternate hyperbolic cosine integral function.\n%\n% Discussion:\n%\n% The alternate hyperbolic cosine integral is defined by\n%\n% CINH(X) =integral ( 0 <= T < X ) ( cosh ( T ) - 1 ) / T dT\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Integrate [ ( Cosh[t] - 1 ) / t, { t, 0, x } ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964,\n% ISBN: 0-486-61272-4,\n% LC: QA47.A34.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Cambridge University Press, 1999,\n% ISBN: 0-521-64314-7,\n% LC: QA76.95.W65.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 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 = 17;\n\n fx_vec = [ ...\n 0.00000000000000000, ...\n 0.06315467070191883, ...\n 0.09136085223843649, ...\n 0.1250284547325902, ...\n 0.1643278712460683, ...\n 0.2094587379417273, ...\n 0.2606512760786754, ...\n 0.3823047024751071, ...\n 0.5318061742668980, ...\n 0.7122865135136963, ...\n 0.9275748842583805, ...\n 1.182304077185436, ...\n 2.030919091578478, ...\n 3.284564141195967, ...\n 5.129213294250493, ...\n 7.850037532801762, ...\n 11.88451858691463 ];\n\n x_vec = [ ...\n 0.0, ...\n 0.5, ...\n 0.6, ...\n 0.7, ...\n 0.8, ...\n 0.9, ...\n 1.0, ...\n 1.2, ...\n 1.4, ...\n 1.6, ...\n 1.8, ...\n 2.0, ...\n 2.5, ...\n 3.0, ...\n 3.5, ...\n 4.0, ... \n 4.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 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/cinh_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7652822886132788}} {"text": "function [res,tau1,tau2,tau,p] = AccSumHugeN(p)\n%ACCSUMHUGEN Faithful rounding of sum(p) for huge dimension\n%\n% res = AccSumHugeN(p)\n%\n%On return, res is a faithful rounding of sum(p), also in the presence\n% of underflow. Input vector p may be single or double precision.\n%\n%Implements Algorithm 8.1 from\n% S.M. Rump, T. Ogita, S. Oishi: Accurate Floating-point Summation II: \n% Sign, K-fold Faithful and Rounding to Nearest, Siam J. Sci. Comput., \n% 31(2):1269-1302, 2008.\n%Requires (4m+4K+3)n flops for m executions of repeat-until loop in \n% Transform and K executions of the while-loop.\n%\n%Reference implementation! Slow due to interpretation!\n%\n\n% written 03/03/07 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest, complex input\n%\n\n if ~isreal(p)\n res = complex(AccSumHugeN(real(p)),AccSumHugeN(imag(p)));\n return\n end\n \n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n if isa(p,'double')\n nmax = 2^50; % nmax = 1,125,899,906,842,624\n else\n nmax = 2^21; % nmax = 2,097,152\n end\n if length(p)>nmax\n error(['maximum length of input vector for AccSumHugeN ' int2str(nmax) '.'])\n end\n \n kPhi = 2;\n [tau1,tau2,p,sigma,Ms] = Transform(p,0,kPhi); % Ms = 2^M\n if sigma<=realmin % p_i identical zero\n res = tau1;\n tau = 0*res; % make sure tau has same precision\n if rndold, setround(rndold); end\n return\n end\n if isa(p,'double'), prec='double'; else prec='single'; end \n u = 0.5*eps(prec);\n tau = zeros(1,16);\n K = 0;\n phi = Ms*u;\n factor = 2*Ms*Ms*u;\n sigmas = phi*sigma;\n while 1\n K = K+1;\n sigma = sigmas;\n [tau(K),p] = ExtractVector(p,sigma);\n sigmas = phi*sigma;\n if ( factor*sigma<=abs(tau1) ) | ( sigma<=realmin )\n taus = tau2 + sum(p);\n for k=K:-1:1\n taus = taus + tau(k);\n end\n res = tau1 + taus;\n if rndold, setround(rndold); end\n return\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/accsumdot/AccSumHugeN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7652822846818157}} {"text": "function centroid = polygonCentroid3d(varargin)\n%POLYGONCENTROID3D Centroid (or center of mass) of a polygon\n%\n% PTC = polygonCentroid3d(POLY)\n% Computes center of mass of a polygon defined by POLY. POLY is a N-by-3\n% array of double containing coordinates of polygon vertices.\n%\n% PTC = polygonCentroid3d(VX, VY, VZ)\n% Specifies vertex coordinates as three separate arrays.\n%\n% Example\n% % compute centroid of a basic polygon\n% poly = [0 0 0; 10 0 10;10 10 20;0 10 10];\n% centro = polygonCentroid3d(poly)\n% centro =\n% 5.0000 5.0000 10.0000\n%\n% See also\n% polygons3d, polygonArea3d, polygonCentroid\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2007-09-18\n% Copyright 2007 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n\nif nargin == 1\n % polygon is given as a single argument\n pts = varargin{1};\n \nelseif nargin == 2\n % polygon is given as 3 corodinate arrays\n px = varargin{1};\n py = varargin{2};\n pz = varargin{3};\n pts = [px py pz];\nend\n\n% create supporting plane (assuming first 3 points are not colinear...)\nplane = createPlane(pts(1:3, :));\n\n% project points onto the plane\npts = planePosition(pts, plane);\n\n% compute centroid in 2D\ncentro2d = polygonCentroid(pts);\n\n% project back in 3D\ncentroid = planePoint(plane, centro2d);\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/polygonCentroid3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7652822777400125}} {"text": "function theta = polygon3dNormalAngle(points, ind)\n%POLYGON3DNORMALANGLE Normal angle at a vertex of the 3D polygon.\n%\n% THETA = polygon3DNormalAngle(POLYGON, IND)\n% where POLYGON is a set of points, and IND is index of a point in\n% polygon. The function compute the angle of the normal cone localized at\n% this vertex.\n% If IND is a vector of indices, normal angle is computed for each vertex\n% specified by IND.\n%\n% Example\n% % create an equilateral triangle in space\n% poly3d = [1 1 0;-1 0 1;0 -1 -1];\n% % compute each normal angle\n% theta = polygon3dNormalAngle(poly3d, 1:size(poly3d, 1));\n% % sum of normal angles must be equal to 2*PI for simple polygons\n% sum(theta)\n%\n% IMPORTANT NOTE: works only for convex angles ! ! ! !\n%\n% See also\n% polygons3d, faceNormalAngle\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2005-11-30\n% Copyright 2005 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n\n% number of points\nnp = size(points, 1);\n\n% number of angles to compute\nnv = length(ind);\n\ntheta = zeros(nv, 1);\n\nfor i=1:nv\n p0 = points(ind(i), :);\n \n if ind(i)==1\n p1 = points(np, :);\n else\n p1 = points(ind(i)-1, :);\n end\n \n if ind(i)==np\n p2 = points(1, :);\n else\n p2 = points(ind(i)+1, :);\n end\n \n theta(i) = pi - anglePoints3d(p1, p0, p2);\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/polygon3dNormalAngle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7652822733052692}} {"text": "function fem2d_poisson_rectangle_linear ( nx, ny )\n\n%*****************************************************************************80\n%\n%% MAIN is the main routine for FEM2D_POISSON_RECTANGLE_LINEAR.\n%\n% Discussion:\n%\n% This program solves\n%\n% - d2U(X,Y)/dx2 - d2U(X,Y)/dy2 = F(X,Y)\n%\n% in a rectangular region in the plane.\n%\n% Along the boundary of the region, Dirichlet conditions\n% are imposed:\n%\n% U(X,Y) = G(X,Y)\n%\n% The code uses continuous piecewise linear basis functions on\n% triangles determined by a uniform grid of NX by NY points.\n%\n% u = sin ( pi * x ) * sin ( pi * y ) + x\n%\n% dudx = pi * cos ( pi * x ) * sin ( pi * y ) + 1\n% dudy = pi * sin ( pi * x ) * cos ( pi * y )\n%\n% d2udx2 = - pi * pi * sin ( pi * x ) * sin ( pi * y )\n% d2udy2 = - pi * pi * sin ( pi * x ) * sin ( pi * y )\n%\n% rhs = 2 * pi * pi * sin ( pi * x ) * sin ( pi * y )\n%\n% THINGS YOU CAN EASILY CHANGE:\n%\n% 1) Change NX or NY, the number of nodes in the X and Y directions.\n% 2) Change XL, XR, YB, YT, the left, right, bottom and top limits\n% of the rectangle.\n% 3) Change the exact solution in the EXACT routine, but make sure you also\n% modify the formula for RHS in the assembly portion of the program%\n%\n% HARDER TO CHANGE:\n%\n% 4) Change from \"linear\" to \"quadratic\" triangles;\n% 5) Change the region from a rectangle to a general triangulated region;\n% 6) Handle Neumann boundary conditions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NX, NY, the number of nodes in the X and Y directions.\n%\n% Local Parameters:\n%\n% Local, sparse real A(NODE_NUM,NODE_NUM), the finite element system matrix.\n%\n% Local, real B(NODE_NUM), the finite element right hand side.\n%\n% Local, real C(NODE_NUM), the finite element coefficient vector.\n%\n% Local, integer ELEMENT_NODE(3,ELEMENT_NUM), the indices of the nodes\n% that form each element.\n%\n% Local, integer ELEMENT_NUM, the number of elements.\n%\n% Local, integer NODE_NUM, the number of nodes.\n%\n% Local, real NODE_XY(2,NODE_NUM), the X and Y coordinates of each node.\n%\n% Local, real XL, the X coordinate of the left boundary.\n%\n% Local, real XR, the X coordinate of the right boundary.\n%\n% Local, real YB, the Y coordindate of the bottom boundary.\n%\n% Local, real YT, the Y coordinate of the top boundary.\n%\n timestamp ( );\n\n element_order = 3;\n\n xl = 0.0;\n xr = 1.0;\n yb = 0.0;\n yt = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_RECTANGLE_LINEAR\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solution of the Poisson equation:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' - Uxx - Uyy = F(x,y) inside the region,\\n' );\n fprintf ( 1, ' U(x,y) = G(x,y) on the boundary of the region.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The region is a rectangle, defined by:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %f = XL<= X <= XR = %f\\n', xl, xr );\n fprintf ( 1, ' %f = YB<= Y <= YT = %f\\n', yb, yt );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The finite element method is used, with piecewise\\n' );\n fprintf ( 1, ' linear basis functions on 3 node triangular\\n' );\n fprintf ( 1, ' elements.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The corner nodes of the triangles are generated by an\\n' );\n fprintf ( 1, ' underlying grid whose dimensions are\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NX = %d\\n', nx );\n fprintf ( 1, ' NY = %d\\n', ny );\n%\n% NODE COORDINATES\n%\n% Numbering of nodes is suggested by the following 5x10 example:\n%\n% J=5 | K=41 K=42 ... K=50\n% ... |\n% J=2 | K=11 K=12 ... K=20\n% J=1 | K= 1 K= 2 K=10\n% +--------------------\n% I= 1 I= 2 ... I=10\n%\n node_num = nx * ny;\n\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n node_xy = zeros(2,node_num);\n\n k = 0;\n for j = 1 : ny\n for i = 1 : nx\n\n k = k + 1;\n\n node_xy(1,k) = ( ( nx - i ) * xl ...\n + ( i - 1 ) * xr ) ...\n / ( nx - 1 );\n\n node_xy(2,k) = ( ( ny - j ) * yb ...\n + ( j - 1 ) * yt ) ...\n / ( ny - 1 );\n\n end\n end\n%\n% ELEMENT array\n%\n% Organize the nodes into a grid of 3-node triangles.\n% Here is part of the diagram for a 5x10 example:\n%\n% | \\ | \\ | \\ |\n% | \\| \\| \\|\n% 21---22---23---24--\n% |\\ 8 |\\10 |\\12 |\n% | \\ | \\ | \\ |\n% | \\ | \\ | \\ | \\ |\n% | 7\\| 9\\| 11\\| \\|\n% 11---12---13---14---15---16---17---18---19---20\n% |\\ 2 |\\ 4 |\\ 6 |\\ 8| |\\ 18|\n% | \\ | \\ | \\ | \\ | | \\ |\n% | \\ | \\ | \\ | \\ | ... | \\ |\n% | 1\\| 3\\| 5\\| 7 \\| |17 \\|\n% 1----2----3----4----5----6----7----8----9---10\n%\n element_num = 2 * ( nx - 1 ) * ( ny - 1 );\n\n fprintf ( 1, ' Number of elements = %d\\n', element_num );\n\n element_node = zeros ( element_order, element_num );\n\n k = 0;\n\n for j = 1 : ny - 1\n for i = 1 : nx - 1\n%\n% (I,J+1)-\n% | \\ \n% | \\ \n% | \\ |\n% (I,J)---(I+1,J)\n%\n k = k + 1;\n element_node(1,k) = i + ( j - 1 ) * nx;\n element_node(2,k) = i + 1 + ( j - 1 ) * nx;\n element_node(3,k) = i + j * nx;\n%\n% (I,J+1)--(I+1,J+1)\n% | \\ |\n% \\ |\n% \\ |\n% -(I+1,J)\n%\n k = k + 1;\n element_node(1,k) = i + 1 + j * nx;\n element_node(2,k) = i + j * nx;\n element_node(3,k) = i + 1 + ( j - 1 ) * nx;\n\n end\n end\n%\n% ASSEMBLE THE SYSTEM\n%\n% Assemble the coefficient matrix A and the right-hand side B of the\n% finite element equations, ignoring boundary conditions.\n%\n b = zeros(node_num,1);\n a = sparse ( [], [], [], node_num, node_num );\n\n for e = 1 : element_num\n\n i1 = element_node(1,e);\n i2 = element_node(2,e);\n i3 = element_node(3,e);\n\n area = 0.5 * ...\n ( node_xy(1,i1) * ( node_xy(2,i2) - node_xy(2,i3) ) ...\n + node_xy(1,i2) * ( node_xy(2,i3) - node_xy(2,i1) ) ...\n + node_xy(1,i3) * ( node_xy(2,i1) - node_xy(2,i2) ) );\n%\n% Consider each quadrature point.\n% Here, we use the midside nodes as quadrature points.\n%\n for q1 = 1 : 3\n\n q2 = mod ( q1, 3 ) + 1;\n\n nq1 = element_node(q1,e);\n nq2 = element_node(q2,e);\n\n xq = 0.5 * ( node_xy(1,nq1) + node_xy(1,nq2) );\n yq = 0.5 * ( node_xy(2,nq1) + node_xy(2,nq2) );\n wq = 1.0 / 3.0;\n%\n% Consider each test function in the element.\n%\n for ti1 = 1 : element_order\n\n ti2 = mod ( ti1, 3 ) + 1;\n ti3 = mod ( ti1 + 1, 3 ) + 1;\n\n nti1 = element_node(ti1,e);\n nti2 = element_node(ti2,e);\n nti3 = element_node(ti3,e);\n\n qi = 0.5 * ( ...\n ( node_xy(1,nti3) - node_xy(1,nti2) ) * ( yq - node_xy(2,nti2) ) ...\n - ( node_xy(2,nti3) - node_xy(2,nti2) ) * ( xq - node_xy(1,nti2) ) ) ...\n / area;\n dqidx = - 0.5 * ( node_xy(2,nti3) - node_xy(2,nti2) ) / area;\n dqidy = 0.5 * ( node_xy(1,nti3) - node_xy(1,nti2) ) / area;\n\n rhs = 2.0 * pi * pi * sin ( pi * xq ) * sin ( pi * yq );\n\n b(nti1) = b(nti1) + area * wq * rhs * qi;\n%\n% Consider each basis function in the element.\n%\n for tj1 = 1 : element_order\n\n tj2 = mod ( tj1, 3 ) + 1;\n tj3 = mod ( tj1 + 1, 3 ) + 1;\n\n ntj1 = element_node(tj1,e);\n ntj2 = element_node(tj2,e);\n ntj3 = element_node(tj3,e);\n\n qj = 0.5 * ( ...\n ( node_xy(1,ntj3) - node_xy(1,ntj2) ) * ( yq - node_xy(2,ntj2) ) ...\n - ( node_xy(2,ntj3) - node_xy(2,ntj2) ) * ( xq - node_xy(1,ntj2) ) ) ...\n / area;\n dqjdx = - 0.5 * ( node_xy(2,ntj3) - node_xy(2,ntj2) ) / area;\n dqjdy = 0.5 * ( node_xy(1,ntj3) - node_xy(1,ntj2) ) / area;\n\n a(nti1,ntj1) = a(nti1,ntj1) ...\n + area * wq * ( dqidx * dqjdx + dqidy * dqjdy );\n\n end\n\n end\n\n end\n\n end\n%\n% BOUNDARY CONDITIONS\n%\n% If the K-th variable is at a boundary node, replace the K-th finite\n% element equation by a boundary condition that sets the variable to U(K).\n%\n k = 0;\n\n for j = 1 : ny\n\n for i = 1 : nx\n\n k = k + 1;\n\n if ( i == 1 | i == nx | j == 1 | j == ny )\n\n [ u, dudx, dudy ] = exact ( node_xy(1,k), node_xy(2,k) );\n\n a(k,1:node_num) = 0.0;\n a(k,k) = 1.0;\n b(k) = u;\n\n end\n end\n end\n%\n% SOLVE the linear system A * C = B.\n%\n c = a \\ b;\n%\n% COMPARE computed and exact solutions at the nodes.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' K I J X Y U U\\n' );\n fprintf ( 1, ' exact computed \\n' );\n\n k = 0;\n\n for j = 1 : ny\n fprintf ( 1, '\\n' );\n for i = 1 : nx\n\n k = k + 1;\n\n [ u, dudx, dudy ] = exact ( node_xy(1,k), node_xy(2,k) );\n\n fprintf ( 1, ' %4d %4d %4d %10f %10f %14e %14e %14e\\n', ...\n k, i, j, node_xy(1,k), node_xy(2,k), u, c(k), abs ( u - c(k) ) );\n\n end\n\n end\n%\n% Compute error integrals.\n%\n if ( 1 )\n\n el2 = 0.0;\n eh1 = 0.0;\n\n for e = 1 : element_num\n\n i1 = element_node(1,e);\n i2 = element_node(2,e);\n i3 = element_node(3,e);\n\n area = 0.5 * ...\n ( node_xy(1,i1) * ( node_xy(2,i2) - node_xy(2,i3) ) ...\n + node_xy(1,i2) * ( node_xy(2,i3) - node_xy(2,i1) ) ...\n + node_xy(1,i3) * ( node_xy(2,i1) - node_xy(2,i2) ) );\n%\n% Consider each quadrature point.\n% Here, we use the midside nodes as quadrature points.\n%\n for q1 = 1 : 3\n\n q2 = mod ( q1, 3 ) + 1;\n\n nq1 = element_node(q1,e);\n nq2 = element_node(q2,e);\n\n xq = 0.5 * ( node_xy(1,nq1) + node_xy(1,nq2) );\n yq = 0.5 * ( node_xy(2,nq1) + node_xy(2,nq2) );\n wq = 1.0 / 3.0;\n\n uh = 0.0;\n dudxh = 0.0;\n dudyh = 0.0;\n\n for tj1 = 1 : element_order\n\n tj2 = mod ( tj1, 3 ) + 1;\n tj3 = mod ( tj1 + 1, 3 ) + 1;\n\n ntj1 = element_node(tj1,e);\n ntj2 = element_node(tj2,e);\n ntj3 = element_node(tj3,e);\n\n qj = 0.5 * ( ...\n ( node_xy(1,ntj3) - node_xy(1,ntj2) ) * ( yq - node_xy(2,ntj2) ) ...\n - ( node_xy(2,ntj3) - node_xy(2,ntj2) ) * ( xq - node_xy(1,ntj2) ) ) ...\n / area;\n dqjdx = - 0.5 * ( node_xy(2,ntj3) - node_xy(2,ntj2) ) / area;\n dqjdy = 0.5 * ( node_xy(1,ntj3) - node_xy(1,ntj2) ) / area;\n\n uh = uh + c(ntj1) * qj;\n dudxh = dudxh + c(ntj1) * dqjdx;\n dudyh = dudyh + c(ntj1) * dqjdy;\n\n end\n\n [ u, dudx, dudy ] = exact ( xq, yq );\n\n el2 = el2 + ( uh - u )^2 * area;\n eh1 = eh1 + ( ( dudxh - dudx )^2 + ( dudyh - dudy )^2 ) * area;\n\n end\n\n end\n\n el2 = sqrt ( el2 );\n eh1 = sqrt ( eh1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, '*********************************************\\n' );\n fprintf ( 1, '* *\\n' );\n fprintf ( 1, '* ERRORS: *\\n' );\n fprintf ( 1, '* L2 error = %14f *\\n', el2 );\n fprintf ( 1, '* H1-seminorm error = %14f *\\n', eh1 );\n fprintf ( 1, '* *\\n' );\n fprintf ( 1, '*********************************************\\n' );\n\n end\n%\n% WRITE the data to files.\n%\n node_filename = 'rectangle_nodes.txt';\n\n r8mat_write ( node_filename, 2, node_num, node_xy );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Wrote the node file \"%s\"\\n', node_filename );\n\n element_filename = 'rectangle_elements.txt';\n\n i4mat_write ( element_filename, element_order, element_num, element_node );\n\n fprintf ( 1, ' Wrote the element file \"%s\"\\n', element_filename );\n\n value_filename = 'rectangle_solution.txt';\n\n r8mat_write ( value_filename, 1, node_num, c' );\n\n fprintf ( 1, ' Wrote the solution value file \"%s\"\\n', value_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_RECTANGLE_LINEAR:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ u, dudx, dudy ] = exact ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT calculates the exact solution and its first derivatives.\n%\n% Discussion:\n%\n% The function specified here depends on the problem being\n% solved. The user must be sure to change both EXACT and RHS\n% or the program will have inconsistent data.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 November 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the coordinates of a point\n% in the region, at which the exact solution is to be evaluated.\n%\n% Output, real U, DUDX, DUDY, the value of\n% the exact solution U and its derivatives dUdX\n% and dUdY at the point (X,Y).\n%\n u = sin ( pi * x ) * sin ( pi * y ) + x;\n dudx = pi * cos ( pi * x ) * sin ( pi * y ) + 1.0;\n dudy = pi * sin ( pi * x ) * cos ( pi * y );\n\n return\nend\nfunction i4mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% I4MAT_WRITE writes an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, integer TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'I4MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %12d', round ( table(i,j) ) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction 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 timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_poisson_rectangle_linear/fem2d_poisson_rectangle_linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7652354275009953}} {"text": "function x=eqConstLSSpher(A,b,alpha,epsRed)\n%%EQCONSTLSSPHER Find x to minimize norm(A*x-b,2) under the constraint\n% that norm(x,2)=alpha. This is essentialy contraining x to\n% the surface of a sphere of radius alpha. This only solves\n% real systems.\n%\n%INPUTS: A A real mXn matrix with m>=n.\n% b A real mX1 vector.\n% alpha The equality constraint value. If this parameter is omitted or\n% an empty matrix is passed, the default of 1 is used.\n% epsRed Let xU be the unconstrained solution to the problem. A possible\n% constrained solutions is considered valid if\n% abs(norm(x)^2-alpha^2)<=epsRed*abs(norm(xU)^2-alpha^2)\n% If no such solutions are found, then xU is returned. The default\n% for this parameter if omitted or an empty matrix is passed is\n% 1e-9. This parameter should be between 0 and 1.\n%\n%OUTPUTS: x The optimal value of x subject to the spherical constraint.\n% lambda The Lagrangian multiplier used in the optimization. lambda>=0.\n% If lambda=0, then the constraint on x did not have to be\n% enforced.\n%\n%This implements a modified version of the algorithm of Chapter 6.2.1 of\n%[1]. The algorithm of Chapter 6.2.1 of [1] solves the optimization\n%constrained such that norm(x,2)<=alpha. We wish to solve the equality\n%constrained problem. To do so, we always enforce the constraint. An\n%equation has to be solved for scalar zeros over lambda. To do so, we\n%multiply both sids by the denominators resulting in a polynomial system.\n%The system is then solved. However, some solutions might not satisfy the\n%constraint (due to cancellation in denominators). Thus, candidate\n%solutions that do not improve the error in the magnitude by a sufficient\n%amount compared to the unconstrained solution are discarded. If no\n%solutions are left, the the unconstrained solution is used.\n%\n%EXAMPLE:\n%This is a simple example where the x returned by the\n%inequality-constrained algorithm is too small.\n% A=magic(8)+20*eye(8);\n% b=(1:8).';\n% x=inv(A)*b;\n% norm(x)%Norm <1.\n% xConst=eqConstLSSpher(A,b);\n% norm(xConst)%Norm=1\n% %It is not just normalizing the vector; elements are not scaled by a\n% %constant.\n% x./xConst\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%December 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(alpha))\n alpha=1;\nend\n\nif(nargin<4||isempty(epsRed))\n epsRed=1e-9;\nend\n\nr=rank(A);\n\n[U,Sigma,V]=svd(A,0);\nsigma=diag(Sigma);\n\n%Sums are only up to r, so get rid of the extra elements.\nU=U(:,1:r);\nV=V(:,1:r);\nsigma=sigma(1:r);\n\nbTilde=U'*b;\nxUnconst=V*(bTilde./sigma);\n\nalpha2Unconst=abs(norm(xUnconst)^2-alpha^2);\n\nnumVal=(sigma.*bTilde).^2;\ndenomVal=sigma.^2;\n\nnumDim=length(sigma);\npolynoms=[ones(numDim,1),2*denomVal,denomVal.^2];\n\n%Construct the polynomial to solve.\npolyNom=0;\nfor k1=1:numDim\n curPoly=numVal(k1);\n for k2=1:numDim\n if(k2==k1)\n continue;\n end\n curPoly=conv(curPoly,polynoms(k2,:));\n end\n polyNom=polySum(curPoly,polyNom);\nend\n\n%The final term\ncurPoly=-alpha^2;\nfor k2=1:numDim\n curPoly=conv(curPoly,polynoms(k2,:));\nend\npolyNom=polySum(curPoly,polyNom);\nlambdaVals=roots(polyNom).';\n%Get rid of imaginary solutions.\nlambdaVals=lambdaVals(imag(lambdaVals)==0);\nnumSol=length(lambdaVals);\n\n%Due to certain values corresponding to zero denominators, there can be\n%more solutions in lambda than are valid. We must eliminate all solutions\n%that do not produce x values with the correct magnitude. First, get all\n%possibly valid solutions regardless of the magnitude.\nx=zeros(numDim,numSol);\nnumKept=0;\nfor k=1:numSol\n xCur=V*((sigma.*bTilde)./(sigma.^2+lambdaVals(k)));\n normErr=abs(norm(xCur)^2-alpha^2);\n if(all(isfinite(xCur))&&normErr<=epsRed*alpha2Unconst)\n numKept=numKept+1;\n x(:,numKept)=xCur;\n end\nend\n\nif(numKept==0)\n %If nothing was kept, then just use the unconstrained solution. \n x=xUnconst;\n return \nend\nx=x(:,1:numKept);\n\n%Of all of the solutions kept, take the one that minimizes the original\n%optimization problem.\nif(numKept>1)\n minCost=norm(A*x(:,1)-b,2);\n minIdx=1;\n for k=2:numKept\n curCost=norm(A*x(:,k)-b,2);\n \n if(curCost Teaching > MATLAB\n\nclc; clear; close all;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nm=.1;\ns=.4;\n\nKappa=.6; % 2*Kappa*T_dot>Lambda^2;\nT_dot=1;\nLambda=1;\nT=252*10;\ndt=1/252;\nJ=2;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndB=sqrt(dt)*randn(J,T);\nyt=1;\ny=[];\nd_Xs=[];\nd_taus=[];\nfor t=1:T\n dy=Kappa*(T_dot-yt)*dt+ Lambda*sqrt(yt).*dB(:,t);\n yt=max(yt+dy,10^(-10));\n \n d_tau=yt*dt;\n dX=normrnd(m*d_tau,s*sqrt(d_tau));\n\n y=[y yt];\n d_taus=[d_taus d_tau];\n d_Xs=[d_Xs dX];\n\nend\ntau=cumsum(d_taus,2);\nX=cumsum(d_Xs,2);\n\nfigure\nsubplot(2,1,1)\nh3=plot(dt*[1:T],X(1,:),'k');\ntitle('CIR-subordinated process')\ngrid on\n\nsubplot(2,1,2)\nh1=plot(dt*[1:T],y(1,:));\nhold on \nh2=plot(dt*[1:T],tau(1,:),'r');\ngrid on\nlegend('CIR','stoch. time','location','northwest')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/04VolatilityClustering/Theory/Subordination/S_SubordinationCIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7650921358200753}} {"text": "function [mi] = calculate_mutual_information_array(data)\n% FUNCTION [MI_ARRAY] = CALCULATE_MUTUAL_INFORMATION_ARRAY(DATA)\n% calculates the mutual information between all pairs of variables\n% Data must be discrete, and take values 1,2,...,size\n% data(i,m) is the node i in the case m.\n\n[num_nodes num_examples] = size(data);\n\nnode_sizes = max(data');\nfor i = 1:num_nodes\n for ic = 1:node_sizes(i) % I CLASS ic\n px(i,ic) = sum(data(i,:)==ic);\n for j = 1:num_nodes % J CLASS jc\n for jc = 1:node_sizes(j)\n pxy(i,ic,j,jc) = sum( (data(i,:)==ic) & (data(j,:)==jc) );\n end\n mi(i,j) = 0;\n end\n end\nend\n\nfor i = 1:num_nodes\n for ic = 1:node_sizes(i)\n for j = 1:num_nodes\n for jc = 1:node_sizes(j)\n if( pxy(i,ic,j,jc)~=0 & px(i,ic)~=0 & px(j,jc)~= 0)\n mi(i,j) = mi(i,j) + pxy(i,ic,j,jc)*log2( num_examples*pxy(i,ic,j,jc)/(px(i,ic)*px(j,jc)) )/num_examples; \n end\n end\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/SLP/scoring/calculate_mutual_information_array.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7650825834829902}} {"text": "function [u1, u2] = projectSVD(U1, u)\n% Assumes that `U1` has orthonormal columns\n% so that :math:`U1 U1^T` is a projector.\n% It returns the projections\n%\n% .. math::\n% u1 &= U1 U1^T u \\\\\n% u2 &= (I - U1 U1^T) u\n%\n% USAGE:\n%\n% [u1, u2] = projectSVD(U1, u)\n%\n% EXAMPLE:\n%\n% [U1, D1, V1, r] = subspaceSVD(S);\n% [uC, uL] = projectSVD(U1, u);\n% [vfR, vfN] = projectSVD(V1, vf);\n% [vrR, vrN] = projectSVD(V1, vr);\n%\n% .. Author: - Michael Saunders 29 Jul 2009 First version of projectSVD.m written as alternative to Ronan's projectOntoSubspace.m.\n\n u1 = U1*(U1'*u);\n u2 = u - u1;\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/projectSVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688025, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7650825743448217}} {"text": "function [xSmooth,PSmooth,xUpd,PUpd]=EKalmanBatchSmoother(xInit,PInit,z,h,HJacob,f,FJacob,R,Q,kD,numIter)\n%%EKALMANBATCHSMOOTHER Run the extended forward-backward Kalman smoother\n% for nonlinear dynamic and measurement models on a batch of\n% measurements. The smoothed result at one time step or\n% along the entire batch is available. The initial predicted\n% states cannot be uninformative.\n%\n%INPUTS: xInit The predicted state at the time of the initial measurement\n% in z.\n% PInit The covariance matrix associated with the predicted state at\n% the time of the initial measurement in z.\n% z The zDim X N matrix of measurements for the whole batch.\n% h A NX1 cell array of function handles for the measurement\n% function that transform the state into the measurement\n% domain at each step. If the same measurement function is\n% used for all steps in the batch, then h can just be the\n% single function handle used.\n% HJacob A NX1 cell array of function handles for the measurement\n% Jacobian matrix that each takes the target state as a\n% parameter. If a single measurement Jacobian matrix is used\n% for all steps of the batch, then HJacob can just be the\n% single function handle used. If an empty matrix is passed or\n% the parameter is omitted, then HJacob will be found using\n% numerical differentiation via the numDiff function with\n% default parameters.\n% f A NX1 cell array of function handles for the state\n% transition function that transform the state into the\n% measurement domain at each step. If the same measurement\n% function is used for all steps in the batch, then h can just\n% be the single function handle used.\n% FJacob A NX1 cell array of function handles for the state\n% transition Jacobian matrix that each takes the target state\n% as a parameter. If a single measurement Jacobian matrix is\n% used for all steps of the batch, then HJacob can just be the\n% single function handle used. If an empty matrix is passed or\n% the parameter is omitted, then HJacob will be found using\n% numerical differentiation via the numDiff function with\n% default parameters.\n% R The zDim X zDim X N hypermatrix of measurement covariance\n% matrices. Alternatively, if all of the measurement\n% covariance matrices are the same, one can just pass a single\n% zDim X zDim matrix.\n% Q The xDim X xDim X (N-1) hypermatrix of process noise\n% covariance matrices. Alternatively, if all of the process\n% noise covariance matrices are the same, one can just pass a\n% single xDim X xDim matrix.\n% kD The discrete time-step at which the smoothed state estimate\n% is desired, where z(:,1) is at discrete time-step 1 (not 0).\n% If kD is omitted or an empty matrix is passed, then\n% results along the entire batch are obtained.\n% numIter The number of iterations to perform if an iterated EKF is\n% desired. The default is zero. That is, just use the\n% standard update without any additional iterations.\n%\n%OUTPUTS: xEst The xDimXN smoothed state estimates at all steps if kD is\n% not provided or the xDimX1 smoothed state estimate at step\n% kD if kD is provided.\n% PEst The covariance matrices associated with the smoothed\n% state estimates. This is xDimXxDimXN for the whole batch\n% if kD is not provided and is xDimXxDim if kD is provided.\n% xUpd The xDimXN state estimates of the forward filter (not\n% smoothed) at all times.\n% PUpd The xDimXxDimXN covariance matrices of the forward filter\n% (not smoothed) at all times.\n%\n%This function implements an extended Kalman smoother modified from Chapter\n%8.6 of [1].\n%\n%The smoothing iteration algorithm is taken from Section III of [2]. This\n%provides an algorithm to iterate the smoothed state, but not the smoothed\n%covariance matrix.\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] L. A. Johnston and V. Krishnamurthy, \"Derivation of a sawtooth\n% iterated extended Kalman smoother via the AECM algorithm,\" IEEE\n% Transactions on Signal Processing, vol. 49, no. 9, pp. 1899-1909,\n% 2001.\n%\n%March 2015 David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif nargin<10\n kD=[];\nend\nif nargin<11\n numIter=0;\nend\n\nxDim=size(xInit,1);\nzDim=size(z,1);\nN=size(z,2);\n\nif(isempty(FJacob))\n FJacob=@(x)numDiff(x,f,xDim);\nend\nif(isempty(HJacob))\n HJacob=@(x)numDiff(x,h,zDim);\nend\n\nif(isa(HJacob,'function_handle'))\n HJacob=repmat({HJacob},N,1);\nend\nif(isa(h,'function_handle'))\n h=repmat({h},N,1);\nend\nif(isa(FJacob,'function_handle'))\n FJacob=repmat({FJacob},N,1);\nend\nif(isa(f,'function_handle'))\n f=repmat({f},N,1);\nend\nif(size(R,3)==1)\n R=repmat(R,1,1,N);\nend\nif(size(Q,3)==1)\n Q=repmat(Q,1,1,N-1);\nend\n\n%Run the Kalman filter forward\nxPred=zeros(xDim,N);\nPPred=zeros(xDim,xDim,N);\nxUpd=zeros(xDim,N);\nPUpd=zeros(xDim,xDim,N);\n\n%The first step uses the priors\nxPred(:,1)=xInit;\nPPred(:,:,1)=PInit;\n\n%The rest of the steps\nfor curStep=1:(N-1)\n [xUpd(:,curStep),PUpd(:,:,curStep)]=EKFUpdate(xPred(:,curStep),PPred(:,:,curStep),z(:,curStep),R(:,:,curStep),h{curStep},HJacob{curStep},numIter);\n [xPred(:,curStep+1),PPred(:,:,curStep+1)]=DiscEKFPred(xUpd(:,curStep),PUpd(:,:,curStep),f{curStep},FJacob{curStep},Q(:,:,curStep));\nend\n[xUpd(:,end),PUpd(:,:,end)]=EKFUpdate(xPred(:,N),PPred(:,:,N),z(:,N),R(:,:,N),h{N},HJacob{N},numIter);\n\n%Run the backwards Kalman smoother\nxSmooth=zeros(xDim,N);\nPSmooth=zeros(xDim,xDim,N);\n\nxSmooth(:,N)=xUpd(:,N);\nPSmooth(:,:,N)=PUpd(:,:,N);\nfor curStep=(N-1):-1:1\n F=FJacob{curStep}(xUpd(:,curStep));\n C=PUpd(:,:,curStep)*F'/PPred(:,:,curStep+1);\n xSmooth(:,curStep)=xUpd(:,curStep)+C*(xSmooth(:,curStep+1)-xPred(:,curStep+1));\n PSmooth(:,:,curStep)=PUpd(:,:,curStep)+C*(PSmooth(:,:,curStep+1)-PPred(:,:,curStep+1))*C';\n \n for curIter=1:numIter\n F=FJacob{curStep}(xSmooth(:,curStep));\n H=HJacob{curStep}(xSmooth(:,curStep));\n B=pinv(pinv(PUpd(:,:,curStep))+H'*inv(R(:,:,curStep))*H+F'*inv(Q(:,:,curStep))*F);\n xSmooth(:,curStep)=xUpd(:,curStep)+B*(...\n H'*inv(R(:,:,curStep))*(z(:,curStep)-h{curStep}(xPred(:,curStep))-H*(xPred(:,curStep)-xSmooth(:,curStep)))...\n +F'*inv(Q(:,:,curStep))*(xSmooth(:,curStep+1)-xPred(:,curStep+1)));\n end\nend\n\nif(~isempty(kD))\n xSmooth=xSmooth(:,kD);\n PSmooth=PSmooth(:,:,kD);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Batch_and_Smoothing/EKalmanBatchSmoother.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582574225518, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7650126595763108}} {"text": "function [CVA] = spm_cva_prob (X1,X2,m)\n% Probabilistic Canonical Variates Analysis\n% FORMAT [CVA] = spm_cva_prob (X1,X2,m)\n%\n% X1 [d1 x N] matrix of dependent variables\n% X2 [d2 x N] matrix of independent variables\n% m dimension of latent variable (min([d1,d2]) by default)\n%\n% Returns fields:\n% \n% .U1,.U2 Canonical vectors\n% .W1,.W2 Factor matrices\n% .L Log-Likelihood\n% .bic Bayesian Information Criterion\n% .aic Akaike's Information Criterion\n%\n% Fits probabilistic model\n%\n% x1 = W1 z + e1\n% x2 = W2 z + e2\n%\n% This algorithm is described in:\n%\n% F. Bach and M. Jordan (2005) A probabilistic interpretation of canonical\n% correlation analysis. Dept. Stats, Univ California, Berkeley CA. \n% Tech Rep 688.\n%\n%___________________________________________________________________________\n% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_cva_prob.m 4687 2012-03-14 18:15:49Z will $\n\n\n[d1,N1]=size(X1);\n[d2,N2]=size(X2);\nd=d1+d2;\n\nif ~N1==N2\n disp('Error in spm_cva_prob: unequal number of samples');\n return\nelse\n N=N1;\nend\n\nif nargin < 3 | isempty(m)\n m=min([d1,d2]);\nelse\n if m > min([d1,d2]);\n disp('m too large');\n return\n end\nend\n\nX=[X1;X2];\nSigma=cov(X')+(10^-8*eye(d1+d2));\nSigma11=Sigma(1:d1,1:d1);\n\nif m==0\n S=diag(diag(Sigma));\n iS=inv(S);\n CVA.L=-0.5*N*(d1+d2)*log(2*pi)-0.5*N*spm_logdet(S)-0.5*N*trace(iS*Sigma);\n CVA.bic=CVA.L;\n CVA.aic=CVA.L;\n CVA.W1=[];CVA.W2=[];CVA.U1=[];CVA.U2=[];\n return\nend\n\nSigma12=Sigma(1:d1,d1+1:d1+d2);\nSigma22=Sigma(d1+1:d,d1+1:d);\nSigma21=Sigma12';\n\nR1=inv(sqrtm(Sigma11));\nR2=inv(sqrtm(Sigma22));\nA=R1*Sigma12*R2;\n\n[V1,P,V2]=svd(A,0);\nsP=diag(P);\nrP=sP/max(sP);\nU1=R1*V1(:,1:m);\nU2=R2*max(sP)*V2(:,1:m);\n\nM1=diag(sqrt(rP(1:m)));\nM2=M1;\n\nW1=Sigma11*U1*M1;\nW2=Sigma22*U2*M2;\nPsi1=diag(diag(Sigma11-W1*W1'));\nPsi2=diag(diag(Sigma22-W2*W2'));\n\nW=[W1;W2];\nS=W*W'+blkdiag(Psi1,Psi2);\n\nCVA.W1=W1;\nCVA.W2=W2;\nCVA.U1=U1;\nCVA.U2=U2;\n \niS=inv(S);\nCVA.L=-0.5*N*(d1+d2)*log(2*pi)-0.5*N*spm_logdet(S)-0.5*N*trace(iS*Sigma);\nk=2*m*(d1+d2); % W1, W2 plus diag Psi's \n\nCVA.bic=CVA.L-0.5*k*log(N);\nCVA.aic=CVA.L-k;\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/mlm/spm_cva_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7650126564053248}} {"text": "function [ c_est, c1_err, c2_err ] = triangle_random_centralize ( n, v )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_RANDOM_CENTRALIZE estimates the centroid of a triangle.\n%\n% Discussion:\n%\n% We generate N points on the surface of a triangle in 2 dimensions.\n% We seek to estimate the centroid of the triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of random points to generate.\n%\n% Input, real V(2,3), the vertices of the triangle.\n%\n% Output, real C_EST(M,1), the estimated centroid.\n%\n% Output, real C1_ERR, the norm of the difference of C_EST and the \n% area centroid.\n%\n% Output, real C2_ERR, the norm of the difference of C_EST and the \n% boundary centroid.\n%\n x = triangle_surface_sample ( n, v );\n\n c = sum ( v, 2 ) / 3.0;\n c_est = sum ( x, 2 ) / n;\n c1_err = norm ( c - c_est );\n\n l1 = norm ( v(1:2,2) - v(1:2,1) );\n l2 = norm ( v(1:2,3) - v(1:2,2) );\n l3 = norm ( v(1:2,1) - v(1:2,3) );\n l_sum = l1 + l2 + l3;\n l1 = 0.5 * l1 / l_sum;\n l2 = 0.5 * l2 / l_sum;\n l3 = 0.5 * l3 / l_sum;\n\n c2(1:2,1) = ( l3 + l1 ) * v(1:2,1) ...\n + ( l1 + l2 ) * v(1:2,2) ...\n + ( l2 + l3 ) * v(1:2,3);\n\n c2_err = norm ( c2 - c_est );\n\n return\nend\n", "meta": {"author": "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/triangle_random_centralize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7649670803204143}} {"text": " function ab = BrokenStickRegression(xx, yy, nstick)\n%BROKENSTICKREGRESSION piecewise linear regression. Fits a line\n% consisting of connected straight sections to a cloud of data points.\n%\n% AB = BrokenStickRegression(XX, YY, NSTICK); XX and YY are the data \n% points; NSTICK is the number of connected straight sections. AB(:, 1)\n% are the x-coordinates of endpoints and breakpoints in ascending order. \n% AB(:, 2) are the corresponding y-coordinates. XX need not be in a\n% monotonic order.\n%\n% AB = BrokenStickRegression(XX, YY, BREAKPOINTS); BREAKPOINTS is either\n% a vector of at least two abscissa values chosen as starting \n% breakpoints or one non-integer starting breakpoint on the abscissa.\n% NUMEL(BREAKPOINTS) + 1 is the number of straight sections of the \n% fitting curve. Choosing starting breakpoints helps in some cases to \n% obtain better fits.\n%\n% Example 1:\n% ---------\n% nstick = 4;\n% nn = 800;\n% xx = linspace(1.0, 11.5, nn)';\n% y0 = sin(xx);\n% yy = y0 + randn(nn, 1) * 0.4;\n% ab = BrokenStickRegression(xx, yy, nstick);\n% plot(xx, yy, 'b.', xx, y0, 'k', ab(:, 1), ab(:, 2), 'r-o')\n% title(['BrokenStickRegression(x, sin(x) + noise, ', ...\n% int2str(nstick), ')'])\n%\n% Example 2:\n% ---------\n% xx = 0:100;\n% yy = [ones(1, 70), 1:10, 11:-1:0];\n% yy = [yy, zeros(1, 101 - length(yy))] + 0.8 * randn(1, 101);\n% bp = [65, 75, 90]; % breakpoints.\n% plot(xx, yy, '.')\n% hold on\n% ab1 = BrokenStickRegression(xx, yy, numel(bp) + 1);\n% plot(ab1(:, 1), ab1(:, 2), 'k-o')\n% ab2 = BrokenStickRegression(xx, yy, bp);\n% plot(ab2(:, 1), ab2(:, 2), 'r-o')\n% legend('data points', 'NSTICK scalar', 'NSTICK vectorial', ...\n% 'Location', 'NW')\n%\n% See also: POLYFIT.\n\n% The algorithm uses POLYFIT and FMINSEARCH.\n%\n% pmwnave@yahoo.de\n% 2010-11-05, started. Submitted to FEX on 2010-11-13, #29387.\n% 2010-11-16, simplified. Update submitted to FEX on 2010-11-15.\n% 2010-12-01, case recognized in which polyfit is supplied with only one\n% data point; case recognized in which the first breakpoint \n% slips to the left of the minimum data point. Both bugs\n% were discovered by Carlos Romero, EPFL, Lausanne. Thanks!\n% Update submitted to FEX on 2010-12-05.\n% 2010-12-07, penalty scheme simplified.\n% 2011-09-04, one breakpoint can now be specified, as suggested by Atul\n% Ingle on 2011-09-01.\n%----------------------------------------------------------------------O\n% Initialize the coordinates ab of the end- and breakpoints. \n%\n xx = xx(:);\n yy = yy(:); \n a0 = [];\n\n if numel(xx) ~= numel(yy),\n error(' ### %s: XX and YY are not equally long.', mfilename)\n end\n if ~all(isfinite(xx)) || ~all(isfinite(yy)),\n error(' ### %s: XX or YY contain non-finite elements.', mfilename)\n end\n if (nargin == 2) || isempty(nstick),\n nstick = 1;\n end\n if numel(nstick) > 1 || round(nstick) ~= nstick,\n a0 = nstick;\n nstick = numel(a0) + 1;\n end\n if numel(xx) < nstick + 1,\n error(' ### %s: too few data points.', mfilename)\n end\n \n ab = zeros(nstick + 1, 2);\n ab(1, 1) = min(xx);\n ab(end, 1) = max(xx);\n \n if nstick == 1,\n%\n% Normal linear regression.\n%\n pp = polyfit(xx, yy, 1); \n ab(:, 2) = pp(1) * ab(:, 1) + pp(2);\n \n else \n%\n% Two or more sticks. Find the breakpoints that minimize the residuals. \n% The appropriate function would be FMINCON which is part of the \n% optimization toolbox, which not everybody owns. A work-around consists\n% in applying penalties whenever constraints are violated. The penalties\n% are defined in MinRes. A and B define constraints: A solution point X\n% is admissible if A * X < B. a0 is(are) the start point(s) of the \n% search process.\n%\n A = zeros(nstick, nstick - 1);\n A(1:nstick + 1:end) = -1; \n A(2:nstick + 1:end) = 1;\n B = zeros(nstick, 1);\n B(1) = -ab(1, 1);\n B(nstick) = ab(end, 1);\n if isempty(a0),\n a0 = (ab(end, 1) - ab(1, 1)) / nstick * (1:nstick - 1)' + ...\n ab(1, 1);\n end\n aa = fminsearch(@MinRes, a0);\n end\n\nfunction rr = MinRes(aa) % nested function.\n%MinRes calculates the residuals rr for given breakpoints aa.\n\n%----------------------------------------------------------------------O\n ab(2:nstick, 1) = aa;\n%\n% Impose a penalty for violating constraining conditions. This approach\n% can possibly be improved. Other constraints may be added as penalties.\n%\n if nstick > 2 && any(A * ab(2:nstick, 1) >= B),\n rr = 1e20; \n return\n end\n%\n% Regression on the leftmost section.\n%\n kk = find(xx <= ab(2, 1));\n kt = numel(kk);\n if kt == 1,\n tmp = 0;\n else\n [pp, ss, mu] = polyfit(xx(kk), yy(kk), 1);\n ab(1:2, 2) = polyval(pp, ab(1:2, 1), [], mu);\n tmp = yy(kk) - polyval(pp, xx(kk), [], mu);\n end\n%\n% All other sections.\n%\n for ii = 2:nstick,\n kk = find((xx > ab(ii, 1)) & (xx <= ab(ii + 1, 1)));\n lh = xx(kk) - ab(ii, 1);\n rh = (yy(kk) - ab(ii, 2)) * (ab(ii + 1, 1) - ab(ii, 1)) + ...\n ab(ii, 2) * (xx(kk) - ab(ii, 1));\n ab(ii + 1, 2) = lh' * rh / (lh' * lh);\n slope = (ab(ii + 1, 2) - ab(ii, 2)) / (ab(ii + 1, 1) - ab(ii, 1));\n tmp = [tmp; yy(kk) - slope * (xx(kk) - ab(ii, 1)) - ab(ii, 2)]; \n end\n rr = tmp' * tmp;\n\nend % MinRes.\nend % BrokenStickRegression.\n% EOF BrokenStickRegression.\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29387-brokenstickregression/BrokenStickRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7649670703854572}} {"text": "function mbasis = basis_matrix_b_uni ( )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_B_UNI sets up the uniform B spline basis matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Foley, van Dam, Feiner, Hughes,\n% Computer Graphics: Principles and Practice,\n% page 493.\n%\n% Parameters:\n%\n% Output, real MBASIS(4,4), the basis matrix.\n%\n mbasis = [ \n -1.0 / 6.0, 3.0 / 6.0, -3.0 / 6.0, 1.0 / 6.0; ...\n 3.0 / 6.0, - 6.0 / 6.0, 3.0 / 6.0, 0.0; ...\n - 3.0 / 6.0, 0.0, 3.0 / 6.0, 0.0; ...\n 1.0 / 6.0, 4.0 / 6.0, 1.0 / 6.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/spline/basis_matrix_b_uni.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8577681104440171, "lm_q1q2_score": 0.764967070385457}} {"text": "function sixdof = hom2six(M)\n% function sixdof = hom2six(M)\n% \n% Convert homogenous transformation (4x4 matrix) to 6-dof representation\n% as used in SPM8. That is, this function assumes that\n% M = Trans([x;y;z]) * RotX(a) * RotY(b) * RotZ(c)\n% and returns the 6 parameters [x,y,z,a,b,c] that generate M.\n%\n% Note that this representation is not unique in case b = +/- pi/2.\n\n% (C) 2010 S. Klanke\n\n%Rotation part is Rx(a)*Ry(b)*Rz(c)\n%[ cb*cc, cb*sc, sb]\n%[ -sa*sb*cc-ca*sc, -sa*sb*sc+ca*cc, sa*cb]\n%[ -ca*sb*cc+sa*sc, -ca*sb*sc-sa*cc, ca*cb]\n\nif M(1,3) == 1 % sb = 1, cb = 0\n%[ 0, 0, 1]\n%[ -sa*cc-ca*sc, -sa*sc+ca*cc, 0]\n%[ -ca*cc+sa*sc, -ca*sc-sa*cc, 0]\n% not unique -> set a = 0 - > ca=1, sa=0\n%[ 0 0 1]\n%[-sc cc 0]\n%[-cc -sc 0]\n\ta = 0;\n\tb = pi/2;\n\tc = atan2(-M(3,2),M(2,2));\nelseif M(1,3) == -1 % sb = -1, cb = 0\n%[ 0, 0, -1]\n%[ +sa*cc-ca*sc, +sa*sc+ca*cc, 0]\n%[ +ca*cc+sa*sc, +ca*sc-sa*cc, 0]\n% not unique -> set a = 0 - > ca=1, sa=0\n%[ 0 0 -1]\n%[-sc cc 0]\n%[ cc sc 0]\n a = 0;\n\tb = -pi/2;\n\tc = atan2(M(3,2),M(2,2));\nelse\n % cos(b)~=0\n c = atan2(M(1,2),M(1,1));\n b = atan2(M(1,3),norm(M(1,1:2)));\n a = atan2(M(2,3),M(3,3));\nend\n\nsixdof = [M(1:3,4)' a b c];\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/hom2six.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7649137365578087}} {"text": "% Mathematics Q2595199\n% https://math.stackexchange.com/questions/2595199\n% Proximal Mapping of Least Squares with L1 and L2 Mixed Norm Regularization (Elastic Net)\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 13/03/2018\n% * First release.\n\n\n%% General Parameters\n\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = ON;\n\n\n%% Simulation Parameters\n\nparamLam1 = 1;\nparamLam2 = 2;\n\nnumElements = 8;\n\nnumIterations = 1000;\nstepSize = 0.0075;\n\n\n%% Generate Data\n\nvB = 10 * randn([numElements, 1]);\n\nhObjFun = @(vX) (0.5 * sum((vX - vB) .^ 2)) + (paramLam1 * norm(vX, 1)) + (paramLam2 * norm(vX, 2));\nhL2SubGrad = @(vX) vX ./ max(norm(vX, 2), 1e-9);\n\nhSoftThresholdL1 = @(vX, paramLambda) sign(vX) .* max(abs(vX) - paramLambda, 0);\nhSoftThresholdL2 = @(vX, paramLambda) vX .* (1 - (paramLambda / (max(norm(vX, 2), paramLambda))));\n\n\n%% Solution by CVX\n\ncvx_begin('quiet')\n cvx_precision('best');\n variable vX(numElements)\n minimize( (0.5 * square_pos(norm(vX - vB, 2))) + (paramLam1 * norm(vX, 1)) + (paramLam2 * norm(vX, 2)) );\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%% Analytic Solution\n\nvX = hSoftThresholdL2(hSoftThresholdL1(vB, paramLam1), paramLam2);\nanalyticObjVal = hObjFun(vX);\n\ndisp([' ']);\ndisp(['Analytic Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(analyticObjVal)]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX.'), ' ]']);\ndisp([' ']);\n\n\n%% Solution by Sub Gradient Method\n\nvObjValSgm = zeros([numIterations, 1]);\n\nvX = zeros([numElements, 1]);\nvObjValSgm(1) = hObjFun(vX);\n\nfor ii = 2:numIterations\n vG = (vX - vB) + (paramLam1 * sign(vX)) + (paramLam2 * hL2SubGrad(vX));\n vX = vX - (stepSize * vG);\n \n vObjValSgm(ii) = hObjFun(vX); \nend\n\ndisp([' ']);\ndisp(['Sub Gradient Method Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(vObjValSgm(numIterations))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX.'), ' ]']);\ndisp([' ']);\n\n\n%% Solution by https://doi.org/10.1007/s10957-012-0245-9 (A Primal Dual Splitting Method for Convex Optimization Involving Lipschitzian, Proximable and Linear Composite Terms)\n% Implementing Algorithm 3.2\n% The Matrix L is identity\n% The Gradient of F is vX - vB\n\nvObjValSplit = zeros([numIterations, 1]);\n\nparamSigma = 0.05;\nparamTau = 0.05;\nparamPhi = 0.5;\n\nhSoftThresholdL1 = @(vX, paramLambda) sign(vX) .* max(abs(vX) - paramLambda, 0);\nhSoftThresholdL2 = @(vX, paramLambda) vX .* (1 - (paramLambda / (max(norm(vX, 2), paramLambda))));\n\nhProxG = @(vX, paramTau) hSoftThresholdL1(vX, paramTau * paramLam1); %1;\n% B(sel)=0;\n% B=reshape(B,numPoints,numPoints);\n% \n% figure(1)\n% clf\n% surf(u,v,20*log10(abs(B)),'EdgeColor','None')\n% axis([-1 1 -1 1 -50 0])\n% caxis([-50 0])\n% colormap(jet(256))\n% view(20,45)\n% light()\n% h1=xlabel('u');\n% h2=ylabel('v');\n% h3=zlabel('Array Response');\n% title('Array Power Response 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%REFERENCES:\n%[1] H. L. Van Trees, Optimum Array Processing. New York:\n% Wiley-Interscience, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. \n\nM=numRows;\nN=numCols;\n\nrowVals=(1/M)*sin(pi*(M/2)*uv(1,:))./sin((pi/2)*uv(1,:));\nrowVals(~isfinite(rowVals))=1;%Remove singularity\n\ncolVals=(1/N)*sin(pi*(N/2)*uv(2,:))./sin((pi/2)*uv(2,:));\ncolVals(~isfinite(colVals))=1;%Remove singularity\n\nB=rowVals.*colVals;\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/Explicit_Beampatterns/stdUnifRectBeamPattern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7647940141164256}} {"text": "function [ mD ] = CalcDistanceMatrixCCols( mX )\n% ----------------------------------------------------------------------------------------------- %\n% [ mD ] = CalcDistanceMatrixCCols( mX )\n% Calculates the distance matrix for the input data. The distance matrix\n% is a symmetric matrix where 'mD(ii, jj) = dist(mX(:, ii), mX(:, jj));'.\n% This function uses the squared Euclidean Distance for the distance\n% metric.\n% Input:\n% - mX - Data Matrix.\n% Each data sample is a column of the matrix.\n% Structure: Matrix (varDim x numVars).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - mD - Distance Matrix.\n% A symmetric matrix where 'mD(ii, jj) = dist(mX(:,\n% ii), mX(:, jj));'.\n% Structure: Matrix (numVars x numVars).\n% Type: 'Single' / 'Double'.\n% Range: [0, inf).\n% References\n% 1. A\n% Remarks:\n% 1. B\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 01/01/2021 Royi Avital\tRoyiAvital@yahoo.com\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nmG = mX.' * mX;\nvG = diag(mG);\n\nmD = vG.' + vG - (2 * mG);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/CodeReview/Q254186/CalcDistanceMatrixCCols.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7647891761943657}} {"text": "function pass = test_battery( prefs ) \n% Check that chebop2 is working by using a battery of Laplace problems. \n% Alex Townsend, March 2013. \n\nif ( nargin < 1 ) \n prefs = chebfunpref(); \nend \ntol = 100*prefs.techPrefs.chebfuneps; \n\n% Harmonic solution to the Laplace equation\nN = chebop2(@(u) diff(u,2,1) + diff(u,2,2)); \nbdy = @(x,y) real(exp(x+1i*y)); \nN.lbc = @(y) bdy(-1,y); N.rbc = @(y) bdy(1,y); \nN.dbc = @(x) bdy(x,-1); N.ubc = @(x) bdy(x,1); \nu = N \\ 0; exact = chebfun2(bdy);\npass(1) = ( norm( exact - u ) < tol ); \n\n% Harmonic solution to the Laplace equation\nN = chebop2(@(u) diff(u,2,1) + diff(u,2,2)); \nbdy = @(x,y) real(exp(2*(x+1i*y))); \nN.lbc = @(y) bdy(-1,y); N.rbc = @(y) bdy(1,y); \nN.dbc = @(x) bdy(x,-1); N.ubc = @(x) bdy(x,1); \nu = N \\ 0; exact = chebfun2(bdy);\npass(2) = ( norm( exact - u ) < tol ); \n\n\n% Harmonic solution to the Laplace equation\nN = chebop2(@(u) diff(u,2,1) + diff(u,2,2)); \nbdy = @(x,y) 10*real(exp(2*(x+1i*y))); \nN.lbc = @(y) bdy(-1,y); N.rbc = @(y) bdy(1,y); \nN.dbc = @(x) bdy(x,-1); N.ubc = @(x) bdy(x,1); \nu = N \\ 0; exact = chebfun2(bdy);\npass(3) = ( norm( exact - u ) < 10*tol ); \n\n\n% Harmonic solution to the Laplace equation\nN = chebop2(@(u) diff(u,2,1) + diff(u,2,2)); \nbdy = @(x,y) real((x+1i*y).^2); \nN.lbc = @(y) bdy(-1,y); N.rbc = @(y) bdy(1,y); \nN.dbc = @(x) bdy(x,-1); N.ubc = @(x) bdy(x,1); \nu = N \\ 0; exact = chebfun2(bdy);\npass(4) = ( norm( exact - u ) < tol ); \n\n\n% Linearity check; \nM = N; \n\nN.lbc = @(x) (1+x).*(1-x); \nN.rbc = 0; N.ubc = 0; N.dbc = 0; \nu1 = N \\ 0; \n\nN = M; N.rbc = @(x) (1+x).*(1-x); \nN.lbc = 0; N.ubc = 0; N.dbc = 0; \nu2 = N \\ 0; \n\nN = M; N.ubc = @(x) (1+x).*(1-x); \nN.rbc = 0; N.lbc = 0; N.dbc = 0; \nu3 = N \\ 0; \n\nN = M; N.dbc = @(x) (1+x).*(1-x); \nN.rbc = 0; N.ubc = 0; N.lbc = 0; \nu4 = N \\ 0; \n\nN = M; \nN.lbc = @(x) (1+x).*(1-x);\nN.rbc = @(x) (1+x).*(1-x); \nN.dbc = @(x) (1+x).*(1-x); \nN.ubc = @(x) (1+x).*(1-x);\nu = N \\ 0; \n\n[xx, yy] = chebfun2.chebpts2(100); \nA = feval(u,xx,yy); \nB = feval(u1,xx,yy) + feval(u2,xx,yy) + feval(u3,xx,yy) + feval(u4,xx,yy); \npass(5) = ( norm( A - B ) < 1e10*tol);\n\n% Check we can use the notation lap(u) = div(grad(u))\nN = chebop2(@(u) -divergence(gradient(u)) );\nN.lbc = 0; N.rbc = 0; N.dbc = 0; N.ubc = 0; \nu = N \\ 1;\nN = chebop2(@(u) -laplacian(u) );\nN.lbc = 0; N.rbc = 0; N.dbc = 0; N.ubc = 0; \nexact = N \\ 1;\npass(6) = ( norm( u - exact ) < tol);\n\n% check lap(u) exists: \nN = chebop2(@(u) -lap(u) );\nN.lbc = 0; N.rbc = 0; N.dbc = 0; N.ubc = 0; \nexact = N \\ 1;\npass(7) = ( norm( u - exact ) < 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/chebop2/test_battery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7647372451769526}} {"text": "function latLonPts=polarAzEquidistProj2Ellipse(pAzPts,latLonRef,a,f)\n%%POLARAZEQUIDISTANTPROJ2ELLIPSE Given points as polar coordinates of an\n% azimuthal equidistant projection, convert the points to latitudes\n% and longitudes on a reference ellipsoid (or sphere). A third height\n% coordinate can also be provided, which doesn't change in the\n% conversion.\n%\n%INPUTS: pAzPts A 2XN set of the [ground distance; heading] points, with the\n% heading given in radians East of North, to convert.\n% Alternatively, if heights are also given, this can be a 3XN\n% set of points with the height being the third dimension.\n% latLonRef A 2X1 [latitude;longitude] reference point in radians about\n% which the projection is taken.\n% a The semi-major axis of the reference ellipsoid (in meters).\n% If this argument is omitted or an empty matrix is passed,\n% the value in Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the reference ellipsoid. If this\n% argument is omitted or an empty matrix is passed, the value\n% in Constants.WGS84Flattening is used.\n%\n%OUTPUTS: latLonPts The 2XN set of converted [latitude;longitude] points in\n% radians. If heights were given in xyPts, then this is a\n% 3XN set of converted [latitude;longitude;height] points\n% with the third row the same as in xyPts.\n%\n%The conversion is described in Chapter 25 of [1], where expressions for\n%a spherical Earth are given. However, we do not use those formulae. The\n%latitude and longitude of the point can be obtained using the\n%directGreatCircleProb function for a spherical Earth or the\n%directGeodeticProb for an ellipsoidal Earth, which is just what is done\n%here.\n%\n%December 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<3||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nhasHeight=(size(pAzPts,1)==3);\nnumPts=size(pAzPts,2);\nif(hasHeight)\n latLonPts=zeros(3,numPts);\nelse\n latLonPts=zeros(2,numPts);\nend\nif(f==0)\n %Under a spherical Earth approximation.\n for k=1:numPts\n distVal=pAzPts(1,k);\n az=pAzPts(2,k);\n \n latLonPts(1:2,k)=directGreatCircleProb(latLonRef,az,distVal,a);\n end\nelse\n %Under an ellipsoidal Earth approximation.\n for k=1:numPts\n distVal=pAzPts(1,k);\n az=pAzPts(2,k);\n \n latLonPts(1:2,k)=directGeodeticProb(latLonRef,az,distVal,a,f);\n end\nend\n\nif(hasHeight)\n latLonPts(3,:)=pAzPts(3,:);\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/polarAzEquidistProj2Ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991952, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7647372433943789}} {"text": "%*****************THE MAIN PROGRAMME*****************\n%====================================================\n%Practise problem for the course of CAO\n%Prof P.Beckers \n%====================================================\n%Porpose :Drawing the orthotomic surface of a Bezier surface %\n% Student: BUI QUOC TINH\n% European Master Mechanices of Contructions\t(EMMC)\t\t\t\t\t \t\t\t\t \n% University the Liege. Belgium\t\t\t\t\t\t\t\t\t\t \t\t %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%====================================================\nclear all;\n\n%Definition of the control points directly\t\t\t \nP00=[-10 0 10];P01=[-10 5 5];P02=[-10 5 -5];P03=[-10 0 -10];\nP10=[-5 5 10];P11=[-5 5 5];P12=[-5 5 -5];P13=[-5 5 -10];\nP20=[5 5 10];P21=[5 5 5];P22=[5 5 -5];P23=[5 5 -10];\nP30=[10 0 10];P31=[10 5 5];P32=[10 5 -5];P33=[10 5 -10];\n\n%Matrix control points of Bezier surface \nPP=[P00 P01 P02 P03;...\n P10 P11 P12 P13;...\n P20 P21 P22 P23;...\n P30 P31 P32 P33];\n \n %S source point\n%disp('INPUT S SOURCE POINT ')\n%xs=input('input xs = ');\n%ys=input('input ys = ');\n%zs=input('input zs = ');\nxs=-5;\nys=3;\nzs=5;\nS=[xs;ys;zs];\n \n%Calculation of the points in the surface \nk=20;\nfor i=1:k\n\tif i>9 & mod(i,10)==0\n\t\tdisp(i) % Using show is the progress of the calculations.\n\tend\nfor j=1:k\nu=0.01*i;\nv=0.01*j;\n\n%=============================================\n%the function of bezier surafce polynomial\nq=P00*B(0,3,u)*B(0,3,v)+P01*B(0,3,u)*B(1,3,v)+P02*B(0,3,u)*B(2,3,v)+P03*B(0,3,u)*B(3,3,v)+...\n+P10*B(1,3,u)*B(0,3,v)+P11*B(1,3,u)*B(1,3,v)+P12*B(1,3,u)*B(2,3,v)+P13*B(1,3,u)*B(3,3,v)+...\n+P20*B(2,3,u)*B(0,3,v)+P21*B(2,3,u)*B(1,3,v)+P22*B(2,3,u)*B(2,3,v)+P23*B(2,3,u)*B(3,3,v)+...\n+P30*B(3,3,u)*B(0,3,v)+P31*B(3,3,u)*B(1,3,v)+P32*B(3,3,u)*B(2,3,v)+P33*B(3,3,u)*B(3,3,v);\n\n%the first derivatives u parametic of bezier surface function\nq_u=P00*B_daoham(0,3,u)*B(0,3,v)+P01*B_daoham(0,3,u)*B(1,3,v)+P02*B_daoham(0,3,u)*B(2,3,v)+P03*B_daoham(0,3,u)*B(3,3,v)+...\n+P10*B_daoham(1,3,u)*B(0,3,v)+P11*B_daoham(1,3,u)*B(1,3,v)+P12*B_daoham(1,3,u)*B(2,3,v)+P13*B_daoham(1,3,u)*B(3,3,v)+...\n+P20*B_daoham(2,3,u)*B(0,3,v)+P21*B_daoham(2,3,u)*B(1,3,v)+P22*B_daoham(2,3,u)*B(2,3,v)+P23*B_daoham(2,3,u)*B(3,3,v)+...\n+P30*B_daoham(3,3,u)*B(0,3,v)+P31*B_daoham(3,3,u)*B(1,3,v)+P32*B_daoham(3,3,u)*B(2,3,v)+P33*B_daoham(3,3,u)*B(3,3,v);\n\n%%the first derivatives v parametic of bezier surface function\nq_v=P00*B(0,3,u)*B_daoham(0,3,v)+P01*B(0,3,u)*B_daoham(1,3,v)+P02*B(0,3,u)*B_daoham(2,3,v)+P03*B(0,3,u)*B_daoham(3,3,v)+...\n+P10*B(1,3,u)*B_daoham(0,3,v)+P11*B(1,3,u)*B_daoham(1,3,v)+P12*B(1,3,u)*B_daoham(2,3,v)+P13*B(1,3,u)*B_daoham(3,3,v)+...\n+P20*B(2,3,u)*B_daoham(0,3,v)+P21*B(2,3,u)*B_daoham(1,3,v)+P22*B(2,3,u)*B_daoham(2,3,v)+P23*B(2,3,u)*B_daoham(3,3,v)+...\n+P30*B(3,3,u)*B_daoham(0,3,v)+P31*B(3,3,u)*B_daoham(1,3,v)+P32*B(3,3,u)*B_daoham(2,3,v)+P33*B(3,3,u)*B_daoham(3,3,v);\n\n%===============\nqx(i,j)=q(1);%Saving points matrix into the remember computer \nqy(i,j)=q(2);\nqz(i,j)=q(3);\n\n%===============\nqx_u=q_u(1);\nqy_u=q_u(2);\nqz_u=q_u(3);\n\n%===============\nqx_v=q_v(1);\nqy_v=q_v(2);\nqz_v=q_v(3);\n\n%===============\n\n%The geomatric information matrix of tangent plane \nR=[qx(i,j) qx_u qx_v;...\n qy(i,j) qy_u qy_v;...\n qz(i,j) qz_u qz_v];\n\n%The normal vector of tangent plane as same as the orient vector of a traigh lines \n%perpendicular with it and through source point \nnn=[(qy_u.*qz_v)-(qz_u.*qy_v);...\n (qz_u.*qx_v)-(qz_v.*qx_v);...\n (qx_u.*qy_v)-(qx_v.*qy_u)];\n\n%The geomatric information matrix of straigh lines d perpendicular with it and through source point \nd=[xs nn(1);...\n ys nn(2);...\n zs nn(3)];\n\n%Solving the equations\nAA=[nn(1) -qx_u -qx_v;...\n nn(2) -qy_u -qy_v;...\n nn(3) -qz_u -qz_v];\nsyms t1 t2 t3 % parametric variables\nT=[t1; t2; t3];\nBB=[(qx(i,j)-xs);...\n (qy(i,j)-ys);...\n (qz(i,j)-zs)];\nT=inv(AA)*BB;\n\n%The intersection points between the tangent plane and the straigh d\nH=S+T(1)*nn;\n\n%The reflective points of the source point about the tangent plane \nS_dx=2*H-S;\n%==================\nS_dxx(i,j)=S_dx(1);\nS_dxy(i,j)=S_dx(2);\nS_dxz(i,j)=S_dx(3);\nend\nend\n\n\n% Drawing the bezier surface\nview(3); \ngrid\nsurface(qx,qy,qz); xlabel('x');ylabel('y');zlabel('z');%\ntitle('The orthotomic surface of a bezier surface');\n\n%Drawing the source point\nhold on\nplot3(xs,ys,zs,'Pr','ButtonDownFcn','animator start','EraseMode','xor','LineWidth',2, ... \n'Marker','>','MarkerSize',5,'Tag','pointer');\ntext(xs+0.2,ys+0.2,zs+0.2,'S')\nhold on\n\n%Drawing the orthotomic surface\nsurface(S_dxx,S_dxy,S_dxz); xlabel('x');ylabel('y');zlabel('z');\n\n% Thank you very much for your course !\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/4731-orthotomic-surface-of-a-bezier-surface/buiquoctinh/run_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.764737235647525}} {"text": "function [esTheta, esPhi] = mie(radius, frequency, theta, phi, nMax)\n\n% Compute the complex-value scattered electric far field of a perfectly\n% conducting sphere using the mie series. Follows the treatment in\n% Chapter 3 of \n%\n% Ruck, et. al. \"Radar Cross Section Handbook\", Plenum Press, 1970.\n% \n% The incident electric field is in the -z direction (theta = 0) and is\n% theta-polarized. The time-harmonic convention exp(jwt) is assumed, and\n% the Green's function is of the form exp(-jkr)/r.\n% \n% Inputs:\n% radius: Radius of the sphere (meters)\n% frequency: Operating frequency (Hz)\n% theta: Scattered field theta angle (radians)\n% phi: Scattered field phi angle (radians)\n% nMax: Maximum mode for computing Bessel functions\n% Outputs:\n% esTheta: Theta-polarized electric field at the given scattering angles\n% esPhi: Phi-polarized electric field at the given scattering angles\n%\n% Output electric field values are normalized such that the square of the\n% magnitude is the radar cross section (RCS) in square meters.\n%\n% Author: Walton C. Gibson, email: kalla@tripoint.org\n\n% speed of light\nc = 299792458.0;\n\n% radian frequency\nw = 2.0*pi*frequency;\n\n% wavenumber\nk = w/c;\n\n% conversion factor between cartesian and spherical Bessel/Hankel function\ns = sqrt(0.5*pi/(k*radius));\n\n% mode numbers\nmode = 1:nMax; \n\n% compute spherical bessel, hankel functions\n[J(mode)] = besselj(mode + 1/2, k*radius); J = J*s;\n[H(mode)] = besselh(mode + 1/2, 2, k*radius); H = H*s;\n[J2(mode)] = besselj(mode + 1/2 - 1, k*radius); J2 = J2*s;\n[H2(mode)] = besselh(mode + 1/2 - 1, 2, k*radius); H2 = H2*s;\n \n% derivatives of spherical bessel and hankel functions\n% Recurrence relationship, Abramowitz and Stegun Page 361\nkaJ1P(mode) = (k*radius*J2 - mode .* J );\nkaH1P(mode) = (k*radius*H2 - mode .* H );\n\n\n% Ruck, et. al. (3.2-1)\nAn = -((i).^mode) .* ( J ./ H ) .* (2*mode + 1) ./ (mode.*(mode + 1));\n\n% Ruck, et. al. (3.2-2), using derivatives of bessel functions \nBn = ((i).^(mode+1)) .* (kaJ1P ./ kaH1P) .* (2*mode + 1) ./ (mode.*(mode + 1));\n \n[esTheta esPhi] = mieScatteredField(An, Bn, theta, phi, frequency);\n \nreturn", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/20430-scattered-field-of-a-conducting-and-stratified-spheres/mie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7645757268350922}} {"text": "%VL_NNNORMALIZE CNN Local Response Normalization (LRN)\n% Y = VL_NNORMALIZE(X, PARAM) computes the so-called Local Response\n% Normalization (LRN) operator. This operator performs a\n% channel-wise sliding window normalization of each column of the\n% input array X. The normalized output is given by:\n%\n% Y(i,j,k) = X(i,j,k) / L(i,j,k)^BETA\n%\n% where the normalization factor is given by\n%\n% L(i,j,k) = KAPPA + ALPHA * (sum_{q in Q(k)} X(i,j,k)^2,\n%\n% PARAM = [N KAPPA ALPHA BETA], and N is the size of the window. The\n% window Q(k) is defined as:\n%\n% Q(k) = [max(1, k-FLOOR((N-1)/2)), min(D, k+CEIL((N-1)/2))].\n%\n% where D is the number of feature channels in X. Note in particular\n% that, by setting N >= 2D, the function can be used to normalize\n% all the channels as a single group (useful to achieve L2\n% normalization).\n%\n% DZDX = VL_NNORMALIZE(X, PARAM, DZDY) computes the derivative of\n% the block projected onto DZDY. DZDX and DZDY have the same\n% dimensions as X and Y respectively.\n%\n% **Remark:** Some CNN libraries (e.g. Caffe) use a slightly\n% different convention for the parameters of the LRN. Caffe in\n% particular uses the convention:\n%\n% PARAM_CAFFE = [N KAPPA N*ALPHA BETA]\n%\n% i.e. the ALPHA paramter is multiplied by N.\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", "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/vl_nnnormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7645757242144876}} {"text": "function h = compute_sparse_spike_filter(type,n,options)\n\n% compute_sparse_spike_filter - compute a discrete seismic filter\n%\n% h = compute_sparse_spike_filter(type,n,options);\n%\n% type can be 'dergauss', 'seisfreq' or 'bump'\n% the width of the gaussian derivative is options.sigma, expressed in [-1,1]\n% so that the width in pixel is sigma*n/2.\n%\n% Copyright (c) 2008 Gabriel Peyre\n\n\nswitch type\n case 'dergauss'\n x = linspace(-1,1,n+1)'; x(end)= [];\n sigma = getoptions(options,'sigma',.02);\n h = x.*exp( -(x.^2)/(2*sigma^2) );\n h = (1-x.^2/sigma^2).*exp( -(x.^2)/(2*sigma^2) );\n h = h-mean(h);\n %sigma = .005;\n %h = exp( -(x.^2)/(2*sigma^2) );\n h0 = h/max(h);\n h0 = h/norm(h,'fro');\n h0 = .1*h0;\n % switch for fft\n h = [h0(end/2+1:end); h0(1:end/2)];\n case {'seisfreq' 'wavelet'}\n rho = getoptions(options, 'rho', .1 * 1024/n); \n % compute by frequency\n x = linspace(-1,1,n+1);\n hf = sin(pi*x/rho).^2;\n hf(abs(x)>rho) = 0;\n hf = [hf(n/2+1:end) hf(1:n/2-1)];\n h = real(ifft(hf));\n h = h'/max(h);\n h = h/sum(abs(h));\n \n case 'bump'\n sigma = getoptions(options,'sigma',.07);\n x = linspace(-1,1,n+1)'; x(end)=[];\n h = exp( -x.^2 / (2*(sigma)^2) );\n h = h; % /norm(h);\n h = [h(end/2+1:end); h(1:end/2)];\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_sparsity/compute_sparse_spike_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7645757205594611}} {"text": "function hyperball_monte_carlo_test02 ( )\n\n%*****************************************************************************80\n%\n%% HYPERBALL_MONTE_CARLO_TEST02 uses HYPERBALL01_SAMPLE in 6D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 6;\n\n e_test = [ ...\n 0, 0, 0, 0, 0, 0; ...\n 1, 0, 0, 0, 0, 0; ...\n 0, 2, 0, 0, 0, 0; ...\n 0, 2, 2, 0, 0, 0; ...\n 0, 0, 0, 4, 0, 0; ...\n 2, 0, 0, 0, 2, 2; ...\n 0, 0, 0, 0, 0, 6 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' Use the Monte Carlo method to estimate integrals \\n' );\n fprintf ( 1, ' over the interior of the unit hyperball in M dimensions.\\n' );\n fprintf ( 1, 'n' );\n fprintf ( 1, ' Spatial dimension M = %d\\n', m );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N' );\n fprintf ( 1, ' 1 ' );\n fprintf ( 1, ' U ' );\n fprintf ( 1, ' V^2 ' );\n fprintf ( 1, ' V^2W^2' );\n fprintf ( 1, ' X^4 ' );\n fprintf ( 1, ' Y^2Z^2' );\n fprintf ( 1, ' Z^6\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = hyperball01_sample ( m, n, seed );\n\n fprintf ( 1, ' %8d', n );\n for j = 1 : 7\n e(1:m) = e_test(1:m,j);\n value = monomial_value ( m, n, e, x );\n result(j) = hyperball01_volume ( m ) * sum ( value(1:n) ) / n;\n fprintf ( 1, ' %14.6g', result(j) );\n end\n fprintf ( 1, '\\n' );\n\n n = 2 * n;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact' );\n for j = 1 : 7\n e(1:m) = e_test(1:m,j);\n result(j) = hyperball01_monomial_integral ( m, e );\n fprintf ( 1, ' %14.6g', result(j) );\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/hyperball_monte_carlo/hyperball_monte_carlo_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7645603713345817}} {"text": "function normals = points2normals(points)\n % estimating a normal vector based on nearby 100 points\n % points is 3 * n matrix for n points\n\n if size(points,2)==3 && size(points,1)~=3\n points = points';\n end\n \n normals = lsqnormest(points, 100);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% functions from http://www.mathworks.com/matlabcentral/fileexchange/27804-iterative-closest-point\n\n% Least squares normal estimation from point clouds using PCA\n%\n% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle. \n% Surface reconstruction from unorganized points. \n% In Proceedings of ACM Siggraph, pages 71:78, 1992.\n%\n% p should be a matrix containing the horizontally concatenated column\n% vectors with points. k is a scalar indicating how many neighbors the\n% normal estimation is based upon.\n%\n% Note that for large point sets, the function performs significantly\n% faster if Statistics Toolbox >= v. 7.3 is installed.\n%\n% Jakob Wilm 2010\n\nfunction n = lsqnormest(p, k)\nm = size(p,2);\nn = zeros(3,m);\n\nv = ver('stats');\nif str2double(v.Version) >= 7.5 \n neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));\nelse\n neighbors = k_nearest_neighbors(p, p, k+1);\nend\n\nfor i = 1:m\n x = p(:,neighbors(2:end, i));\n p_bar = 1/k * sum(x,2);\n \n P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P\n %P = 2*cov(x);\n \n [V,D] = eig(P);\n \n [~, idx] = min(diag(D)); % choses the smallest eigenvalue\n \n n(:,i) = V(:,idx); % returns the corresponding eigenvector \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Program to find the k - nearest neighbors (kNN) within a set of points. \n% Distance metric used: Euclidean distance\n%\n% Note that this function makes repetitive use of min(), which seems to be\n% more efficient than sort() for k < 30.\n\nfunction [neighborIds,neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)\n\nnumDataPoints = size(dataMatrix,2);\nnumQueryPoints = size(queryMatrix,2);\n\nneighborIds = zeros(k,numQueryPoints);\nneighborDistances = zeros(k,numQueryPoints);\n\nD = size(dataMatrix, 1); %dimensionality of points\n\nfor i=1:numQueryPoints\n d=zeros(1,numDataPoints);\n for t=1:D % this is to avoid slow repmat()\n d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;\n end\n for j=1:k\n [s,t] = min(d);\n neighborIds(j,i)=t;\n neighborDistances(j,i)=sqrt(s);\n d(t) = NaN; % remove found number from d\n end\nend\n ", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/points2normals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7645603681016736}} {"text": "function vs = sphere_triangle_vertices_to_centroid ( r, v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_VERTICES_TO_CENTROID gets a spherical triangle centroid in 3D.\n%\n% Discussion:\n%\n% A sphere centered at 0 in 3D satisfies the equation:\n%\n% X*X + Y*Y + Z*Z = R*R\n%\n% A spherical triangle is specified by three points on the sphere.\n%\n% The (true) centroid of a spherical triangle is the point\n%\n% VT = (XT,YT,ZT) = Integral ( X, Y, Z ) dArea / Integral 1 dArea\n%\n% Note that the true centroid does NOT, in general, lie on the sphere. \n%\n% The \"flat\" centroid VF is the centroid of the planar triangle defined by\n% the vertices of the spherical triangle.\n%\n% The \"spherical\" centroid VS of a spherical triangle is computed by\n% the intersection of the geodesic bisectors of the triangle angles.\n% The spherical centroid lies on the sphere.\n%\n% VF, VT and VS lie on a line through the center of the sphere. We can\n% easily calculate VF by averaging the vertices, and from this determine\n% VS by normalizing.\n%\n% Of course, we still will not have actually computed VT, which lies\n% somewhere between VF and VS!\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% Parameters:\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real V1(3), V2(3), V3(3), the vertices of the triangle.\n%\n% Output, real VS(3), the coordinates of the \"spherical\n% centroid\" of the spherical triangle.\n%\n dim_num = 3;\n\n vs(1:dim_num) = ( v1(1:dim_num) + v2(1:dim_num) + v3(1:dim_num) ) / 3.0;\n\n norm = sqrt ( sum ( vs(1:dim_num).^2 ) );\n\n vs(1:dim_num) = r * vs(1:dim_num) / norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_triangle_vertices_to_centroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7645603584820693}} {"text": "function [HotellingT2] = HotellingT2(X,alpha)\n%Hotelling T-Squared testing procedures for multivariate samples. \n%\n% Syntax: function [HotellingT2] = HotellingT2(X,alpha) \n% \n% Inputs:\n% X - multivariate data matrix. \n% alpha - significance level (default = 0.05).\n%\n% Outputs:\n% It depends of the Hotelling's T-Squared multivariate test of interest, \n% being able to be:\n%\n% |-One-sample\n% | |-Homoskedasticity (to test)\n% | |-Independent |\n% | | |-Heteroskedasticity (to test)\n% |-Two-sample |\n% |\n% |-Dependent\n%\n% Each case calls to a corresponding function that contains a complete\n% explanation.\n%\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n% And the special collaboration of the post-graduate students of the 2002:2\n% Multivariate Statistics Course: Karel Castro-Morales, Alejandro Espinoza-Tenorio,\n% Andrea Guia-Ramirez.\n%\n% Copyright (C) December 2002.\n%\n\nif nargin < 2, \n alpha = 0.05; %(default)\nend; \n\nif nargin < 1, \n error('Requires at least one input argument.'); \nend; \n\nsam = input('Do you have one multivariate sample (1) or two multivariate samples (2)?: ');\nif sam == 1;\n T2Hot1(X,alpha)\nelse\n id = input('They are independent (1) or dependent (2)?: ');\n if id == 1;\n disp('The covariance matrix homogeneity will be testing.:');\n MBoxtest(X,alpha);\n disp(' ')\n dc = input('Are they significant? (y/n): ','s');\n if dc == 'y'\n T2Hot2ihe(X,alpha);\n else\n T2Hot2iho(X,alpha);\n end;\n else\n T2Hot2d(X,alpha);\n end;\nend;\n\nreturn;\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/ref functions/HotellingT2/HotellingT2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7645122591143312}} {"text": "%% file example_mtl_classify.m\n% This example shows how to perform classification using least squares\n% loss and logistic loss. \n%\n%% LICENSE\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye \n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on June 3, 2012.\n%\n\n\nclear, clc;\naddpath('../MALSAR/utils/')\naddpath('../MALSAR/functions/Lasso/')\n\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% training and prediction using least squares loss\nW_pred = Least_Lasso(X, Y, 0.01);\n% compute training error\nleast_acc = zeros(t, 1);\nfor i = 1: t\n least_acc(i) = nnz(sign(X{i} * W_pred(:, i)) == Y{i})/n;\nend\nfprintf('Least Squares Loss Training Accuracy: %.4f +/- %.4f\\n', mean(least_acc), std(least_acc));\n\n\n% training and prediction using logistic loss\n[W_pred C_pred]= Logistic_Lasso(X, Y, 0.01);\n% compute training error\nlogistic_acc = zeros(t, 1);\nfor i = 1: t\n logistic_acc(i) = nnz(sign(X{i} * W_pred(:, i) + C_pred(i)) == Y{i})/n;\nend\nfprintf('Logistic Loss Training Accuracy: %.4f +/- %.4f\\n', mean(logistic_acc), std(logistic_acc));\n\n\n\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_mtl_classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7644108656939668}} {"text": "function cdf = semicircular_cdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% SEMICIRCULAR_CDF evaluates the Semicircular CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, the parameter of the PDF.\n% 0.0 < B.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( x <= a - b )\n\n cdf = 0.0;\n\n elseif ( x <= a + b )\n\n y = ( x - a ) / b;\n\n cdf = 0.5 + ( y * sqrt ( 1.0 - y * y ) + asin ( y ) ) / pi;\n\n elseif ( a + b < x )\n\n cdf = 1.0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/semicircular_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7644108619260742}} {"text": "function ha = r8mat_house_hxa ( n, a, v )\n\n%*****************************************************************************80\n%\n%% R8MAT_HOUSE_HXA computes H*A where H is a compact Householder matrix.\n%\n% Discussion:\n%\n% The Householder matrix H(V) is defined by\n%\n% H(V) = I - 2 * v * v' / ( v' * v )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real A(N,N), the matrix to be premultiplied.\n%\n% Input, real V(N), a vector defining a Householder matrix.\n%\n% Output, real HA(N,N), the product H*A.\n%\n ha = a - 2.0 * v * v' * a / ( v' * v );\n\n return\nend\n", "meta": {"author": "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_hxa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7644108581290053}} {"text": "function BW = im2bw_ent(IM)\n% This fucntion convert an intensity image to a binary image\n% by using Entropy-based method\n%\n% Usage: BW = im2bw_ent(IM)\n% Input: IM -> Input Image\n% Output: BW -> Segmented Image\n%\n% Example:\n% IM = imread('house.jpg');\n% BW = im2bw_ent(IM);\n% imagesc(BW)\n%\n% Reference: E.R.Davies Machine Vision 3rd Edition\n\n% size of input image\ndim = size(IM);\n% Change input image to gray scale\nleng = length(dim);\nif leng == 3\n IM = rgb2gray(IM);\nend\n\n% histgram of input image\nihis = imhist(IM);\n\nleng = length(ihis);\npara = zeros(1,leng);\nfor k = 2:leng-1\n % intensity of class A\n classa = ihis(1:k);\n ind = (classa==0);\n classa = classa+ind;\n clear ind\n % intensity of class B\n classb = ihis(k+1:end);\n ind = (classb==0);\n classb = classb+ind;\n clear ind\n % probability distribution of class A\n Pa = classa/(dim(1,1)*dim(1,2));\n % probability distribution of class B\n Pb = classb/(dim(1,1)*dim(1,2));\n % parameters to decide threshold\n para1 = log2(sum(Pa));\n para2 = log2(sum(Pb));\n logpa = log2(Pa);\n logpb = log2(Pb);\n para3 = -sum(Pa.*logpa)/sum(Pa);\n para4 = -sum(Pb.*logpb)/sum(Pb);\n % parameter which has to be maximized\n para(1,k) = abs(para1+para2+para3+para4);\n clear classa classb logpa logpb\nend\n\n% find threshold\n[maxv,row] = max(para);\nthresh = row-1;\n% segment input image\nBW = (IM>=thresh);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8502-automatic-thresholding/im2bw_ent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642531177793, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7643544982264898}} {"text": "function a = plu ( n, pivot )\n\n%*****************************************************************************80\n%\n%% PLU returns the PLU matrix.\n%\n% Discussion:\n%\n% The PLU matrix has known P, L and U Gauss factors.\n%\n% Example:\n%\n% Input:\n%\n% N = 5\n% PIVOT = ( 1, 3, 3, 5, 5 )\n%\n% Output:\n%\n% A:\n%\n% 11 12 13 14 15\n% 1.375 9.75 43.25 44.75 46.25\n% 2.75 25 26.25 27.5 28.75\n% 0.34375 2.4375 7.71875 17.625 73.125\n% 0.6875 4.875 15.4375 60 61.5625\n%\n% P:\n%\n% 1 0 0 0 0\n% 0 0 1 0 0\n% 0 1 0 0 0\n% 0 0 0 0 1\n% 0 0 0 1 0\n%\n% L:\n%\n% 1 0 0 0 0\n% 0.25 1 0 0 0\n% 0.125 0.375 1 0 0\n% 0.0625 0.1875 0.3125 1 0\n% 0.03125 0.09375 0.15625 0.21875 1\n%\n% U:\n%\n% 11 12 13 14 15\n% 0 22 23 24 25\n% 0 0 33 34 35\n% 0 0 0 44 45\n% 0 0 0 0 55\n%\n% Note:\n%\n% The LINPACK routine DGEFA will factor the above A as:\n%\n% 11 12 13 14 15\n% -0.125 22 23 24 25\n% -0.25 -0.375 33 34 35\n% -0.03125 -0.09375 -0.15625 44 45\n% -0.0625 -0.1875 -0.3125 -0.21875 55\n%\n% and the pivot information in the vector IPVT as:\n%\n% ( 1, 3, 3, 5, 5 ).\n%\n% The LAPACK routine DGETRF will factor the above A as:\n%\n% 11 12 13 14 15\n% 0.25 22 23 24 25\n% 0.125 0.375 33 34 35\n% 0.0625 0.1875 0.3125 44 45\n% 0.03125 0.09375 0.15625 0.21875 55\n%\n% and the pivot information in the vector IPIV as:\n%\n% ( 1, 3, 3, 5, 5 ).\n%\n% Method:\n%\n% The L factor will have unit diagonal, and subdiagonal entries\n% L(I,J) = ( 2 * J - 1 ) / 2^I, which should result in a unique\n% value for every entry.\n%\n% The U factor of A will have entries\n% U(I,J) = 10 * I + J, which should result in \"nice\" entries as long\n% as N < 10.\n%\n% The P factor can be deduced by applying the pivoting operations\n% specified by PIVOT in reverse order to the rows of the identity.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer PIVOT(N), the list of pivot rows. PIVOT(I)\n% must be a value between I and N, reflecting the choice of\n% pivot row on the I-th step. For no pivoting, set PIVOT(I) = I.\n%\n% Output, real A(N,N), the matrix.\n%\n [ p, l, u ] = plu_plu ( n, pivot );\n\n a = p * l * u;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/plu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7643544926422357}} {"text": "function dstimgs = slpixlinnorm(imgs, mu, sigma)\n%SLPIXLINNORM Performs linear normalization on pixel values\n%\n% $ Syntax $\n% - dstimgs = slpixlinnorm(imgs);\n% - dstimgs = slpixlinnorm(imgs, mu, sigma)\n%\n% $ Arguments $\n% - imgs: the array of images\n% - mu: the mean pixel value to be normalized to (default = 0)\n% - sigma: the standard deviation relative to mean pixel (default = 1)\n%\n% $ Description $\n% - dstimgs = slpixlinnorm(imgs, mu, sigma) performs linear normalization\n% on the image pixels so that the average pixel value is set to mu\n% while the standard deviation is set to sigma. The normalization is\n% conducted on each page(channel) respectively.\n%\n% - dstimgs = slpixlinnorm(imgs) performs linear pixel value\n% normalization using default values.\n%\n% $ History $\n% - Created by Dahua Lin, on Aug 8th, 2006\n%\n\n%% parse and verify input arguments\n\nif ~isa(imgs, 'double')\n imgs = im2double(imgs);\nend\n[h, w, n] = size(imgs);\n\nif nargin < 2 || isempty(mu)\n mu = 0;\nend\n\nif nargin < 3 || isempty(sigma)\n sigma = 1;\nend\n\nd = h * w;\n\n%% perform normalization\n\nif n == 1\n dstimgs = normalize_page(imgs, d, mu, sigma);\nelse\n dstimgs = zeros(size(imgs));\n for i = 1 : n\n dstimgs(:,:,i) = normalize_page(imgs(:,:,i), d, mu, sigma);\n end\nend\n\n\nfunction dstimg = normalize_page(img, d, mu, sigma)\n\ncurimg = img(:);\n\n% compute current mean value\ncur_mv = sum(curimg) / d;\n\n% shift to zero mean\ncurimg = curimg - cur_mv;\n\n% compute current standard deviation\ncur_std = norm(curimg) / sqrt(d);\n\n% normalize to specified std dev\nk = sigma / cur_std;\ncurimg = curimg * k;\n\n% shift to specified mean\nif mu ~= 0\n curimg = curimg + mu;\nend\n\n% reshape back to origin shape\ndstimg = reshape(curimg, size(img));\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/imgproc/slpixlinnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7642747488304974}} {"text": "%% Rotation Demonstration: Discontinous Data\n%\n% A demonstration of how the timestep affects the error of the splitting\n% method for a rotation. Similar results can be expected in general,\n% although nonlinear sharpening may give smaller errors.\n%\n% The equation we solve is\n%\n% $$u_t - y u_x + x u_y = 0, \\qquad u(x,y,0)=u_0(x,y)$$\n%\n% where the initial function u0 is discontinuous. To solve the equation, we\n% will use Godunov splitting and front tracking to approximate the 1-D\n% solution operators.\n\n%% Initial setup\nT = 4*pi;\nxmin = -1.5; xmax=1.5; \nN = 128; \nh = (xmax-xmin)/N; \nx = xmin+h*(0:N);\ny = 0.5*(x(1:end-1)+x(2:end));\n[X,Y] = meshgrid(y,y);\nu0 = adiscontnuous_function(X,Y);\nsurfl(X,Y,u0); shading interp, view(-15,60), colormap(gray), axis tight\n\n%% Error versus CFL number\n% First we study the pointwise and the L1 error for CFL numbers 2.^(0:5)\ncolormap(jet)\nfor i=1:6\n\tnu=2^(i-1);\n\terr= abs( rotrack(u0,y,y,nu,T) - u0);\n subplot(2,3,i), pcolor(y,y,err), axis equal image, shading interp;\n set(colorbar('West'),'XColor',[1 1 1],'YColor',[1 1 1]);\n caxis([0 2]), title(['CFL = ', num2str(nu)]);\n set(gca,'XTick',[],'YTick',[])\n xlabel(['L1 error: ', num2str(h*h*sum(abs(err(:))))]);\n\tdrawnow;\nend;\n%%\n% The error is determined by two error mechanisms that work in opposite\n% directions. The splitting error increases with increasing splitting\n% steps, whereas the smoothing error caused by the projection operator\n% increases with decreasing splitting steps. The total splitting error is\n% therefore a convex function of the time step, and in the figure above,\n% the minimum error is observed for CFL number 16.\n\n%% Testing convergence \n% We choose the best CFL number vu=16, and check for convergence rate.\n% To this end, we use only one lap (it takes too long otherwise).\nT = 2*pi;\nLerr = zeros(1,7);\nwbar = waitbar(0,'Convergence study');\nfor i=1:7,\n\tN = 2^(i+3);\n\th = (xmax-xmin)/N; x=xmin+h*(1:N);\n\t[X,Y]=meshgrid(x,x);\n\tu0 = adiscontnuous_function(X,Y);\n\terr = abs(rotrack(u0,x,x,nu,T) - u0);\n\tLerr(i)=sum(err(:)) / sum(abs(u0(:)));\n\twaitbar(i/7,wbar);\nend;\nclose(wbar);\nclf, semilogy(1:7,Lerr,'o--');\nset(gca,'XTick',1:7,'XTickLabel',2.^((1:7)+3))\nxlabel('Grid size'); ylabel('Log(error)'); axis tight\ntitle('Errors for \\nu = 16');", "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/Rotationtrack/rotdemo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7642747428471297}} {"text": "% Chapter 3 - Complex Iterative Maps.\n% Program 3b - The Mandelbrot Set.\n% Thanks to Steve Lord from The MathWorks for his help.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Vectorized program.\n% Plot the Mandelbrot set in black and white (Figure 3.2).\nNmax = 50; scale = 0.005;\nxmin = -2.4; xmax = 1.2;\nymin = -1.5; ymax = 1.5;\n\n% Generate x and y coordinates and z complex values\n[x,y]=meshgrid(xmin:scale:xmax,ymin:scale:ymax);\nz = x+1i*y;\n\n% Generate w accumulation matrix and k counting matrix\nw = zeros(size(z));\nk = zeros(size(z));\n\nN = 0;\nwhile N4) = N;\nend\nk(k==0) = Nmax;\nfigure\ns = pcolor(x, y, mod(k, 2));\ncolormap([0 0 0;1 1 1])\nset(s,'edgecolor','none')\n\naxis([xmin xmax -ymax ymax])\nfsize=15;\nset(gca,'XTick',xmin:0.4:xmax,'FontSize',fsize)\nset(gca,'YTick',-ymax:0.5:ymax,'FontSize',fsize)\nxlabel('Re z','FontSize',fsize)\nylabel('Im z','FontSize',fsize)\n% End of Program 3b\n\n", "meta": {"author": "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_3b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.764271001054962}} {"text": "function value = r8_cin ( x )\n\n%*****************************************************************************80\n%\n%% R8_CIN evaluates the alternate cosine integral Cin of an R8 argument.\n%\n% Discussion:\n%\n% CIN(X) = gamma + log(X)\n% + integral ( 0 <= T <= X ) ( cos ( T ) - 1 ) / T dT\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the cosine integral Cin evaluated at X.\n%\n persistent cincs\n persistent eul\n persistent ncin\n persistent xmin\n\n eul = 0.57721566490153286060651209008240;\n\n if ( isempty ( ncin ) )\n\n cincs = [ ...\n 0.37074501750909688741654801228564992, ...\n -0.05893574896364446831956864397363697, ...\n 0.00538189642113569124048745326203340, ...\n -0.00029860052841962135319594906563410, ...\n 0.00001095572575321620077031054467306, ...\n -0.00000028405454877346630491727187731, ...\n 0.00000000546973994875384912457861806, ...\n -0.00000000008124187461318157083277452, ...\n 0.00000000000095868593117706609013181, ...\n -0.00000000000000920266004392351031377, ...\n 0.00000000000000007325887999017895024, ...\n -0.00000000000000000049143726675842909, ...\n 0.00000000000000000000281577746753902, ...\n -0.00000000000000000000001393986788501, ...\n 0.00000000000000000000000006022485646, ...\n -0.00000000000000000000000000022904717, ...\n 0.00000000000000000000000000000077273, ...\n -0.00000000000000000000000000000000233 ]';\n\n ncin = r8_inits ( cincs, 18, 0.1 * r8_mach ( 3 ) );\n xmin = sqrt ( r8_mach ( 1 ) );\n\n end\n\n absx = abs ( x );\n\n if ( absx <= xmin )\n value = 0.0;\n elseif ( absx <= 4.0 )\n value = r8_csevl ( ( x * x - 8.0 ) * 0.125, cincs, ncin ) * x * x;\n else\n [ f, g ] = r8_sifg ( absx );\n sinx = sin ( absx );\n value = - f * sinx + g * cos ( absx ) + log ( absx ) + eul;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_cin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7642167946027586}} {"text": "function [ xstar, seed ] = rk2_tv_step ( x, t, h, q, fv, gv, seed )\n\n%*****************************************************************************80\n%\n%% RK2_TV_STEP takes one step of a stochastic Runge Kutta scheme.\n%\n% Discussion:\n%\n% The Runge-Kutta scheme is second-order, and suitable for time-varying\n% systems.\n%\n% d/dx X(t,xsi) = F ( X(t,xsi), t ) + G ( X(t,xsi), t ) * w(t,xsi)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Jeremy Kasdin,\n% Runge-Kutta algorithm for the numerical integration of\n% stochastic differential equations,\n% Journal of Guidance, Control, and Dynamics,\n% Volume 18, Number 1, January-February 1995, pages 114-120.\n%\n% Jeremy Kasdin,\n% Discrete Simulation of Colored Noise and Stochastic Processes\n% and 1/f^a Power Law Noise Generation,\n% Proceedings of the IEEE,\n% Volume 83, Number 5, 1995, pages 802-827.\n%\n% Parameters:\n%\n% Input, real X, the value at the current time.\n%\n% Input, real T, the current time.\n%\n% Input, real H, the time step.\n%\n% Input, real Q, the spectral density of the input white noise.\n%\n% Input, external real FV, the name of the deterministic\n% right hand side function.\n%\n% Input, external real GV, the name of the stochastic\n% right hand side function.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, real XSTAR, the value at time T+H.\n%\n a21 = 1.0;\n a31 = 0.5;\n a32 = 0.5;\n\n q1 = 2.0;\n q2 = 2.0;\n\n t1 = t;\n x1 = x;\n [ n1, seed ] = r8_normal_01 ( seed );\n w1 = n1 * sqrt ( q1 * q / h );\n k1 = h * fv ( t1, x1 ) + h * gv ( t1, x1 ) * w1;\n\n t2 = t1 + a21 * h;\n x2 = x1 + a21 * k1;\n [ n2, seed ] = r8_normal_01 ( seed );\n w2 = n2 * sqrt ( q2 * q / h );\n k2 = h * fv ( t2, x2 ) + h * gv ( t2, x2 ) * w2;\n\n xstar = x1 + a31 * k1 + a32 * k2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stochastic_rk/rk2_tv_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7642167852022408}} {"text": "\nfunction fluxlimiter(N, method) \n% N = number of grid points\n\n% grid spacing on interval (-1,1)\ndx = 2./N; \n\n% location of cell centers \nx = linspace(-1+0.5*dx, 1-0.5*dx, N);\n\n% advection speed\nu = 1;\n\n% cfl condition + safety margin\ndt = 0.25*dx;\n\n% final time \nFinalTime = 2;\nNsteps = ceil(FinalTime/dt);\ndt = FinalTime/Nsteps;\nlam = u*dt/dx;\n\n% initial condition\nq = fluxlimiterexact(x); \n\n% time step\nfor n=1:Nsteps\n \n qp1 = [q(2:N),q(1)]; % q_{m+1}\n qm1 = [q(N),q(1:N-1)]; % q_{m-1}\n qm2 = [qm1(N), qm1(1:N-1)]; % q_{m-2}\n \n % compute limited cell average jumps based on method choice\n % theta_{i-1/2} = (q_{i-1}-q_{i-2})/(q_{i}-q_{i-1})\n tol = 1e-10;\n dq1 = q-qm1;\n dq2 = qm1-qm2;\n % have to test in case dq1 is small because of finite precision effects\n \n % are both dq1, and dq2 small (smooth)\n ids = find(abs(dq1)+abs(dq2)tol );\n thetaL(ids) = 100; % choose theta large\n \n % hopefully the remainder\n ids = find(abs(dq1)>= tol);\n thetaL(ids) = dq2(ids)./dq1(ids);\n \n if(strcmp(method,'minmod'))\n phiL = minmod(1, thetaL);\n elseif(strcmp(method,'MC'))\n phiL = max(0, min(min(0.5*(1+thetaL),2), 2*thetaL));\n elseif(strcmp(method,'vanleer'))\n phiL = (thetaL+abs(thetaL))./(1+abs(thetaL));\n elseif(strcmp(method,'superbee'))\n phiL = max(0, max(min(1,2*thetaL), min(2,thetaL)));\n elseif(strcmp(method,'Fromm'))\n phiL = 0.5*(1+thetaL);\n elseif(strcmp(method,'BeamWarming'))\n phiL = thetaL; % upwind\n elseif(strcmp(method,'LaxWendroff'))\n phiL = ones(size(q)); % downwind\n elseif(strcmp(method, 'upwind'))\n phiL = zeros(size(q));\n elseif(strcmp(method, 'custom'))\n \n phiL = customphi(thetaL);\n else\n disp('WARNING: wrong choice of flux limiter');\n end\n phiR = [phiL(2:N), phiL(1)];\n \n % update cell averages\n q = q - lam*(q-qm1) - 0.5*lam*(1-lam)*(phiR.*(qp1-q) -phiL.*(q-qm1)); \n\n if(mod(n,40)==0)\n plot(x,q, '.'); \n hold on; plot(x-0.5*dx, phiL, 'g-'); hold off;pause(0.02);\n end\nend\n\nplot(x, q, 'b.'); \n% have gone one exact period\nhold on; plot(x, fluxlimiterexact(x), 'r-'); hold off;\nhold on; plot(x-0.5*dx, phiL, 'g-'); hold off;\nxlabel('x'); \nlegend(sprintf('%s N=%d T=%f', method, N, FinalTime), ...\n 'Exact solution', sprintf('flux limiter function: phi_{%s}', method));\naxis([-1 1 -1 3])", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/NumericalMethods/fluxlimiter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.764134905437883}} {"text": "% hohmann.m July 9, 2013\n\n% Hohmann two impulse orbit transfer between\n% planar and non-coplanar circular orbits\n\n% includes three-dimensional orbit graphics\n% and graphical primer vector analysis\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal rtd dtr pvi pvdi\n\nglobal mu req hn1 hn2 hn3 dinc\n\n% astrodynamic and utility constants\n\nom_constants;\n\n% Brent root-finding tolerance\n\nrtol = 1.0e-8;\n\n% request inputs\n\nclc; home;\n\nfprintf('\\nHohmann Orbit Transfer Analysis\\n');\n\nwhile (1)\n \n fprintf('\\n\\nplease input the initial altitude (kilometers)\\n');\n \n alt1 = input('? ');\n \n if (alt1 > 0.0)\n break;\n end\n \nend\n\nwhile (1)\n \n fprintf('\\n\\nplease input the final altitude (kilometers)\\n');\n \n alt2 = input('? ');\n \n if (alt2 > 0.0)\n break;\n end\n \nend\n\nwhile (1)\n \n fprintf('\\n\\nplease input the initial orbital inclination (degrees)');\n fprintf('\\n(0 <= inclination <= 180)\\n');\n \n inc1 = input('? ');\n \n if (inc1 >= 0.0 && inc1 <= 180.0)\n break;\n end\n \nend\n\nwhile (1)\n \n fprintf('\\n\\nplease input the final orbital inclination (degrees)');\n fprintf('\\n(0 <= inclination <= 180)\\n');\n \n inc2 = input('? ');\n \n if (inc2 >= 0.0 && inc2 <= 180.0)\n break;\n end\n \nend\n\n% convert orbit inclinations to radians\n\ninc1 = inc1 * dtr;\n\ninc2 = inc2 * dtr;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve the orbit transfer problem %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% calculate total inclination change (radians)\n\ndinc = abs(inc2 - inc1);\n\n% compute geocentric radii of initial and final orbits (kilometers)\n\nr1 = req + alt1;\n\nr2 = req + alt2;\n\n% compute \"normalized\" radii\n\nhn1 = sqrt(2.0 * r2 / (r2 + r1));\n\nhn2 = sqrt(r1 / r2);\n\nhn3 = sqrt(2.0 * r1 / (r2 + r1));\n\n% compute \"local circular velocity\" of initial and final orbits (km/sec)\n\nv1 = sqrt(mu / r1);\n\nv2 = sqrt(mu / r2);\n\n% compute transfer orbit semimajor axis (kilometers)\n\nsmat = 0.5 * (r1 + r2);\n\n% compute transfer orbit eccentricity (non-dimensional)\n\necct = (max(r1, r2) - min(r1, r2)) / (r1 + r2);\n\n% compute transfer orbit perigee and apogee radii and velocities\n\nrp = smat * (1.0 - ecct);\n\nra = smat * (1.0 + ecct);\n\nvt1 = sqrt(2.0 * mu * ra / (rp * (rp + ra)));\n\nvt2 = sqrt(2.0 * mu * rp / (ra * (rp + ra)));\n\n% compute transfer orbit period (seconds)\n\ntaut = 2.0 * pi * sqrt(smat^3 / mu);\n\ntof = 0.5 * taut;\n\nif (abs(dinc) == 0)\n \n % coplanar orbit transfer\n \n if (r2 > r1)\n \n % higher-to-lower transfer\n \n dv1 = vt1 - v1;\n \n dv2 = v2 - vt2;\n \n else\n \n % lower-to-higher transfer\n \n dv1 = v1 - vt2;\n \n dv2 = vt1 - v2;\n \n end\n \n dinc1 = 0;\n \n dinc2 = 0;\n \n inct = inc1;\n \nelse\n \n % non-coplanar orbit transfer\n \n [xroot, froot] = brent('hohmfunc', 0, dinc, rtol);\n \n % calculate delta-v's\n \n dinc1 = xroot;\n \n dinc2 = dinc - dinc1;\n \n dv1 = v1 * sqrt(1.0 + hn1 * hn1 - 2.0 * hn1 * cos(dinc1));\n \n dv2 = v1 * sqrt(hn2 * hn2 * hn3 * hn3 + hn2 * hn2 ...\n - 2.0 * hn2 * hn2 * hn3 * cos(dinc2));\n \n if (inc2 > inc1)\n \n inct = inc1 + dinc1;\n \n else\n \n inct = inc1 - dinc1;\n \n end\n \nend\n\n% print results\n\nclc; home;\n\nfprintf('\\nHohmann Orbit Transfer Analysis');\nfprintf('\\n-------------------------------\\n\\n');\n\nfprintf('initial orbit altitude %10.4f kilometers \\n\\n', alt1);\n\nfprintf('initial orbit radius %10.4f kilometers \\n\\n', alt1 + req);\n\nfprintf('initial orbit inclination %10.4f degrees \\n\\n', inc1 * rtd);\n\nfprintf('initial orbit velocity %10.4f meters/second \\n\\n\\n', 1000.0 * v1);\n\nfprintf('final orbit altitude %10.4f kilometers \\n\\n', alt2);\n\nfprintf('final orbit radius %10.4f kilometers \\n\\n', alt2 + req);\n\nfprintf('final orbit inclination %10.4f degrees \\n\\n', inc2 * rtd);\n\nfprintf('final orbit velocity %10.4f meters/second \\n', 1000.0 * v2);\n\nfprintf('\\n\\nfirst inclination change %10.4f degrees\\n\\n', dinc1 * rtd);\n\nfprintf('second inclination change %10.4f degrees\\n\\n', dinc2 * rtd);\n\nfprintf('total inclination change %10.4f degrees\\n\\n\\n', rtd * (dinc1 + dinc2));\n\nfprintf('first delta-v %10.4f meters/second \\n\\n', 1000.0 * dv1);\n\nfprintf('second delta-v %10.4f meters/second \\n\\n', 1000.0 * dv2);\n\nfprintf('total delta-v %10.4f meters/second \\n\\n\\n', 1000.0 * (dv1 + dv2));\n\nfprintf('transfer orbit semimajor axis %10.4f kilometers \\n\\n', smat);\n\nfprintf('transfer orbit eccentricity %10.8f \\n\\n', ecct);\n\nfprintf('transfer orbit inclination %10.4f degrees \\n\\n', rtd * inct);\n\nfprintf('transfer orbit perigee velocity %10.4f meters/second \\n\\n', 1000.0 * vt1);\n\nfprintf('transfer orbit apogee velocity %10.4f meters/second \\n\\n', 1000.0 * vt2);\n\nfprintf('transfer orbit coast time %10.4f seconds \\n', tof);\n\nfprintf(' %10.4f minutes \\n', tof / 60.0);\n\nfprintf(' %10.4f hours \\n\\n', tof / 3600.0);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% create trajectory graphics %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% load orbital elements arrays, create state vectors and plot orbits\n\noevi(1) = r1;\noevi(2) = 0.0;\noevi(3) = inc1;\noevi(4) = 0.0;\noevi(5) = 0.0;\n\n% determine correct true anomaly (radians)\n\nif (alt2 > alt1)\n \n oevi(6) = 0.0;\n \nelse\n \n oevi(6) = 180.0 * dtr;\n \nend\n\n[ri, vi] = orb2eci(mu, oevi);\n\noevti(1) = smat;\noevti(2) = ecct;\noevti(3) = inct;\noevti(4) = 0.0;\noevti(5) = 0.0;\n\n% determine correct true anomaly (radians)\n\nif (alt2 > alt1)\n \n oevti(6) = 0.0;\n \nelse\n \n oevti(6) = 180.0 * dtr;\n \nend\n\n[rti, vti] = orb2eci(mu, oevti);\n\noevtf(1) = smat;\noevtf(2) = ecct;\noevtf(3) = inct;\noevtf(4) = 0.0;\noevtf(5) = 0.0;\n\n% determine correct true anomaly (radians)\n\nif (alt2 > alt1)\n \n oevtf(6) = 180.0 * dtr;\n \nelse\n \n oevtf(6) = 0.0;\n \nend\n\n[rtf, vtf] = orb2eci(mu, oevtf);\n\noevf(1) = r2;\noevf(2) = 0.0;\noevf(3) = inc2;\noevf(4) = 0.0;\noevf(5) = 0.0;\n\n% determine correct true anomaly (radians)\n\nif (alt2 > alt1)\n \n oevf(6) = 180.0 * dtr;\n \nelse\n \n oevf(6) = 0.0;\n \nend\n\n[rf, vf] = orb2eci(mu, oevf);\n\n% compute orbital periods\n\nperiod1 = 2.0 * pi * oevi(1) * sqrt(oevi(1) / mu);\n\nperiod2 = 2.0 * pi * oevti(1) * sqrt(oevti(1) / mu);\n\nperiod3 = 2.0 * pi * oevf(1) * sqrt(oevf(1) / mu);\n\ndeltat1 = period1 / 300;\n\nsimtime1 = -deltat1;\n\ndeltat2 = 0.5 * period2 / 300;\n\nsimtime2 = -deltat2;\n\ndeltat3 = period3 / 300;\n\nsimtime3 = -deltat3;\n\nfor i = 1:1:301\n \n simtime1 = simtime1 + deltat1;\n \n simtime2 = simtime2 + deltat2;\n \n simtime3 = simtime3 + deltat3;\n \n % compute initial orbit \"normalized\" position vector\n \n [rwrk, vwrk] = twobody2 (mu, simtime1, ri, vi);\n \n rp1_x(i) = rwrk(1) / req;\n \n rp1_y(i) = rwrk(2) / req;\n \n rp1_z(i) = rwrk(3) / req;\n \n % compute transfer orbit position vector\n \n [rwrk, vwrk] = twobody2 (mu, simtime2, rti, vti);\n \n rp2_x(i) = rwrk(1) / req;\n \n rp2_y(i) = rwrk(2) / req;\n \n rp2_z(i) = rwrk(3) / req;\n \n % compute final orbit position vector\n \n [rwrk, vwrk] = twobody2 (mu, simtime3, rf, vf);\n \n rp3_x(i) = rwrk(1) / req;\n \n rp3_y(i) = rwrk(2) / req;\n \n rp3_z(i) = rwrk(3) / req;\n \nend\n\nfigure(1);\n\n% create axes vectors\n\nxaxisx = [1 1.5];\nxaxisy = [0 0];\nxaxisz = [0 0];\n\nyaxisx = [0 0];\nyaxisy = [1 1.5];\nyaxisz = [0 0];\n\nzaxisx = [0 0];\nzaxisy = [0 0];\nzaxisz = [1 1.5];\n\nfigure (1);\n\nhold on;\n\ngrid on;\n\n% plot earth\n\n[x y z] = sphere(24);\n\nh = surf(x, y, z);\n\ncolormap([127/255 1 222/255]);\n\nset (h, 'edgecolor', [1 1 1]);\n\n% plot coordinate system axes\n\nplot3(xaxisx, xaxisy, xaxisz, '-g', 'LineWidth', 1);\n\nplot3(yaxisx, yaxisy, yaxisz, '-r', 'LineWidth', 1);\n\nplot3(zaxisx, zaxisy, zaxisz, '-b', 'LineWidth', 1);\n\n% plot initial orbit\n\nplot3(rp1_x, rp1_y, rp1_z, '-r', 'LineWidth', 1.5);\n\nplot3(rp1_x(1), rp1_y(1), rp1_z(1), 'ob');\n\n% plot transfer orbit\n\nplot3(rp2_x, rp2_y, rp2_z, '-b', 'LineWidth', 1.5);\n\nplot3(rp2_x(end), rp2_y(end), rp2_z(end), 'ob');\n\n% plot final orbit\n\nplot3(rp3_x, rp3_y, rp3_z, '-g', 'LineWidth', 1.5);\n\nxlabel('X coordinate (ER)', 'FontSize', 12);\n\nylabel('Y coordinate (ER)', 'FontSize', 12);\n\nzlabel('Z coordinate (ER)', 'FontSize', 12);\n\ntitle('Hohmann Transfer: Initial, Transfer and Final Orbits', 'FontSize', 16);\n\naxis equal;\n\nview(50, 20);\n\nrotate3d on;\n\nprint -depsc -tiff -r300 hohmann1.eps\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% create primer graphics\n%%%%%%%%%%%%%%%%%%%%%%%%\n\ndvi = (vti - vi)';\n\ndvf = (vf - vtf)';\n\n% perform primer vector initialization\n\npviniz(tof, rti, vti, dvi, dvf);\n\n% number of graphic data points\n\nnpts = 300;\n\n% plot behavior of primer vector magnitude\n\ndt = tof / npts;\n\nfor i = 1:1:npts + 1\n \n t = (i - 1) * dt;\n \n if (t == 0)\n \n % initial value of primer magnitude and derivative\n \n pvm = norm(pvi);\n \n pvdm = dot(pvi, pvdi) / pvm;\n \n else\n \n % primer vector and derivative magnitudes at time t\n \n [pvm, pvdm] = pvector(rti, vti, t);\n \n end\n \n % load data array\n \n x1(i) = t / 60.0;\n \n y1(i) = pvm;\n \n y2(i) = pvdm;\n \nend\n\nfigure(2);\n\nhold on;\n\nplot(x1, y1, '-r', 'LineWidth', 1.5);\n\nplot(x1(1), y1(1), 'or');\n\nplot(x1(end), y1(end), 'or');\n\ntitle('Primer Vector Analysis of the Hohmann Transfer', 'FontSize', 16);\n\nxlabel('simulation time (minutes)', 'FontSize', 12);\n\nylabel('primer vector magnitude', 'FontSize', 12);\n\ngrid;\n\n% create eps graphics file with tiff preview\n\nprint -depsc -tiff -r300 primer.eps;\n\n% plot behavior of magnitude of primer derivative\n\nfigure(3);\n\nhold on;\n\nplot(x1, y2, '-r', 'LineWidth', 1.5);\n\nplot(x1(1), y2(1), 'or');\n\nplot(x1(end), y2(end), 'or');\n\ntitle('Primer Vector Analysis of the Hohmann Transfer', 'FontSize', 16);\n\nxlabel('simulation time (minutes)', 'FontSize', 12);\n\nylabel('primer derivative magnitude', 'FontSize', 12);\n\ngrid;\n\n% create eps graphics file with tiff preview\n\nprint -depsc -tiff -r300 primer_der.eps;\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/38942-the-hohmann-orbit-transfer/hohmann.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7640864924082832}} {"text": "function [theta] = normalEqn(X, y)\n %% NORMALEQN Computes the closed-form solution to linear regression \n % NORMALEQN(X,y) computes the closed-form solution to linear \n % regression using the normal equations.\n theta = pinv(X' * X) * X' * y;\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/linear-regression/code/normalEqn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7640864841899335}} {"text": "%MAIN_singlePendulum.m\n%\n% This script runs a simple simulation of a single pendulum\n\n% Use: EoM_Single_Pendulum to write the equations of motion\n\nm = 1.0; % (kg) pendulum mass\ng = 9.81; % (m/s^2) gravity\nl = 1.0; % (m) pendulum length\n\ntSpan = [0,10]; %Simulation time interval\n\nth0 = (pi/180)*(-178); %Initial angle\nw0 = 0; %Initial angular rate\nz0 = [th0;w0];\n\nuserFunc = @(t,z)singlePendulumRhs(t,z,g,l);\n\noptions = odeset(...\n 'AbsTol',1e-8,...\n 'RelTol',1e-8,...\n 'Vectorized','on');\n\n% Run the simulation!\nsol = ode45(userFunc,tSpan,z0,options);\n\n% Break apart solution for plotting\nnPlot = 1000;\ntime = linspace(tSpan(1),tSpan(2),nPlot);\nz = deval(sol,time); %Evaluate solution from ode45 at points in time\nth = z(1,:);\nw = z(2,:);\n[energy, kinetic, potential] = singlePendulumEnergy(th,w,m,g,l);\n\n% Plotting!\n\nfigure(1111);clf;\n\nsubplot(3,1,1);\nplot(time,th,'k-','LineWidth',2);\nxlabel('time (s)')\nylabel('angle (rad)');\n\nsubplot(3,1,2);\nplot(time,w,'k-','LineWidth',2);\nxlabel('time (s)')\nylabel('angle rate (rad/s)');\n\n\nsubplot(3,1,3); hold on;\nplot(time,energy,'k-','LineWidth',3);\nplot(time,kinetic,'r-','LineWidth',2);\nplot(time,potential,'b-','LineWidth',2);\nxlabel('time (s)')\nylabel('energy (J)');\nlegend('total','kinetic','potential');\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/singlePendulum/MAIN_singlePendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7640798208467026}} {"text": "function [err, C] = gen_pos_err(std, n, type, absolute)\n%GEN_POS_ERR Generates position errors. We first generate i.i.d. position errors\n%for each sensor. We use the first sensor as the reference sensor and substract\n%the the position error of the first sensor from the remaining sensors.\n%Therefore, the resulting covariance matrix is not diagonal.\n%Inputs:\n% std - Standard deviation of the position errors.\n% n - Number of sensors.\n% type - 'Gaussian' or 'Uniform'.\n% absolute - If set to true, will not use the first sensor as the reference\n% sensor and the position errors will be i.i.d.\n%Outputs:\n% err - 2xn vector of position errors.\n% C - Covariance matrix. (2n-2) x (2n-2) if absolute is false, (2n) x (2n) if\n% absolute is true.\nif nargin < 4\n absolute = false;\nend\nswitch lower(type)\n case 'gaussian'\n err = randn(2, n)*std;\n if nargout > 1\n if absolute\n C = std^2*eye(n + n);\n else\n C = std^2*(eye(n - 1) + ones(n - 1));\n C = blkdiag(C, C);\n end\n end\n case 'uniform'\n b = sqrt(3)*std;\n err = unifrnd(-b, b, 2, n);\n if nargout > 1\n if absolute\n C = std^2*eye(n + n);\n else\n C = std^2*(eye(n - 1) + ones(n - 1));\n C = blkdiag(C, C);\n end\n end\n otherwise\n error('Unknow type \"%s\".', type);\nend\nif ~absolute\n err(1,2:end) = err(1,2:end) - err(1,1);\n err(2,2:end) = err(2,2:end) - err(2,1);\n err(1,1) = 0;\n err(2,1) = 0;\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/examples/experiments/location_errors/gen_pos_err.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7640798149188867}} {"text": "function Zf = filt2(Z,res,lambda,filtertype) \n% filt2 performs a highpass, lowpass, bandpass, or bandstop 2D gaussian filter on gridded data such as \n% topographic, atmospheric, oceanographic, or any kind of geospatial data. This function is designed to\n% make it easy to remove features longer or shorter than a given characteristic wavelength. The\n% input grid can contain NaNs! \n% \n%% Syntax\n% \n% Zf = filt2(Z,res,lambda,filtertype)\n% \n%% Description \n% \n% Zf = filt2(Z,res,lambda,filtertype) filters 2D dataset Z that has resolution res, \n% to an approximate wavelength lambda. If the filtertype is 'lp' or 'hp' for lowpass\n% or highpass, lambda must be a scalar value. If the filtertype is 'bp' or 'bs' for \n% bandpass or bandstop, lambda must be a two-element array of the two cutoff wavelengths. \n% \n%% Explanation of this type of filter \n% For an explanation of this filter with pictures, type \n% \n% showdemo filt2_documentation \n% \n% into your command window. \n% \n%% Example\n% Consider a 100 km by 100 km elevation dataset that has a resolution of 200 m. It has \n% some long 25 km wavelength features aligned with north/south direction, some short \n% ~5 km features oriented diagonally, and a considerable amount of random noise. There's\n% also a block of missing data. Here's what your datset looks like: \n% \n% res = 0.2; % 200 m resolution\n% x = 0:res:100; % eastings from 0 to 100 km\n% y = 0:res:100; % northings from 0 to 100 km\n% [X,Y] = meshgrid(x,y);\n% \n% % Z contains 25 km features, ~5 km diagonal features, and noise: \n% Z = cos(2*pi*X/25)+cos(2*pi*(X+Y)/7)+randn(size(X)); \n% \n% % Z also has some missing data: \n% Z(100:120,100:120) = nan; \n% \n% subplot(1,3,1) \n% imagesc(x,y,Z); \n% axis xy image \n% caxis([-1 1])\n% title ' original Z matrix '\n% xlabel ' eastings (km) '\n% ylabel ' northings (km) '\n% \n% % Get the lowpass-filtered version of Z: \n% Zlow = filt2(Z,res,15,'lp'); \n% \n% subplot(1,3,2) \n% imagesc(x,y,Zlow); \n% axis xy image \n% caxis([-1 1])\n% title ' 15 km lowpass filtered Z matrix ' \n% xlabel ' eastings (km) '\n% ylabel ' northings (km) '\n% \n% % Get the highpass-filtered version of Z: \n% Zhi = filt2(Z,res,15,'hp'); \n% \n% subplot(1,3,3) \n% imagesc(x,y,Zhi); \n% axis xy image \n% caxis([-1 1])\n% title ' 15 km highpass filtered Z matrix ' \n% xlabel ' eastings (km) '\n% ylabel ' northings (km) '\n% \n%% Author Info\n% This function was written by Chad A. Greene of the University of Texas Institute for \n% Geophysics in November 2016; however, all I did was repackage Carlos Adrian Vargas Aguilera's \n% superb ndnanfilter function, which can be found here: http://www.mathworks.com/matlabcentral/fileexchange/20417. \n% Many thanks to Carlos for his well-thought-out code and clear documentation. \n% \n% See also conv2, imgaussfilt, and imfilter.\n\n%% Input checks\n\nnarginchk(4,4) \n% assert(license('test','image_toolbox')==1,'Error: I''m sorry, the filt2 function requires the Image Processing Toolbox.') \nassert(ismatrix(Z)==1,'Input error: Z must be a 2d matrix.')\n%assert(isscalar(res)==1,'Input error: res must be a scalar value.') \nassert(ismember(lower(filtertype),{'lp','hp','bp','bs'}),'Input error: filtertype must be ''hp'', ''lp'', ''bp'', or ''bs''.') \nif lambda<=(2*max(res)) \n warning('Nyquist says the wavelength should exceed two times the resolution of the dataset, which is an unmet condition based on these inputs. I''ll give you some numbers, but I would''t trust ''em if I were you.') \nend\n\nif ismember(lower(filtertype),{'bp','bs'})\n assert(numel(lambda)==2,'Input error: Wavelength lambda must be a two-element array for a bandpass filter.') \nelse\n assert(isscalar(lambda)==1,'Input error: Wavelength lambda must be a scalar for lowpass or bandpass filters.') \nend\n\n%% Design filter: \n\n% 2*pi*sigma is the wavelength at which the amplitude is multiplied by a factor of about 0.6 (more exactly, exp(-0.5))\nsigma = (lambda(1)./res) /(2*pi); \n%f = fspecial('gaussian',2*ceil(2.6*sigma)+1,sigma);\n% WJP implementation without image processing toolbox, subfunc at bottom of\n% this function\nf = gaussian2D([2*ceil(2.6*sigma(1))+1 2*ceil(2.6*sigma(end))+1], sigma);\n\n%% Now filter the data\n\nswitch lower(filtertype)\n %WJP incorrect usage originally but happened to work if imfilter is available\n case 'lp'\n Zf = ndnanfilter(Z,f,size(f),[],[],{'replicate'}); % ndnanfilter is Carlos Adrian Vargas Aguilera's excellent function, which is included as a subfunction below. \n \n case 'hp'\n Zf = Z - ndnanfilter(Z,f,size(f),[],[],{'replicate'}); \n \n case 'bp' \n Zf = filt2(filt2(Z,res,max(lambda),'hp'),res,min(lambda),'lp'); \n \n case 'bs' \n Zf = filt2(Z,res,max(lambda),'lp') - filt2(Z,res,min(lambda),'hp'); \n \n otherwise \n error('No such filter type.') \nend\n\n\nend\n\n\nfunction [Y,W] = ndnanfilter(X,HWIN,F,DIM,WINOPT,PADOPT,WNAN)\n% NDNANFILTER N-dimensional zero-phase digital filter, ignoring NaNs.\n%\n% Syntax:\n% Y = ndnanfilter(X,HWIN,F);\n% Y = ndnanfilter(X,HWIN,F,DIM);\n% Y = ndnanfilter(X,HWIN,F,DIM,WINOPT);\n% Y = ndnanfilter(X,HWIN,F,DIM,WINOPT,PADOPT);\n% Y = ndnanfilter(X,HWIN,F,DIM,WINOPT,PADOPT,WNAN);\n% [Y,W] = ndnanfilter(...);\n%\n% Input:\n% X - Data to be filtered with/without NaNs.\n% HWIN - Window function handle (or name) or numeric multidimensional\n% window to be used (without NaNs). See WINDOW for details. \n% Default: @rectwin or 'rectwin' (moving average).\n% F - A vector specifying the semi-width of the window for each\n% dimension. The final window's width will be 2*F+1. \n% Default: 3 (i.e. a 1-dimensional window of width 6).\n% DIM - If F is a single scalar, the window will be applied through\n% this dimension; otherwise, this will be ignored. \n% Default: columns (or the first non-singleton dimension).\n% WINOPT - Cell array specifying optional arguments for the window\n% function HWIN (in addition to the width). \n% Default: {} (window's defaults).\n% PADOPT - Cell array specifying the optional arguments for the\n% PADARRAY MATLAB's function (in addition to the array X and\n% the padsize: 2*F+1). If the function is not found, data is\n% padded with zeros or the specified value: try {mean(X(:))}\n% for example.\n% Default: {'replicate'} (repeats border elements of X).\n% Default: {0} (pads with zeros if PADARRAY not found).\n% WNAN - Integer indicating NaNs treatment and program behaviour!:\n% 0: Filters data and interpolates NaNs (default). \n% 1: Filters data but do not interpolates NaNs \n% 2: \"Do not filters data\" but interpolates NaNs!\n% See the NOTEs below\n%\n% Output:\n% Y - Filtered X data (same size as X!).\n% W - N-dimensional window with central symmetry generated by a\n% special subfunction called NDWIND. See the description below\n% for details.\n%\n% Description:\n% This function applies a N-dimensional convolution of X with W, using\n% the MATLAB's IMFILTER or CONVN function. One important aspect of the\n% function is the generation of the N-dimensional window (W) from the\n% specified function and width, which cannot be done with MATLAB's\n% functions. Besides, unlike MATLAB's FILTER, FILTER2 and IMFILTER,\n% NaNs elements are taken into account (ignored).\n%\n% The N-dimensional window is generated from rotating the 1-dimensional\n% output of the HWIN function, through each of the N-dimensions, and\n% then shrinking it through each of its axes in order to fit the\n% specified semi-widths (F). This is done in the included subfunction\n% named NDWIND. In this way, the window has central symmetry and do not\n% produce a phase shift on X data.\n%\n% By default, the edges are padded with the values of X at the borders\n% with the PADARRAY MATLAB's function. In this way, the edges are\n% treated smoothly. When PADARRAY is not found, the program performs\n% zero-padding.\n%\n% Notes: \n% * The use of semi-widths F's is to force the generated window to be\n% even and, therefore, the change of phase is null. \n% * The window function HWIN should output an even function, otherwise,\n% it won't generate an error but the user should be aware that this\n% program will consider only the last half of it.\n% * The function window should return a monotonically decreasing\n% result, this restriction is because I try to avoid the use of FZERO\n% function, for example, to find the expanding/shrinking factors.\n% * If the user has an already generated window, it can be used in HWIN\n% instead of a function handle or name. \n% * Accepts empty value for any input. When X is empty, the program can\n% be used as a N-dimensional window generator.\n% * NaNs elements surrounded by no-NaNs elements (which will depend on\n% window width) are the ones that will be interpolated. The others\n% are leaved untouched.\n% * When WNAN=2, the programs acts like an NAN-interpolat/GAP-filling,\n% leaving untouched the no-NaNs elements but the filtering is\n% perfomed anyway. I recomend the default behaviour (WNAN=0) in order\n% to keep the filtered data in the workspace, and then use the code\n% at the end of this function to get/remove the interpolated NaNs\n% (see the example).\n% * The program looks for the IMFILTER and PADARRAY functions from the\n% Image Processing Toolbox. If not found, then CONVN is used instead\n% (slower) and pads with zeros or the given value. In this latter\n% case, if border elements are NaNs, the window won't work properly.\n%\n% Example:\n% FWIN = 'hamming';\n% F = [13 8];\n% N = 100;\n% Pnoise = 0.30;\n% PNaNs = 0.20;\n% X = peaks(N); % original\n% Y = X + ((rand(size(X))-0.5)*2)*max(X(:))*Pnoise; % add noise\n% Y(round(1 + (N^2-1).*rand(N^2*PNaNs,1))) = NaN; % add NaNs\n% [Z0,W] = ndnanfilter(Y,FWIN,F); % filters\n% Z1 = Z0; Z2 = Y; inan = isnan(Y);\n% Z1(inan) = NaN;\n% Z2(inan) = Z0(inan); \n% subplot(231), imagesc(X), clim = caxis; axis equal tight\n% title('Original data')\n% subplot(232), imagesc(Y), caxis(clim), axis equal tight \n% title('Data + NOISE + NaNs')\n% subplot(234), imagesc(Z0), caxis(clim), axis equal tight \n% title('FILTERS + NaNs interpolation')\n% subplot(235), imagesc(Z1), caxis(clim), axis equal tight \n% title('FILTERS ignoring NaNs')\n% subplot(236), imagesc(Z2), caxis(clim), axis equal tight \n% title('GAP-filling with interpolated NaNs')\n% subplot(233), imagesc(-F(1):F(1),-F(2):F(2),W), axis equal tight, \n% title([upper(FWIN) ' 2D window']), view(2) \n%\n% See also: FILTER, FILTER2 and CONVN; WINDOW from the Signal Processing\n% Toolbox; and FWIND1, FWIND2, FSPECIAL, IMFILTER and PADARRAY from the\n% Image Processing Toolbox. \n\n% Copyright 2008 Carlos Adrian Vargas Aguilera\n% $Revision: 1.2 $ $Date: 2008/06/30 18:00:00 $\n\n% Written by\n% M.S. Carlos Adrian Vargas Aguilera\n% Physical Oceanography PhD candidate\n% CICESE \n% Mexico, 2008\n% nubeobscura@hotmail.com\n%\n% Download from:\n% http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objec\n% tType=author&objectId=1093874\n\n% 1.0 Release (2008/06/23 10:30:00)\n% 1.1 Fixed Bug adding an extra dimension of unitary width. \n% 1.2 Fixed Bug with ynan.\n\n% Use the IMFILTER function? (faster than CONVN):\nyimfilter = (exist('imfilter','file')==2);\n\n% Use the PADARRAY function (or zero padding): \nypadarray = (exist('padarray','file')==2);\n\n% Check inputs and sets defaults of principal arguments:\nif nargin<3 || nargin>7\n error('Filtern:IncorrectNumberOfInputs',...\n 'At least three inputs are needed and less than 7.')\nend\nif isempty(HWIN)\n HWIN = 'rectwin';\nend\nif isempty(F)\n F = 3;\nend\nN = length(F);\nS = size(X);\n% Secondary arguments:\nif N && (nargin<4 || isempty(DIM))\n DIM = find(S~=1,1); % DIM = min(find(S~=1));\n if isempty(DIM), DIM = 1; end\nend\nif nargin<5 || isempty(WINOPT)\n WINOPT = {};\nend\nif nargin<6 || isempty(PADOPT)\n if ypadarray\n PADOPT = {'replicate'};\n else\n PADOPT = {0};\n end\nelseif ~ypadarray && ~isnumeric(PADOPT{1})\n PADOPT = {0};\nend\nif nargin<7 || isempty(WNAN)\n WNAN = 0;\nend\n\n% Selects the 1-dimensional filter or set a row vector: \nif N==1\n a = zeros(1,DIM);\n a(DIM) = F;\n F = a;\n clear a\nend\n\n% Checks if the window input is a function or an array:\nif ~isa(HWIN,'function_handle') && ~ischar(HWIN)\n W = HWIN;\nelse\n W = [];\nend\n\n% If no input data but two outputs then generates the window only:\nif isempty(X)\n Y = [];\n if nargout==2 && ~isempty(W)\n W = ndwind(HWIN,F,WINOPT{:});\n end\n return\nend\n\n% Generates the window:\nif isempty(W)\n W = ndwind(HWIN,F,WINOPT{:});\nend\n\n% Check for NaN's:\ninan = isnan(X);\nynan = any(inan(:)); % Bug fixed 30/jun/2008\nif ynan\n X(inan) = 0;\nelse\n factor = sum(W(:));\nend\n\n% Filtering:\nif yimfilter % Use IMFILTER (faster)\n if ~isa(X,'double')\n X = double(X);\n end\n if ~isa(W,'double')\n W = double(W);\n end\n if ynan\n Y = imfilter(X,W ,PADOPT{:},'conv');\n else\n Y = imfilter(X,W/double(factor),PADOPT{:},'conv');\n end\nelse % Use CONVN\n % Sets F and S of equal sizes.\n F = reshape(F,1,N);\n Nx = numel(S);\n if NNx\n S(Nx+1:N) = 1;\n end\n F2 = 2*F;\n % Pads the borders:\n if ypadarray\n ind = padarray(false(S),F2,true ); % Index of the padding.\n Y = padarray(X ,F2,PADOPT{:},'both');\n elseif length(PADOPT{1})==1\n ind2 = cell(N,1);\n for n = 1:N\n ind2{n} = F2(n) + (1:S(n)).';\n end\n ind = true(2*F2+S);\n Y = repmat(PADOPT{1},2*F2+S);\n ind(ind2{:}) = false;\n Y(ind2{:}) = X;\n else % No padding at all\n Y = X;\n ind = false(S); \n warning('Ndnanfilter:PaddingOption','Do not perfom any padding.')\n end\n % Convolutes both arrays:\n if ynan\n Y = convn(Y,W ,'same');\n else\n Y = convn(Y,W/factor,'same');\n end\n % Eliminates the padding:\n Y(ind) = [];\n Y = reshape(Y,S); \nend\n\n% Estimates the averages when NaNs are present:\nif ynan\n if yimfilter\n factor = imfilter(double(~inan),W,PADOPT{:},'conv');\n else\n if ypadarray\n factor = padarray(~inan,F2,PADOPT{:});\n elseif length(PADOPT{1})==1 % (won't work properly with NaNs at borders)\n factor = ind;\n factor(ind2{:}) = ~inan;\n else\n factor = ~inan;\n end\n factor = convn(factor,W,'same');\n factor(ind) = [];\n factor = reshape(factor,S);\n end\n Y = Y./factor;\nend\n\n% What about NaNs?:\nif WNAN == 1 % Leave NaNs elements untouched!\n Y(inan) = NaN;\nelseif WNAN == 2 % Leave no-NaNs elements untouched!!!\n X(inan) = Y(inan);\n Y = X;\nend \nend\n\nfunction W = ndwind(HWIN,F,varargin)\n% NDWIND Generate a N-Dimensional zero-phase window.\n%\n% Syntax:\n% W = ndwind(HWIN,F);\n% W = ndwind(HWIN,F,OPT);\n%\n% Input:\n% HWIN - Window function handle. See WINDOW for details. By default\n% uses: @rectwin (a rectangular window).\n% F - A vector specifying the semiwidth of the window for each\n% dimension. The window's width will be 2*F+1. By default uses:\n% 3 (i.e. a window of width 6). \n% OPT - Cell array specifying optional arguments for the window\n% function. By default uses: {[]} (window's defaults).\n%\n% Output:\n% W - N-Dimensional window with central symmetry.\n%\n% Description:\n% In the axes of each dimension, W has a 1-D window defined as\n% feval(HWIN,2*F(n)+1), n = 1,...,N.\n% That is, they are defined by the same window function but have\n% different widths. So, this program creates another widther window (at\n% least 201 points), with the same definition, and finds how much the\n% former windows should be expanded in order to fit the latter one. \n%\n% Afterwards, the coordinates of every point are expanded accordingly\n% and the value of the window in those points are found by linear\n% interpolation with the bigger window. \n%\n% In resume, it is like rotating this big window through every\n% dimension and then shrinking it through each of its axes to fix the\n% specified widths.\n%\n% Notes: \n% * Because of the use of the semi-widths F's, all the generated\n% windows are even. Therefore the change of phase is null. \n% * The window function HWIN should output an even function, otherwise,\n% it won't generate an error but this program will consider only the\n% last half of it.\n% * The window should be monotonically decreasing.\n% * Instead of the handle window, it can be given as a string:\n% 'hamming' instead of @hamming, for example.\n% * Uses the MATLAB's function FUNC2STR.\n%\n% Example:\n% W = ndwind(@hamming,[3 2])\n% % Results:\n% W =\n% \n% 0 0 0.0800 0 0\n% 0 0.1417 0.3100 0.1417 0\n% 0 0.3966 0.7700 0.3966 0\n% 0.0800 0.5400 1.0000 0.5400 0.0800\n% 0 0.3966 0.7700 0.3966 0\n% 0 0.1417 0.3100 0.1417 0\n% 0 0 0.0800 0 0\n%\n%\n% See also: WINDOW from the Signal Processing Toolbox; and FWIND1,\n% FWIND2, and FSPECIAL from the Image Processing Toolbox.\n\n% Copyright 2008 Carlos Adrian Vargas Aguilera\n% $Revision: 1.1 $ $Date: 2008/06/26 19:30:00 $\n\n% Written by\n% M.S. Carlos Adrian Vargas Aguilera\n% Physical Oceanography PhD candidate\n% CICESE \n% Mexico, 2008\n% nubeobscura@hotmail.com\n%\n% Download from:\n% http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objec\n% tType=author&objectId=1093874\n\n% 1.0 Release (2008/06/23 10:30:00)\n% 1.1 Fixed Bug adding an extra dimension of unitary width. \n\n% Check inputs:\nif nargin<1 || isempty(HWIN)\n HWIN = 'rectwin';\nend\nif nargin<2 || isempty(F)\n F = 3;\nend\n\n% Rectangular wind?:\nif isa(HWIN,'function_handle')\n HWIN = func2str(HWIN);\nend\nif strcmpi(HWIN,'rectwin')\n W = ones([2*F(:).'+1 1]);\n return\nend\n\n% Generate the BIG window (only the last half):\nFBIG = max([100; F(:)]);\nBIGw = feval(HWIN,2*FBIG+1,varargin{:});\nBIGw(1:FBIG) = []; % Deletes the first half.\nrBIGw = 0:FBIG; % Window argument (distance).\n\n% Axial windows widths:\nN = numel(F);\nF = reshape(F,1,N); \nF = [F 0]; % BUG fixed by adding an extra dimension.\nN = N+1;\nF2 = 2*F+1;\n\n\n% Pre-allocates the final window and the expanded axis:\nW = zeros(F2);\nAn = cell(N,1);\nAe = An;\n\n% Generates the index and expanded axes:\nfor n = 1:N\n \n % Generate temporally the window in the n-axis:\n wn = feval(HWIN,F2(n),varargin{:});\n \n % Finds the expansion factors (Note: the window should tends to zero):\n if F(n)\n piv = wn(end);\n ind = (BIGw == piv);\n if ~any(ind)\n ind1 = (BIGw >= piv); ind1 = length(ind1(ind1));\n ind2 = (BIGw <= piv); ind2 = length(ind2(~ind2))+1;\n if ind2>FBIG+1\n r = rBIGw(ind1);\n else\n r = interp1(BIGw([ind1 ind2]), rBIGw([ind1 ind2]),piv);\n end\n else\n r = rBIGw(ind);\n end\n Ef = r/F(n);\n else\n Ef = 1;\n end\n \n % Reversed index and expanded n-axis (for the following grid):\n An{n} = (F(n):-1:0);\n Ae{n} = An{n}*Ef;\n \nend\n\n% Estimates the expanded distances outside the axes (only at the 1st\n% quarter):\n% Note: In a 2-Dimensional matrix, by the 1st quarter of a matrix I mean\n% the first 1/4 piece of the matrix after you divided it throuh the middle\n% row and column. In N-dimensions it would be the 1st 1/2^N part.\ngride4 = cell(N,1);\n[gride4{:}] = ndgrid(Ae{:});\nR4 = sqrt(sum(reshape([gride4{:}],prod(F+1),N).^2,2));\n\n% Generates the window and linear index in the 1st quarter:\ngrid4 = cell(N,1);\n[grid4{:}]= ndgrid(An{:});\nin = (R4<=rBIGw(end)); % Looks for elements inside window.\nW4 = zeros(F+1); % 1st quarter of the window.\nW4(in) = interp1(rBIGw,BIGw,R4(in)); % Interpolates the window values.\nfor n=1:N % Linear index on the 1st quarter.\n grid4{n} = flip(grid4{n}+1,n);\nend\nind4 = sub2ind(F2,grid4{:});\n\n% Index of permutations to fill the N-D window:\nnp = 2^N-1;\nip = zeros(1,np);\nfor n = 1:N\n ini = 2^(n-1);\n step = ini*2;\n ip(ini:step:np) = n;\nend\n\n% Fills the N-D window by flipping W4 and the index: \nones4 = false(F2); % Avoids using new FALSE function\nones4(ind4) = true;\nW(ones4) = W4;\nfor kp = ip\n W4 = flip(W4,kp);\n ones4 = flip(ones4,kp);\n W(ones4) = W4;\nend\nend\n\nfunction h = gaussian2D(siz, std)\n\n % create the grid of (x,y) values\n siz = (siz-1)./2;\n [x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));\n\n \n std = max(std);\n sr = siz(2)/siz(1);\n if sr > 1\n sy = sr^2; sx = 1;\n else\n sx = sr^2; sy = 1;\n end\n \n % analytic function\n h = exp(-(sx*x.*x + sy*y.*y)/(2*std*std));\n\n % truncate very small values to zero\n h(h 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...\n\t\tlength(x1) ~= length(y1)\n\terror('X1 and Y1 must be equal-length vectors of at least 2 points.')\nend\n% x2 and y2 must be vectors with same number of points (at least 2).\nif sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...\n\t\tlength(x2) ~= length(y2)\n\terror('X2 and Y2 must be equal-length vectors of at least 2 points.')\nend\n\n\n% Force all inputs to be column vectors.\nx1 = x1(:);\ny1 = y1(:);\nx2 = x2(:);\ny2 = y2(:);\n\n% Compute number of line segments in each curve and some differences we'll\n% need later.\nn1 = length(x1) - 1;\nn2 = length(x2) - 1;\nxy1 = [x1 y1];\nxy2 = [x2 y2];\ndxy1 = diff(xy1);\ndxy2 = diff(xy2);\n\n% Determine the combinations of i and j where the rectangle enclosing the\n% i'th line segment of curve 1 overlaps with the rectangle enclosing the\n% j'th line segment of curve 2.\n[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...\n\trepmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...\n\trepmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...\n\trepmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...\n\trepmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...\n\trepmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...\n\trepmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...\n\trepmat(min(y2(1:end-1),y2(2:end)).',n1,1));\n\n% Force i and j to be column vectors, even when their length is zero, i.e.,\n% we want them to be 0-by-1 instead of 0-by-0.\ni = reshape(i,[],1);\nj = reshape(j,[],1);\n\n% Find segments pairs which have at least one vertex = NaN and remove them.\n% This line is a fast way of finding such segment pairs. We take\n% advantage of the fact that NaNs propagate through calculations, in\n% particular subtraction (in the calculation of dxy1 and dxy2, which we\n% need anyway) and addition.\n% At the same time we can remove redundant combinations of i and j in the\n% case of finding intersections of a line with itself.\nif self_intersect\n\tremove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;\nelse\n\tremove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));\nend\ni(remove) = [];\nj(remove) = [];\n\n% Initialize matrices. We'll put the T's and B's in matrices and use them\n% one column at a time. AA is a 3-D extension of A where we'll use one\n% plane at a time.\nn = length(i);\nT = zeros(4,n);\nAA = zeros(4,4,n);\nAA([1 2],3,:) = -1;\nAA([3 4],4,:) = -1;\nAA([1 3],1,:) = dxy1(i,:).';\nAA([2 4],2,:) = dxy2(j,:).';\nB = -[x1(i) x2(j) y1(i) y2(j)].';\n\n% Loop through possibilities. Trap singularity warning and then use\n% lastwarn to see if that plane of AA is near singular. Process any such\n% segment pairs to determine if they are colinear (overlap) or merely\n% parallel. That test consists of checking to see if one of the endpoints\n% of the curve 2 segment lies on the curve 1 segment. This is done by\n% checking the cross product\n%\n% (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).\n%\n% If this is close to zero then the segments overlap.\n\n% If the robust option is false then we assume no two segment pairs are\n% parallel and just go ahead and do the computation. If A is ever singular\n% a warning will appear. This is faster and obviously you should use it\n% only when you know you will never have overlapping or parallel segment\n% pairs.\n\nif robust\n\toverlap = false(n,1);\n\twarning_state = warning('off','MATLAB:singularMatrix');\n\t% Use try-catch to guarantee original warning state is restored.\n\ttry\n\t\tlastwarn('')\n\t\tfor k = 1:n\n\t\t\tT(:,k) = AA(:,:,k)\\B(:,k);\n\t\t\t[unused,last_warn] = lastwarn;\n\t\t\tlastwarn('')\n\t\t\tif strcmp(last_warn,'MATLAB:singularMatrix')\n\t\t\t\t% Force in_range(k) to be false.\n\t\t\t\tT(1,k) = NaN;\n\t\t\t\t% Determine if these segments overlap or are just parallel.\n\t\t\t\toverlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;\n\t\t\tend\n\t\tend\n\t\twarning(warning_state)\n\tcatch err\n\t\twarning(warning_state)\n\t\trethrow(err)\n\tend\n\t% Find where t1 and t2 are between 0 and 1 and return the corresponding\n\t% x0 and y0 values.\n\tin_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1).';\n\t% For overlapping segment pairs the algorithm will return an\n\t% intersection point that is at the center of the overlapping region.\n\tif any(overlap)\n\t\tia = i(overlap);\n\t\tja = j(overlap);\n\t\t% set x0 and y0 to middle of overlapping region.\n\t\tT(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...\n\t\t\tmin(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;\n\t\tT(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...\n\t\t\tmin(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;\n\t\tselected = in_range | overlap;\n\telse\n\t\tselected = in_range;\n\tend\n\txy0 = T(3:4,selected).';\n\t\n\t% Remove duplicate intersection points.\n\t[xy0,index] = unique(xy0,'rows');\n\tx0 = xy0(:,1);\n\ty0 = xy0(:,2);\n\t\n\t% Compute how far along each line segment the intersections are.\n\tif nargout > 2\n\t\tsel_index = find(selected);\n\t\tsel = sel_index(index);\n\t\tiout = i(sel) + T(1,sel).';\n\t\tjout = j(sel) + T(2,sel).';\n\tend\nelse % non-robust option\n\tfor k = 1:n\n\t\t[L,U] = lu(AA(:,:,k));\n\t\tT(:,k) = U\\(L\\B(:,k));\n\tend\n\t\n\t% Find where t1 and t2 are between 0 and 1 and return the corresponding\n\t% x0 and y0 values.\n\tin_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1).';\n\tx0 = T(3,in_range).';\n\ty0 = T(4,in_range).';\n\t\n\t% Compute how far along each line segment the intersections are.\n\tif nargout > 2\n\t\tiout = i(in_range) + T(1,in_range).';\n\t\tjout = j(in_range) + T(2,in_range).';\n\tend\nend\n\n% Plot the results (useful for debugging).\n% plot(x1,y1,x2,y2,x0,y0,'ok');\n", "meta": {"author": "peiyunh", "repo": "tiny", "sha": "37c44deacf53e0fbe23327ef3721b5fb5f22559f", "save_path": "github-repos/MATLAB/peiyunh-tiny", "path": "github-repos/MATLAB/peiyunh-tiny/tiny-37c44deacf53e0fbe23327ef3721b5fb5f22559f/toolbox/intersections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7640721257979503}} {"text": "function res = hbg(im,thresh)\n\n% inputs\n% im is the fourier transform of the image\n% thresh is the cutoff circle radius\n\n%outputs\n% res is the boosted image\n\n\n[r,c]=size(im);\nd0=thresh;\nd=zeros(r,c);\nh=zeros(r,c);\n\nfor i=1:r\n for j=1:c\n d(i,j)= sqrt( (i-(r/2))^2 + (j-(c/2))^2);\n end\nend\n\nA=1.75; % boost factor or coefficient\n\nfor i=1:r\n for j=1:c\n \n h(i,j)= 1-exp ( -( (d(i,j)^2)/(2*(d0^2)) ) );\n h(i,j)=(A-1)+h(i,j);\n end\n \nend\n\n\nfor i=1:r\n for j=1:c\n res(i,j)=(h(i,j))*im(i,j);\n end\nend\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40579-frequency-domain-filtering-for-grayscale-images/freqfilters/hbg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7640446801301888}} {"text": " function [proj, J, alpha, kb_m, d] = kaiser_bessel_xray(r, J, alpha, kb_m, d)\n%function [proj, J, alpha, kb_m, d] = kaiser_bessel_xray(r, J, alpha, kb_m, d)\n%\n% X-ray transform of generalized Kaiser-Bessel function,\n% See (A7) in lewitt:90:mdi, JOSA-A, Oct. 1990.\n%\n% in\n%\tr\t[?]\tradial locations in projection space (unitless)\n%\n% options\n%\tJ\t\tdiameter of blob (a = J/2), default 4\n%\talpha\t\tshape parameter, default 10.83\n%\tkb_m\t\torder parameter, default 2\n%\td\t\tdimension, default 2\n%\n% out\n%\tproj\t[?]\tx-ray transform values\n%\n% Copyright 2005-7-29, Jeff Fessler, The University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(r, 'test'), kaiser_bessel_xray_test, return, end\n\nif ~isvar('J'), J = 4; end\nif ~isvar('alpha') || isempty('alpha'), alpha = 10.83; end\nif ~isvar('kb_m') || isempty('kb_m'), kb_m = 2; end\nif ~isvar('d'), d = 2; end\ntol = 1e-4;\n\n%\n% trick to yield inline functions\n%\nif ischar(r)\n\tkernel = sprintf('kaiser_bessel_xray(r, %d, %g, %g, %g)', ...\n\t\tJ, alpha, kb_m, d);\n\n\tif streq(r, 'string')\n\t\tproj = kernel;\n\telseif streq(r, 'inline')\n\t\tproj = inline(kernel, 'r');\n\telse\n\t\terror 'bad argument'\n\tend\nreturn\nend\n\n\n%\n% Check for validity of FT formula\n%\npersistent warned\nif (kb_m < 0 || (abs(round(kb_m)-kb_m) > eps))\n\tif isempty(warned)\n\t\tprintf([mfilename: 'kb_m=%g in kaiser_bessel_xray()'], kb_m)\n\t\tprintf('validity of formula uncertain')\n\t\twarned = 1;\n\tend\nend\n\na = J/2;\nfactor = a / besseli(kb_m, alpha) * sqrt(2*pi/alpha);\nroot = sqrt(1 - (r/a).^2);\nnu = kb_m + 1/2;\nproj = factor * root.^nu .* besseli(nu, alpha * root);\nproj = reale(proj, tol);\n\n\n%\n% test\n%\nfunction kaiser_bessel_xray_test\nx = linspace(-2.5,2.5,501)';\ny = x;\n[xx yy] = ndgrid(x, y);\nr = sqrt(xx.^2 + yy.^2);\n[proj J kb_m alpha] = kaiser_bessel_xray(x);\ndx = x(2) - x(1);\n\nf0 = kaiser_bessel(r, J, kb_m, alpha);\npsum = sum(f0,2) * dx;\n\nif im\n\tclf\n\tim(221, x, y, f0, 'blob'), grid\n\tsubplot(222)\n\tplot(x, f0(:,y==0)), title 'profile', axis tight\n\txtick([-2:1.0:2]), grid\n\tsubplot(212)\n\tplot(x, proj, '-', x, psum, '--'), axis tight, title 'projection'\n\tlegend('Analytical', 'Numerical')\nend\nmax_percent_diff(proj, psum, mfilename)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/kaiser_bessel_xray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7640337078532938}} {"text": "function pdf = reciprocal_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% RECIPROCAL_PDF evaluates the Reciprocal PDF.\n%\n% Formula:\n%\n% PDF(X)(A,B) = 1.0D+00 / ( X * LOG ( B / A ) )\n% for 0.0D+00 <= X\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < A <= B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x <= 0.0 )\n pdf = 0.0;\n elseif ( 0.0 < x )\n pdf = 1.0 / ( x * log ( b / a ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/reciprocal_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7640248512758855}} {"text": "function [bmproc] = brownian(npoints, sigma)\n% BROWNIAN generate and plot an aproximation to Brownian motion.\n% Generates a random walk with normally distributed jumps\n%\n% [bmproc] = brownian(npoints [, sigma])\n%\n% Inputs: npoints - length of the trajectory \n% sigma - optional, the norming constant (standard\n% deviation of B(1)). Default 1.\n%\n% Outputs: bmproc - trajectory of the process\n\n% Authors: R.Gaigalas, I.Kaj\n% v1.2 04-Oct-02\n\n % set default parameter values\n if (nargin==1)\n sigma = 1;\n end\n\n % generate a sample from a Gaussian distribution and sum up\n bmproc = [0 cumsum(sigma.*randn(1, npoints-1))]; \n\n % plot the process\n plot([0:npoints-1], bmproc);\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/2493-simulation-of-stochastic-processes/stproc/brownian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7640248359131906}} {"text": "function g = p27_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P27_G evaluates the gradient for problem 27.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n r = sqrt ( x(1)^2 + x(2)^2 );\n\n if ( r == 0.0 )\n g(1) = 0.0;\n g(2) = 0.0;\n return\n end\n\n rx1 = x(1) / r;\n rx2 = x(2) / r;\n\n a = ( 1.0 + 0.001 * r^2 )^( -2 );\n ar = - 0.004 * r * ( 1.0 + 0.001 * r^2 )^( -3 );\n\n b = ( sin ( r ) )^2 - 0.5;\n br = sin ( 2.0 * r );\n\n g(1) = ( ar * b + a * br ) * rx1;\n g(2) = ( ar * b + a * br ) * rx2;\n\n return\nend\n", "meta": {"author": "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/p27_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7639989478887589}} {"text": "function x = MW2cv(P,N)\n%MW1CV critical Mann-Whitney's U associated to a p-value. \n%It obtain a Mann-Whitney's U of two random variables with continuous cumulative\n%distribution associated to a p-value. This procedure is highly recommended for sample sizes\n%7< nx & ny <=40. For nx & ny <=7 it is recommended to use the MW1cv function;\n%otherwise, U-value may be a poor approximation.\n%It works with a procedure to get the nearest cumulative distribution relative value to P.\n%[Based on the Fortran77 algorithm AS 62 Appl. Statist. (1973)]\n%\n% Syntax: function x = MW2cv(P,N) \n% \n% Inputs:\n% P - cumulative probability value of interest.\n% N - 2-element vector of sample sizes for the two samples []. \n% The input quantities should be scalars.\n% Outputs:\n% x - Mann-Whitney's U statistic.\n%\n% Example: For two independent samples we are interested to get the\n% Mann-Whitney's statistic U with an associated cumulative\n% probability P = 0.95. Sample sizes are n1 = 36 and n2 = 14.\n%\n% P = 0.95; N = [36,14];\n%\n% Calling on Matlab the function: \n% x = MW2cv(P,N)\n%\n% Answer is:\n%\n% 328 \n%\n\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n%\n% May 23, 2003.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A. and R. Hernandez-Walls. (2003). MW2cv: Critical Mann-Whitney's U \n% associated to a p-value: nx or ny >7. A MATLAB file. [WWW document]. URL http://\n% www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3555&objectType=FILE\n%\n% References:\n% \n% Mann, H. B. and Whitney, D. R. (1947), On a test of whether one of two \n% random variables is stochastically larger than the other. Annals\n% of Mathematical Statistics, 18: 50-60.\n% Algorithm AS 62 (1973). Journal of Applied Statistics, 22(2):1-3.\n%\n\nif nargin < 2,\n error('Requires two input arguments.');\nend\n\nnmin = min(N); %largest sample size.\nnmax = max(N); %smallest sample size.\n\nif (nmin <= 7) & (nmax <= 7);\n fprintf('Warning: For nx and ny <= 7, the p-value may be a poor approximation.\\n'); \n fprintf('It is recommended to use the MW1cv function you can find on the\\n');\n fprintf('Matlab>File Exchange Antonio Trujillo-Ortiz'' Author Page.\\n');\n disp(' ');\n cont=input('Do you want to continue anyway (y/n):','s');\n \n if (cont=='y');\n disp('Here it goes.');\n \n mn1 = prod(N)+1;\n n1 = nmax+1;\n freq = [ones(n1,1); zeros(mn1-n1,1)];\n \n lwrk = floor((mn1+1)/2 + nmin);\n work = zeros(lwrk,1);\n \n% Generate successively higher-order distributions\n in = nmax;\n for i = 2:nmin\n in = in+nmax;\n n1 = in+2;\n l = 1 + in/2;\n k = i;\n \n% Generate complete distribution from outside inwards\n for j = 1:l\n k = k+1;\n n1 = n1-1;\n summ = freq(j) + work(j);\n freq(j) = summ;\n work(k) = summ - freq(n1);\n freq(n1) = summ;\n end;\n end;\n \n freq = freq/sum(freq); % Make distribution relative\n \n% Cumulative frequency distribution\n cumfreq = cumsum(freq);\n \n%Location of the interested Mann-Whitney's U on all the possible U's for this 2-sample sizes.\n%Here we are using a procedure to get the nearest fc value to P.\n cumfreq=cumfreq-P;\n u = find(abs(cumfreq)==min(abs(cumfreq(:))));\n \n UU = [0:length(freq)-1]; %vector of all the possible Mann-Whitney's U values.\n \n%Association of the interested Mann-Whitney's U with its cumulative distribution.\n x = UU(u);\n else\n end\nelse\n \n mn1 = prod(N)+1;\n n1 = nmax+1;\n freq = [ones(n1,1); zeros(mn1-n1,1)];\n \n lwrk = floor((mn1+1)/2 + nmin);\n work = zeros(lwrk,1);\n \n%Generate successively higher-order distributions\n in = nmax;\n for i = 2:nmin\n in = in+nmax;\n n1 = in+2;\n l = 1 + in/2;\n k = i;\n \n%Generate complete distribution from outside inwards\n for j = 1:l\n k = k+1;\n n1 = n1-1;\n summ = freq(j) + work(j);\n freq(j) = summ;\n work(k) = summ - freq(n1);\n freq(n1) = summ;\n end;\n end;\n \n freq = freq/sum(freq); % Make distribution relative\n \n% Cumulative frequency distribution\n cumfreq = cumsum(freq);\n \n%Location of the interested Mann-Whitney's U on all the possible U's for this 2-sample sizes.\n%Here we are using a procedure to get the nearest fc value to P.\n cumfreq=cumfreq-P;\n u = find(abs(cumfreq)==min(abs(cumfreq(:))));\n \n UU = [0:length(freq)-1]; %vector of all the possible Mann-Whitney's U values.\n \n%Association of the interested Mann-Whitney's U with its cumulative distribution.\n x = UU(u); \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/3555-mw2cv/MW2cv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7639989441887537}} {"text": "function varargout = holdertable(X)\n% Holder table function\n%\n% HOLDERTABLE([x1, x2]) returns the value of the Holder table\n% function at the specified points. [x1] and [x2] may be vectors.\n% The search domain is\n%\n% -10 < x_i < 10\n%\n% The four global minima are near the edges of the interval, and have a\n% function value of \n%\n% f(x*) = -1.92085026. \n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-10, -10]; % LB\n varargout{3} = [+10, +10]; % UB\n varargout{4} = [+8.055023472141116e+000 +9.664590028909654e+000\n -8.055023472141116e+000 +9.664590028909654e+000\n +8.055023472141116e+000 -9.664590028909654e+000\n -8.055023472141116e+000 -9.664590028909654e+000]; % solution\n varargout{5} = -1.920850256788675e+001; % function value at solution\n \n % otherwise, output function value\n else\n \n % keep values within the search interval\n X(X < -10) = inf; X(X > 10) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = -abs(sin(x1).*cos(x2).*exp(abs(1 - sqrt(x1.^2 + x2.^2)/pi)));\n \n end\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23147-many-testfunctions-for-global-optimizers/single-objective/holdertable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7639989432064173}} {"text": "function r = hammersley_sequence ( n )\n\n%*****************************************************************************80\n%\n%% HAMMERSLEY_SEQUENCE computes N elements of a leaped Hammersley subsequence.\n%\n% Discussion:\n%\n% The DIM_NUM-dimensional Hammersley sequence is really DIM_NUM separate\n% sequences, each generated by a particular base. If the base is \n% greater than 1, a standard 1-dimensional\n% van der Corput sequence is generated. But if the base is \n% negative, this is a signal that the much simpler sequence J/(-BASE) \n% is to be generated. For the standard Hammersley sequence, the\n% first spatial coordinate uses a base of (-N), and subsequent\n% coordinates use bases of successive primes (2, 3, 5, 7, 11, ...).\n% This program allows the user to specify any combination of bases,\n% included nonprimes and repeated values.\n%\n% This routine selects elements of a \"leaped\" subsequence of the \n% Hammersley sequence. The subsequence elements are indexed by a\n% quantity called STEP, which starts at 0. The STEP-th subsequence \n% element is simply element \n%\n% SEED(1:DIM_NUM) + STEP * LEAP(1:DIM_NUM) \n%\n% of the original Hammersley sequence.\n%\n%\n% This routine \"hides\" a number of input arguments. To specify these\n% arguments explicitly, use I4_TO_HAMMERSLEY instead.\n%\n% All the arguments have default values. However, if you want to\n% examine or change them, you may call the appropriate routine first.\n%\n% * DIM_NUM, the spatial dimension, \n% Default: DIM_NUM = 1;\n% Required: 1 <= DIM_NUM is required.\n%\n% * STEP, the subsequence index.\n% Default: STEP = 0.\n% Required: 0 <= STEP.\n%\n% * SEED(1:DIM_NUM), the Hammersley sequence element corresponding to STEP = 0.\n% Default SEED = (0, 0, ... 0). \n% Required: 0 <= SEED(1:DIM_NUM).\n%\n% * LEAP(1:DIM_NUM), the succesive jumps in the Hammersley sequence.\n% Default: LEAP = (1, 1, ..., 1). \n% Required: 1 <= LEAP(1:DIM_NUM).\n%\n% * BASE(1:DIM_NUM), the Hammersley bases.\n% Default: BASE = (2, 3, 5, 7, 11, ... ) or (-N,2,3,5,7,11,...) if N is known. \n% Required: 1 < BASE(I) for any van der Corput dimension, or BASE(I) < 0\n% to generate the fractional sequence J/|BASE(I)|.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% J M Hammersley,\n% Monte Carlo methods for solving multivariable problems,\n% Proceedings of the New York Academy of Science,\n% Volume 86, 1960, pages 844-874.\n%\n% Ladislav Kocis and William Whiten,\n% Computational Investigations of Low-Discrepancy Sequences,\n% ACM Transactions on Mathematical Software,\n% Volume 23, Number 2, 1997, pages 266-294.\n%\n% Parameters:\n%\n% Input, integer N, the number of elements to compute.\n%\n% Output, real R(DIM_NUM,N), the SEED-th through SEED+N-1th elements of \n% the Hammersley sequence.\n%\n dim_num = hammersley_dim_num_get ( );\n step = hammersley_step_get ( );\n seed = hammersley_seed_get ( );\n leap = hammersley_leap_get ( );\n base = hammersley_base_get ( );\n\n r = i4_to_hammersley_sequence ( dim_num, n, step, seed, leap, base );\n\n step = step + n;\n\n hammersley_step_set ( step );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hammersley/hammersley_sequence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.763990490285936}} {"text": "function [E, E1, E2, Et, Et1, Et2] = testClassSeperability(N,MEAN1,STD1,MEAN2,STD2, PLOT)\n\n%\n% This function generates two random Gaussian sequences and computes \n% both the theoretical error and the histogram-based method, using\n% respectively the functions computeHistError() and theoreticalError().\n%\n%\n% ARGUMENTS:\n% N: number of samples per class\n% MEAN1: average value of the samples (1st class)\n% STD1: standard deviation of the samples (1st class)\n% MEAN2: average value of the samples (2nd class)\n% STD2: standard deviation of the samples (2nd class)\n% PLOT: this is 1 if results are to be plotted\n%\n% --------------------------------------------\n% Theodoros Giannakopoulos\n% Dep. of Informatics and Telecommunications\n% University of Athens, Greece\n% http://www.di.uoa.gr/~tyiannak\n% --------------------------------------------\n%\n\n\nif (N<100)\n fprintf('N has to be at lest 1000!\\n');\n return;\nend\n\n% GENERATE DATASETS (normal distribution)\nx1 = randn(N,1) * sqrt(STD1) + MEAN1;\nx2 = randn(N,1) * sqrt(STD2) + MEAN2;\n\nif (N<1000)\n nBins = 10;\nelse\n if (N<10000)\n nBins = 50;\n else\n nBins = 100;\n end\nend\n\n% CALCULATE HISTOGRAMS FOR BOTH CLASSES:\nstep = (max(MEAN1,MEAN2) - min(MEAN1,MEAN2)) / nBins;\nX = min(MEAN1-3*STD1,MEAN2-3*STD2): step : max(MEAN1+3*STD1,MEAN2+3*STD2);\n[H1, X1] = hist(x1, X);\n[H2, X2] = hist(x2, X);\n\n% COMPUTE THE ERROR PROBABILITIES FOR BOTH CLASSES using the historam method:\n%\n% N O T E : this function computes the error classification probability for\n% the training data using the histograms as a pdf estimation method.\n% Therefore, it can be used for any distribution of input data.\n%\n\n[E1, E2] = computeHistError(x1, x2);\nE1 = 100* E1;\nE2 = 100* E2;\n\n% OVERALL ERROR PROBABILITY:\nE = (E1 + E2) / 2;\n\nif (PLOT==1)\n figure;\n subplot(2,1,1);\n str = sprintf('Estimated Errors: E1 = %.2f%%, E2 = %.2f%%, E = %.2f%%.', E1, E2, E); \n plot(X1, H1);\n hold on;\n plot(X2, H2,'r');\n legend('Class A','Class B');\n title(str);\n axis([min(MEAN1-3*STD1,MEAN2-3*STD2) max(MEAN1+3*STD1,MEAN2+3*STD2) 0 max([H1 H2])]); \n subplot(2,1,2); \n [Et, Et1, Et2, x] = theoreticalError(MEAN1, STD1, MEAN2, STD2); \n str = sprintf('Theoretical Errors: E1 = %.2f%%, E2 = %.2f%%, E = %.2f%%.', Et1, Et2, Et); \n title(str);\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/18791-histogram-based-class-separability-measure/testClassSeperability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.7639904714721114}} {"text": "% %Question No: 5 (a)\n% Determine the weights of a network with 4 input and 2 output units using \n% Perceptron Learning Law for the following input-output pairs:\n\n% Input: [1100]' [1001]' [0011]' [0110]'\n% output: [11]' [10]' [01]' [00]'\n% Discuss your results for different choices of the learning rate \n% parameters.\n% Use suitable values for the initial weights.\n\nin=[1 1 0 0 -1;1 0 0 1 -1; 0 0 1 1 -1; 0 1 1 0 -1];\nout=[1 1; 1 0; 0 1; 0 0];\neta=input('Enter the learning rate value = ');\nit=input('Enter the number of iterations required = ');\nwgt=input('Enter the weights,2 by 5 matrix(including weight for bias):\\n');\nfor x=1:it\n for i=1:4\n s1=0;\n s2=0;\n for j=1:5\n s1=s1+in(i,j)*wgt(1,j);\n s2=s2+in(i,j)*wgt(2,j);\n end\n wi=eta*(out(i,1)-sign(s1))*in(i,:);\n wgt(1,:)=wgt(1,:)+wi;\n wi=eta*(out(i,2)-sign(s2))*in(i,:);\n wgt(2,:)=wgt(2,:)+wi;\n end\nend\nwgt\n\n", "meta": {"author": "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/perceptron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7639376382319459}} {"text": "function [dist, t] = distancePointEdge3d(point, edge)\n%DISTANCEPOINTEDGE3D Minimum distance between a 3D point and a 3D edge\n%\n% DIST = distancePointEdge3d(POINT, EDGE);\n% Return the euclidean distance between edge EDGE and point POINT. \n% EDGE has the form: [x1 y1 z1 x2 y2 z2], and POINT is [x y z].\n%\n% If EDGE is N-by-6 array, result is N-by-1 array computed for each edge.\n% If POINT is a N-by-3 array, the result is computed for each point.\n% If both POINT and EDGE are array, they must have the same number of\n% rows, and the result is computed for each couple point(i,:);edge(i,:).\n%\n% [DIST POS] = distancePointEdge3d(POINT, EDGE);\n% Also returns the position of closest point on the edge. POS is\n% comprised between 0 (first point) and 1 (last point).\n%\n% See also:\n% edges3d, points3d, distancePoints3d, distancePointLine3d\n% \n\n% ---------\n% author : David Legland \n% INRA - CEPIA URPOI - MIA MathCell\n% created the 07/04/2004.\n%\n\n% HISTORY\n% 2005-06-24 rename, and change arguments sequence\n% 2009-04-30 add possibility to return position of closest point\n% 2011-04-14 add checkup for degenerate edges, improve speed, update doc\n\n% direction vector of each edge\nvl = edge(:, 4:6) - edge(:, 1:3);\n\n% compute position of points projected on the supporting line\n% (Size of t is the max number of edges or points)\nt = linePosition3d(point, [edge(:,1:3) vl]);\n\n% change position to ensure projected point is located on the edge\nt(t < 0) = 0;\nt(t > 1) = 1;\n\n% difference of coordinates between projected point and base point\np0 = bsxfun(@plus, edge(:,1:3), [t .* vl(:,1) t .* vl(:,2) t .* vl(:,3)]);\np0 = bsxfun(@minus, point, p0);\n\n% compute distance between point and its projection on the edge\ndist = sqrt(sum(p0 .* p0, 2));\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/distancePointEdge3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8705972549785201, "lm_q1q2_score": 0.7639288880679971}} {"text": "% Computing an numerical Jordan decomposition\n% X*J*inv(X)\n% of a given matrix A within a distance threshold theta, formulated under\n% a 'three-strikes principle'. For details, see\n% Z. Zeng and T.Y. Li, A numerical algorithm for computing the Jordan\n% Canonical Form, preprint, 2007\n%\n% In a nutshell, let A be a matrix whose entries are given approximately \n% with error magnitude being small. The exact JCF of A will be degraded.\n% However, it is possible to recover the underlying Jordan structure and\n% approximate X and J by NumericalJoranForm\n%\n% Syntax: There are several choices for either LHS or RHS\n% >> LHS = RHS\n% ------------------- | --------------------------------------\n% [J,X] | RegularizedJCF(A)\n% [J,X,e,s,t] | RegularizedJCF(A,theta)\n% | RegularizedJCF(A,theta,tau,gap)\n%\n% Input: A -- matrix whose AJCF is to be computed\n% theta -- (optional) distance threshold\n% tau -- (optional) deflation threshold, simple eigenvalues\n% whose geometric condition numbers above tau will be deflated\n% gap -- (optional) singular value gap used in rank revealing\n%\n% Output: J -- The numerical Jordan Canonical Form\n% X -- The principle vector matrix\n% e -- the list of distinct eigenvalues\n% s -- The Jordan block sizes of the eigenvalues\n% t -- the residuals (backward errors) and the staircase condition\n% numbers of the eigenvalues\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/RegularizedJCF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7638638175041988}} {"text": "function [Afp,Bfp]=freeprecess(T,T1,T2,df)\n%\n%\tFunction simulates free precession and decay\n%\tover a time interval T, given relaxation times T1 and T2\n%\tand off-resonance df. Times in ms, off-resonance in Hz.\n\nphi = 2*pi*df*(T/1000);\t% Off-resonance precession, radians.\n\n% Relaxation exponentials\nE1 = exp(-T/T1);\t\nE2 = exp(-T/T2);\n\n% Decay and phase due to off-resonance\nAfp = [E2 0 0;0 E2 0;0 0 E1]*zrot(phi); % Mathieu, check order of matrix multiplication\n\n% Regrowth\nBfp = [0 0 1-E1]';\n\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/blochSim/freeprecess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7638638166202053}} {"text": "function u=transsplit(u0,a,b,x,y,T,nstep)\n%%\n% Computes an approximation to the solution of \n%\n% $$ u_t+ a u_x + b u_y=0 $$\n%\n% with initial data u0 on the rectangle spanned by the vectors x and y. u0 must be\n% of the size |[length(x),length(y)]|.\n%\n% Output is a 3d matrix of size |[lentgth(x),length(y),((T/dt)+1)]|.\n%\n%% Initial setup\ndt=T/nstep; Nt=ceil(T/dt); dt=T/Nt;\ndx=x(2)-x(1); dy=y(2)-y(1);\nu=zeros(length(x),length(y),Nt+1);\n\n%% Solving by Strang splitting \nu(:,:,1) = u0;\nu1 = transport(b,u(:,:,1),0.5*dt,dx,1); % Transport in the x-direction\nfor i=2:Nt,\n u(:,:,i) = transport(a,u1, dt,dy,2); % Transport in the y-direction\n u1 = transport(b,u(:,:,i),dt,dx,1); % Transport in the x-direction\nend\nu(:,:,Nt+1) = transport(a,u1, dt,dy,2); % Transport in the y-direction\nu(:,:,Nt+1) = transport(b,u(:,:,Nt+1),0.5*dt,dx,1); % Transport in the x-direction\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/OperatorSplitting/Chapter2/Example2_3/transsplit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802362, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7638638123435704}} {"text": "%--------------------------------------------------------------------------\n% W = word(N, theta_tgt, window_N, lamda, position, theta_jam)\n%--------------------------------------------------------------------------\n% 功能:\n% 正交投影加宽零陷抗干扰\n%--------------------------------------------------------------------------\n% 输入:\n% N 阵元数\n% theta_tgt 波束指向 度\n% window_N 指向加窗\n% lambda 波长\n% position 阵列坐标\n% theta_jam 干扰来向\n% 输出:\n% W 加权系数\n%--------------------------------------------------------------------------\n% 例子:\n% N = 64; \n% lambda = 1; %波长\n% dd = lambda/2; %阵元间距d = lambda/2\n% d = 0:dd:(N-1)*dd; %构建阵列坐标\n% W= word( 64, 0,@taylorwin, lambda, d, theta_jam); %生成权系数\n%--------------------------------------------------------------------------\nfunction W = word(N, theta_tgt, window_N, lamda, position, theta_jam)\n%--------------------------------------------------------------------------\n% 指向角的导向矢量\n%--------------------------------------------------------------------------\nAs = window_N(N).* ...\n exp(1j*2*pi*position*sind(theta_tgt)/lamda).'; \n \n%--------------------------------------------------------------------------\n% 生成单位阵\n%--------------------------------------------------------------------------\nIn= eye( N);\nAi = [Ai exp( 1j* 2* pi* position* sind( theta_jam(idx))/ lamda).'];\n\n%--------------------------------------------------------------------------\n% 干扰来向构造矩阵\n%--------------------------------------------------------------------------\nP = In - Ai*( Ai'* Ai)^-1*Ai'; %干扰来向的投影矩阵的 正交子空间\nW_temp=(As'*P)';\nW= W_temp/sqrt( W_temp'* W_temp); %归一化\n", "meta": {"author": "qwe14789cn", "repo": "SP", "sha": "4134ad2e50a446a3d496517720358a808da2f059", "save_path": "github-repos/MATLAB/qwe14789cn-SP", "path": "github-repos/MATLAB/qwe14789cn-SP/SP-4134ad2e50a446a3d496517720358a808da2f059/+sp/word.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7638330268881404}} {"text": "function extended_rosenbrock_test ( )\n\n%*****************************************************************************80\n%\n%% EXTENDED_ROSENBROCK_TEST works with the extended Rosenbrock function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXTENDED_ROSENBROCK_TEST:\\n' );\n fprintf ( 1, ' Test COMPASS_SEARCH with the extended Rosenbrock function.\\n' );\n m = 4;\n delta_tol = 0.00001;\n delta = 0.3;\n k_max = 20000;\n\n x = [ - 1.2, 1.0, -1.5, 1.2 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', extended_rosenbrock ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @extended_rosenbrock, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n%\n% Demonstrate correct minimizer.\n%\n x = [ 1.0, 1.0, 1.0, 1.0 ];\n r8vec_print ( m, x, ' Correct minimizer X*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', extended_rosenbrock ( m, x ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/compass_search/extended_rosenbrock_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.868826771143471, "lm_q1q2_score": 0.7638262418743673}} {"text": "function f = f10_f0 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% F10_F0 returns the value of function 10.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N,1), Y(N,1), the evalution points.\n%\n% Output, real F(N,1), the function values.\n%\n t1(1:n,1) = sqrt ( ( 80.0 * x(1:n,1) - 40.0 ).^2 + ( 90.0 * y(1:n,1) - 45.0 ).^2 );\n t2(1:n,1) = exp ( - 0.04 * t1(1:n,1) );\n t3(1:n,1) = cos ( 0.15 * t1(1:n,1) );\n\n f(1:n,1) = t2(1:n,1) .* t3(1:n,1);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp_2d/f10_f0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7637987010447851}} {"text": "function sc = ssd(I,J,SII,SJJ)\n\n% SSD Sum of Squared Differences coefficient\n% SSD(I,J) computes the SSD score of matrices I and J:\n%\n% SSD = 1/N*sum((I-J).^2)\n% \n% where N = prod(size(I)) \n% and size(I) = size(J)\n%\n% SSD(I,J,SII,SJJ) accepts useful intermediate results\n% that permit to speed up the calculations. These are:\n%\n% SII = sum(sum(I.*I))\n% SJJ = sum(sum(J.*J))\n%\n% See also PATCHCORR, ZNCC, CENSUS\n\n% (c) 2005 Joan Sola\n\nif size(I) ~= size(J)\n error ('Matrices must be the same size.')\nelse\n switch nargin\n case {1,2}\n SII = sum(sum(I.*I));\n SJJ = sum(sum(J.*J));\n case 3\n SJJ = sum(sum(J.*J));\n end\n \n SIJ = sum(sum(I.*J));\n \n N = numel(I);\n \n sc = sqrt((SII+SJJ-2*SIJ)/(N+eps));\n\nend\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/DetectionMatching/ssd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7637021502177246}} {"text": "function p = hexagon_shape_2d ( angle )\n\n%*****************************************************************************80\n%\n%% HEXAGON_SHAPE_2D returns points on the unit regular hexagon in 2D.\n%\n% Diagram:\n%\n% 120_____60\n% / \\\n% 180/ \\0\n% \\ /\n% \\_____/\n% 240 300\n%\n% Discussion:\n%\n% The unit regular hexagon has radius 1. The radius is the distance from\n% the center to any vertex, and it is also the length of any side.\n% An example of a unit hexagon is the convex hull of the points:\n%\n% ( 1, 0 ),\n% ( 0.5, sqrt (3)/2 ),\n% ( - 0.5, sqrt (3)/2 ),\n% ( - 1, 0 ),\n% ( - 0.5, - sqrt (3)/2 ),\n% ( 0.5, - sqrt (3)/2 ).\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 ANGLE, the angle, in degrees, of the point.\n%\n% Output, real P(2,1), the coordinates of the point.\n%\n\n%\n% Ensure that 0 <= ANGLE < 360.\n%\n angle2 = r8_modp ( angle, 360.0 );\n%\n% y = - sqrt(3) * x + sqrt(3)\n%\n if ( 0.0 <= angle2 & angle2 <= 60.0 )\n\n p(1,1) = sqrt ( 3.0 ) / ( tan_deg ( angle2 ) + sqrt ( 3.0 ) );\n p(2,1) = tan_deg ( angle2 ) * p(1,1);\n%\n% y = sqrt(3) / 2\n%\n elseif ( angle2 <= 120.0 )\n\n p(2,1) = sqrt ( 3.0 ) / 2.0;\n p(1,1) = cot_deg ( angle2 ) * p(2,1);\n%\n% y = sqrt(3) * x + sqrt(3)\n%\n elseif ( angle2 <= 180.0 )\n\n p(1,1) = sqrt ( 3.0 ) / ( tan_deg ( angle2 ) - sqrt ( 3.0 ) );\n p(2,1) = tan_deg ( angle2 ) * p(1,1);\n%\n% y = - sqrt(3) * x - sqrt(3)\n%\n elseif ( angle2 <= 240.0 )\n\n p(1,1) = - sqrt ( 3.0 ) / ( tan_deg ( angle2 ) + sqrt ( 3.0 ) );\n p(2,1) = tan_deg ( angle2 ) * p(1,1);\n%\n% y = - sqrt(3) / 2\n%\n elseif ( angle2 <= 300.0 )\n\n p(2,1) = - sqrt ( 3.0 ) / 2.0;\n p(1,1) = cot_deg ( angle2 ) * p(2,1);\n%\n% y = sqrt(3) * x - sqrt(3)\n%\n elseif ( angle2 <= 360.0 )\n\n p(1,1) = - sqrt ( 3.0 ) / ( tan_deg ( angle2 ) - sqrt ( 3.0 ) );\n p(2,1) = tan_deg ( angle2 ) * p(1,1);\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/hexagon_shape_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7636999001575816}} {"text": "function K = gaussian_correlation ( s, t )\n\n%*****************************************************************************80\n%\n%% GAUSSIAN_CORRELATION evaluates the Gaussian 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 = exp ( - ( s - t ).^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/correlation_chebfun/gaussian_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.7636825676489853}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n%ONEVSALL trains multiple logistic regression classifiers and returns all\n%the classifiers in a matrix all_theta, where the i-th row of all_theta \n%corresponds to the classifier for label i\n% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n% logisitc regression classifiers and returns each of these classifiers\n% in a matrix all_theta, where the i-th row of all_theta corresponds \n% to the classifier for label i\n\n% Some useful variables\nm = size(X, 1);\nn = size(X, 2);\n\n% You need to return the following variables correctly \nall_theta = zeros(num_labels, n + 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the following code to train num_labels\n% logistic regression classifiers with regularization\n% parameter lambda. \n%\n% Hint: theta(:) will return a column vector.\n%\n% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n% whether the ground truth is true/false for this class.\n%\n% Note: For this assignment, we recommend using fmincg to optimize the cost\n% function. It is okay to use a for-loop (for c = 1:num_labels) to\n% loop over the different classes.\n%\n% fmincg works similarly to fminunc, but is more efficient when we\n% are dealing with large number of parameters.\n%\n% Example Code for fmincg:\n%\n% % Set Initial theta\n% initial_theta = zeros(n + 1, 1);\n% \n% % Set options for fminunc\n% options = optimset('GradObj', 'on', 'MaxIter', 50);\n% \n% % Run fmincg to obtain the optimal theta\n% % This function will return theta and the cost \n% [theta] = ...\n% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n% initial_theta, options);\n%\n\nfor c = 1:num_labels\n init_theta = zeros(n + 1, 1);\n options = optimset('GradObj', 'on', 'MaxIter', 50);\n [theta] = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), init_theta, options);\n all_theta(c,:) = theta';\nend;\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "rieder91", "repo": "MachineLearning", "sha": "f6708f216326cb5c9e9e5c3afc912060bfa10486", "save_path": "github-repos/MATLAB/rieder91-MachineLearning", "path": "github-repos/MATLAB/rieder91-MachineLearning/MachineLearning-f6708f216326cb5c9e9e5c3afc912060bfa10486/Exercise 3/ex3/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7636825604495858}} {"text": "function b = isPointOnRay(point, ray, varargin)\n%ISPOINTONRAY Test if a point belongs to a ray\n%\n% B = isPointOnRay(PT, RAY);\n% Returns 1 if point PT belongs to the ray RAY.\n% PT is given by [x y] and RAY by [x0 y0 dx dy].\n%\n% If PT is a N-by-2 array, and RAY is a M-by-4 array, then the result is\n% a N-by-M array containing the result of each pair-wise test.\n%\n% B = isPointOnRay(PT, RAY, TOL);\n% Specifies the tolerance to use for testing if point is on the ray.\n%\n% Example\n% ray = [10 20 3 4];\n% % test for a point on the ray\n% p1 = [16 28]; \n% isPointOnRay(p1, ray)\n% ans =\n% logical\n% 0\n% % test for a point on the supporting line but \"before\" the origin\n% p2 = [7 16];\n% isPointOnRay(p1, ray)\n% ans =\n% logical\n% 0\n% \n% See also:\n% rays2d, points2d, isPointOnLine, isPointOnEdge\n%\n\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 31/10/2003.\n%\n\n% HISTORY\n% 07/07/2005 normalize condition to test if on the line and add support\n% of multiple rays or points\n% 22/05/2009 rename to isPointOnRay, add psb to specify tolerance\n% 26/01/2010 was drawing a line before making test\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% number of rays and points\nNr = size(ray, 1);\nNp = size(point, 1);\n\n% if several rays or several points, adapt sizes of arrays\nx0 = repmat(ray(:,1)', Np, 1);\ny0 = repmat(ray(:,2)', Np, 1);\ndx = repmat(ray(:,3)', Np, 1);\ndy = repmat(ray(:,4)', Np, 1);\nxp = repmat(point(:,1), 1, Nr);\nyp = repmat(point(:,2), 1, Nr);\n\n% test if points belongs to the supporting line\nb1 = abs((xp-x0).*dy - (yp-y0).*dx) ./ (dx.*dx + dy.*dy) < tol;\n\n% check if points lie the good direction on the rays\nind = abs(dx) > abs(dy);\nt = zeros(size(b1));\nt(ind) = (xp(ind) - x0(ind)) ./ dx(ind);\nt(~ind) = (yp(~ind) - y0(~ind)) ./ dy(~ind);\n\n% combine the two tests\nb = b1 & (t >= 0);\n", "meta": {"author": "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/isPointOnRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8902942363098472, "lm_q1q2_score": 0.763665999963109}} {"text": "function a = line_adj_eigen_right ( n )\n\n%*****************************************************************************80\n%\n%% LINE_ADJ_EIGEN_RIGHT returns the right eigenvectors of the LINE_ADJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the right eigenvector matrix.\n%\n a = zeros ( n, n );\n\n for i = 1: n\n for j = 1 : n\n angle = ( i * j ) * pi / ( n + 1 );\n a(i,j) = sqrt ( 2.0 / ( n + 1 ) ) * sin ( angle );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/line_adj_eigen_right.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7636659862307319}} {"text": "function dist = distancePoints(p1, p2, varargin)\n%DISTANCEPOINTS Compute distance between two points.\n%\n% D = distancePoints(P1, P2)\n% Return the Euclidean distance between points P1 and P2.\n%\n% If P1 and P2 are two arrays of points, result is a N1-by-N2 array\n% containing distance between each point of P1 and each point of P2. \n%\n% D = distancePoints(P1, P2, NORM)\n% Compute distance using the specified norm. NORM=2 corresponds to usual\n% euclidean distance, NORM=1 corresponds to Manhattan distance, NORM=inf\n% is assumed to correspond to maximum difference in coordinate. Other\n% values (>0) can be specified.\n%\n% D = distancePoints(..., 'diag')\n% compute only distances between P1(i,:) and P2(i,:).\n%\n% See also:\n% points2d, minDistancePoints, nndist, hausdorffDistance\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Copyright 2009 INRA - Cepia Software Platform.\n% created the 24/02/2004.\n%\n\n% HISTORY :\n% 25/05/2004: manage 2 array of points\n% 07/04/2004: add option for computing only diagonal.\n% 30/10/2006: generalize to any dimension, and manage different norms\n% 03/01/2007: bug for arbitrary norm, and update doc\n% 28/08/2007: fix bug for norms 2 and infinite, in diagonal case\n\n\n%% Setup options\n\n% default values\ndiag = false;\nnorm = 2;\n\n% check first argument: norm or diag\nif ~isempty(varargin)\n var = varargin{1};\n if isnumeric(var)\n norm = var;\n elseif strncmp('diag', var, 4)\n diag = true;\n end\n varargin(1) = [];\nend\n\n% check last argument: diag\nif ~isempty(varargin)\n var = varargin{1};\n if strncmp('diag', var, 4)\n diag = true;\n end\nend\n\n\n% number of points in each array and their dimension\nn1 = size(p1, 1);\nn2 = size(p2, 1);\nd = size(p1, 2);\n\nif diag\n % compute distance only for apparied couples of pixels\n dist = zeros(n1, 1);\n \n if norm == 2\n % Compute euclidian distance. this is the default case\n % Compute difference of coordinate for each pair of point\n % and for each dimension. -> dist is a [n1*n2] array.\n for i = 1:d\n dist = dist + (p2(:,i)-p1(:,i)).^2;\n end\n dist = sqrt(dist);\n \n elseif norm == inf\n % infinite norm corresponds to maximal difference of coordinate\n for i = 1:d\n dist = max(dist, abs(p2(:,i)-p1(:,i)));\n end\n \n else\n % compute distance using the specified norm.\n for i = 1:d\n dist = dist + power((abs(p2(:,i)-p1(:,i))), norm);\n end\n dist = power(dist, 1/norm);\n end\nelse\n % compute distance for all couples of pixels\n dist = zeros(n1, n2);\n \n if norm == 2\n % Compute euclidian distance. This is the default case.\n % Compute difference of coordinate for each pair of point\n % and for each dimension. -> dist is a [n1*n2] array.\n for i = 1:d\n % equivalent to:\n % dist = dist + ...\n % (repmat(p1(:,i), [1 n2])-repmat(p2(:,i)', [n1 1])).^2;\n dist = dist + bsxfun (@minus, p1(:,i), p2(:, i)').^2;\n end\n dist = sqrt(dist);\n \n elseif norm == inf\n % infinite norm corresponds to maximal difference of coordinate\n for i = 1:d\n dist = max(dist, abs(bsxfun (@minus, p1(:,i), p2(:, i)')));\n end\n \n else\n % compute distance using the specified norm.\n for i = 1:d\n % equivalent to:\n % dist = dist + power((abs(repmat(p1(:,i), [1 n2]) - ...\n % repmat(p2(:,i)', [n1 1]))), norm);\n dist = dist + power(abs(bsxfun(@minus, p1(:,i), p2(:, i)')), norm);\n end\n dist = power(dist, 1/norm);\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/z_geom3d/geom3d/private/distancePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7636202270129897}} {"text": "function [ err ] = residual_KR_robust( X1, X2, imsize1, imsize2, paras, sigma )\n\n% parameretes sigma indicates the distance scope for inliers with homopraphy matrix, in pixels\n\nk1 = paras(1);\nk2 = paras(2);\ntheta = paras(3:5);\n% yaw = paras(3);\n% pitch = paras(4);\n% roll = paras(5);\n\nK1 = [k1, 0, imsize1(2)/2;\n 0, k1, imsize1(1)/2;\n 0, 0, 1];\nK2 = [k2, 0, imsize2(2)/2;\n 0, k2, imsize2(1)/2;\n 0, 0, 1];\ntheta_m = [0 -theta(3) theta(2)\n theta(3) 0 -theta(1)\n -theta(2) theta(1) 0];\nR = expm(theta_m);\n% Ry = [cos(yaw), 0, -sin(yaw);\n% 0, 1, 0;\n% sin(yaw), 0, cos(yaw)] ;\n% Rp = [1, 0 0;\n% 0, cos(pitch), sin(pitch);\n% 0, -sin(pitch), cos(pitch)] ;\n% Rr = [cos(roll), sin(roll), 0;\n% -sin(roll), cos(roll), 0;\n% 0, 0, 1] ;\n% R = Rr * Rp * Ry;\n\nerr = residual_H(X1, X2, K1, K2, R);\n\noutlier = (abs(err) > sigma);\nerr(outlier) = sign(err(outlier)) .* (sigma + sigma * log(abs(err(outlier))/sigma));\n% err(outlier) = sign(err(outlier)) .* sqrt(2*sigma*abs(err(outlier)) - sigma*sigma);\n\nend\n\n", "meta": {"author": "gain2217", "repo": "Robust_Elastic_Warping", "sha": "36ad3cb2f709fbea17225642ea1fa7b083924fd9", "save_path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping", "path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping/Robust_Elastic_Warping-36ad3cb2f709fbea17225642ea1fa7b083924fd9/two_views/residual_KR_robust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7636192450555477}} {"text": "function [xs,ys] = snakeIterate(alpha,beta,gamma,x,y,NI,Fx,Fy)\n%SNAKEITERATE Iterative solution of the snake equation.\n% [XS,YS] = SNAKEITERATE(ALPHA,BETA,GAMMA,X,Y,NI,Fx,Fy) computes the\n% [XS,YS] coordinates of a segmentation snake using the iterative\n% solution in Eq.(12-7) of DIPUM3E. Vectors X and Y are the initial\n% coordinates of the snake (provided in sequential order). These\n% vectors are updated during iteration. ALPHA, BETA, and GAMMA are\n% parameters in Eq. (12-7) and (12-8), and Fx, Fy are the 2D force\n% arrays obtained, for example, using DIPUM3E function snakeForce.\n%\n% This function is normally run within an outer loop with snake-point\n% respacing after each execution of the loop. NI controls the number\n% of iterations of Eq. (12-7) before the snake points are respaced. A\n% common value of NI is 1, indicating one execution of point respacing\n% after each iteration of Eq. (12-7).\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\n% PRELIMINARIES.\nK = numel(x);\n% Multiply the forces by gamma.\nFx = gamma*Fx;\nFy = gamma*Fy;\n\n% CONSTRUCT MATRIX A IN EQ. (12-8) FOR USE IN EQ. (12-7).\n% First construct matrix D2 in Eq. (12-9).\na = -2*ones(K,1);\nb = 1*ones(K-1,1);\nD2 = diag(a) + diag(b,-1) + diag(b,1);\nD2(1,K) = 1;\nD2(K,1) = 1;\n% Next construct D4 in Eq. (12-10).\na = 6*ones(K,1);\nb = -4*ones(K-1,1);\nc = 1*ones(K-2,1);\nD4 = diag(a) + diag(b,-1) + diag(b,1) + diag(c,-2) + diag(c,2);\nD4(1,K) = -4;\nD4(K,1) = -4;\nD4(1,K-1) = 1;\nD4(K-1,1) = 1;\nD4(2,K) = 1;\nD4(K,2) = 1;\n% Construct matrix A. The inverse operation is performed during\n% iteration.\nD = alpha*D2 - beta*D4;\nA = eye(K) - D;\n\n% ITERATIVE SOLUTION.\nfor I = 1:NI\n\t% Obtain the force vectors fx and fy in Eq. (12-7). These are\n\t% obtained from Fx and Fy, the 2-D array components of the force\n\t% field F, by interpolating values of Fx and Fy at the locations of\n\t% the current snake coordinates, x and y. The 0 in the following\n\t% function call avoids NaNs in areas where there are no points to\n\t% interpolate. The order y,x is because function interp2 works with\n\t% (col,row), as opposed to (row,col) as in the book.\n\tfx = interp2(Fx,y,x,'linear',0);\n\tfy = interp2(Fy,y,x,'linear',0);\n \n\t% Compute new values of x and y using Eq. (12-7). Note the use of x =\n\t% A\\(x + fx), as opposed to x = inv(A)*(x + fx), and similarly for y.\n\t% The former method is faster and more accurate.\n\tx = A\\(x + fx);\n\ty = A\\(y + fy);\nend\n \n% FORM THE SNAKE.\nxs = x;\nys = y;\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/snakeFunctions/snakeIterate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7635638716464569}} {"text": "function v = legendre_van ( m, a, b, n, x )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_VAN returns the LEGENDRE_VAN matrix for [A,B].\n%\n% Discussion:\n%\n% The LEGENDRE_VAN matrix is the Legendre Vandermonde-like matrix.\n%\n% Normally, the Legendre polynomials are defined on -1 <= XI <= +1.\n% Here, we assume the Legendre polynomials have been defined on the\n% interval A <= X <= B, using the mapping\n% XI = ( - ( B - X ) + ( X - A ) ) / ( B - A )\n% so that\n% Lab(A,B;X) = L(XI).\n%\n% if ( I = 1 ) then\n% V(1,1:N) = 1\n% else if ( I = 2 ) then\n% V(2,1:N) = XI(1:N)\n% else\n% V(I,1:N) = ( (2*I-1) * XI(1:N) * V(I-1,1:N) - (I-1)*V(I-2,1:N) ) / I\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of the matrix.\n%\n% Input, real A, B, the limits of the interval.\n%\n% Input, integer N, the number of columns of the matrix.\n%\n% Input, real X(N), the abscissas.\n%\n% Output, real V(M,N), the matrix.\n%\n\n%\n% Force X to be a row vector.\n%\n x = ( x(:) .' );\n%\n% Compute the normalized abscissas in [-1,+1].\n%\n xi(1,1:n) = ( - 1.0 * ( b - x(1,1:n) ) ...\n + 1.0 * ( x(1,1:n) - a ) ) ...\n / ( b - a );\n%\n% Set up the matrix.\n%\n v = zeros ( m, n );\n\n for i = 1 : m\n\n if ( i == 1 )\n v(i,1:n) = 1.0;\n elseif ( i == 2 )\n v(i,1:n) = xi(1,1:n);\n else\n v(i,1:n) = ( ( 2 * i - 1 ) * xi(1,1:n) .* v(i-1,1:n) ...\n + ( - i + 1 ) * v(i-2,1:n) ) ...\n / ( 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/line_fekete_rule/legendre_van.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7635638716464568}} {"text": "function [Fh,Vh]=honeyCombMesh(minV,maxV,pointSpacing)\n\n% function [Fh,Vh]=honeyCombMesh(minV,maxV,pointSpacing)\n% -----------------------------------------------------------------------\n% This function creates the faces (Fh) and vertices (Vh) for a hexagon\n% (honey comb) mesh. The hexagons are created between the limits minV\n% (containing desired minimum X and Y coordinates) and maxV (containing\n% desired maximum X and Y coordinates). The size of the hexagons is set by\n% the desired point spacing. \n%\n% -----------------------------------------------------------------------\n\n%% CREATE TRIANGULATION\n\nmaxV(2)=maxV(2)+pointSpacing; \n[F,V]=triMeshEquilateral(minV,maxV,pointSpacing);\n\n%% GET DUAL FOR HONEY-COMB\n\n[Vh,Fd]=patch_dual(V,F,0);\nnumVert=cellfun(@(x) size(x,2),Fd);\nFh=Fd{numVert==6};\n\n[Fh,Vh]=patchCleanUnused(Fh,Vh);\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/honeyCombMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7635638557965694}} {"text": "function R = wishrand(S,nu);\n%WISHRND Random matrices from Wishard distribution.\n% R = WISHRAND(S,N) returns a matrix of random numbers chosen \n% from the central Wishard distribution with parameters S and NU.\n%\n% S is a symmetric positive definite scale matrix\n% NU is degrees of freedom\n%\n% Note: E[R]=S\n%\n% References: Gelman, Carlin, Stern, Dunson, Vehtari, and Rubin (2013).\n% Bayesian Data Analysis, third edition.\n% Gentle (2003), Random Number Generation and Monte Carlo\n% Methods, 2nd ed, Springer, p. 199, Algorithm 5.8. \n% Smith & Hocking (1972), Algorithm AS 53: Wishard Variate\n% Generator, Applied Statistics, 21(3), pp. 341-345.\n%\n%\tSee also INVWISHRAND\n%\n% Copyright (c) 1999-2004 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 2\n error('Requires two input arguments.'); \nend;\n\n[d d2] = size(S);\nif d ~= d2\n error('Matrix S must be square');\nend\n\n% Algorithm 5.8 step 0.\n[T,p]=chol(S);\nif p > 0\n error('Matrix S must be positive definite.');\nend\n\nif (nu >= d) && (nu == round(nu))\n % distribution is proper and degrees of freedom is integer\n % brute-force may be used, which is surprisingly faster in Matlab\n % at least up to d>10, nu>1000\n % Algorithm described e.g. in (Gelman et al., 2013)\n Y = T'*randn(d,nu);\n R = Y*Y'./nu;\nelse\n % distribution is not proper or degrees of freedom is not integer\n % (Gentle, 2003) Algorithm 5.8\n % Algorithm 5.8 step 1.\n Z=zeros(d);\n for j=2:d\n Z(1:j,j)=randn(j,1);\n end\n % Algorithm 5.8 step 2. Note that there is error in the book.\n % Book says nu-i, while it should be nu+1-i\n % See errata \n % gamrand below is same as chi2rnd(nu-(1:d)+1), but much faster using c-code\n y=gamrand((nu+1-(1:d)),nu+1-(1:d)); \n % Algorithm 5.8 step 3.\n Z2=Z.^2;\n sy=sqrt(y);\n B=zeros(d);\n B(1,1)=y(1);\n % In Matlab 6.5 following loop is accelerated and thus quite fast\n for j=2:d\n B(j,j)=y(j)+sum(Z2(1:(j-1),j));\n B(1,j)=Z(1,j).*sy(1);\n B(j,1)=B(1,j);\n for i=2:(j-1)\n B(i,j)=Z(i,j).*sy(i)+sum(Z(1:(i-1),i).*Z(1:(i-1),j));\n B(j,i)=B(i,j);\n end\n end\n % Algorithm 5.8 step 4.\n R=T'*B*T/nu;\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/wishrand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7634166768231367}} {"text": "function [mu vr] = ricestat(v, s)\n%RICESTAT Mean and variance of Rice/Rician probability distribution.\n% [mu vr] = ricestat(v, s) returns the mean and variance of the Rice \n% distribution with parameters v and s.\n%\n% R ~ Rice(v, s) if R = sqrt(X^2 + Y^2), where X ~ N(v*cos(a), s^2) and\n% Y ~ N(v*sin(a), s^2) are independent normal distributions (any real a).\n% Note that v and s are *not* the mean and standard deviation of R!\n%\n% Reference: http://en.wikipedia.org/wiki/Rice_distribution (!)\n%\n% Example:\n%\n% % Compare expected and sample stats:\n% v = 5; s = 4; N = 1000;\n% r = ricernd(v*ones(1, N), s);\n% mu = mean(r), vr = var(r)\n% [Mu Vr] = ricestat(v, s)\n% % Plot histogram and mark expected mean +/- 1 stdev:\n% c = linspace(0, ceil(max(r)), 20);\n% w = c(2); % histogram bin-width\n% h = histc(r, c); bar(c, h, 'histc'); hold on\n% pk = N*w*ricepdf(Mu, v, s);\n% plot([Mu-sqrt(Vr) Mu+sqrt(Vr)], [pk pk]/2, 'ro-')\n% plot(Mu, pk/2, 'rx')\n%\n% See also RICEPDF, RICERND, RICEFIT\n\n% Missing (?) 'See also's RICECDF, RICEINV, RICELIKE\n\n% Inspired by normstat from the MATLAB statistics toolbox\n% Copyright 2008 Ged Ridgway (Ged at cantab dot net)\n\nL = Lhalf(-0.5 * v^2 / s^2);\nmu = s * sqrt(pi/2) * L;\nvr = 2*s^2 + v^2 - (pi * s^2 / 2) * L^2;\n\n\nfunction l = Lhalf(x)\n% Laguerre polynomial L_{1/2}(x)\n% see Moments section of http://en.wikipedia.org/wiki/Rice_distribution\nl = exp(x/2) * ( (1-x) * besseli(0, -x/2) - x*besseli(1, -x/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/rician/ricestat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7633884770338915}} {"text": "function [sigma,mu,A]=mygaussfit(x,y,h)\n\n%\n% [sigma,mu,A]=mygaussfit(x,y)\n% [sigma,mu,A]=mygaussfit(x,y,h)\n%\n% this function is doing fit to the function\n% y=A * exp( -(x-mu)^2 / (2*sigma^2) )\n%\n% the fitting is been done by a polyfit\n% the lan of the data.\n%\n% h is the threshold which is the fraction\n% from the maximum y height that the data\n% is been taken from.\n% h should be a number between 0-1.\n% if h have not been taken it is set to be 0.2\n% as default.\n%\n\n\n%% threshold\nif nargin==2, h=0.2; end\n\n%% cutting\nymax=max(y);\nxnew=[];\nynew=[];\nfor n=1:length(x)\n if y(n)>ymax*h;\n xnew=[xnew,x(n)];\n ynew=[ynew,y(n)];\n end\nend\n\n%% fitting\nylog=log(ynew);\nxlog=xnew;\np=polyfit(xlog,ylog,2);\nA2=p(1);\nA1=p(2);\nA0=p(3);\nsigma=sqrt(-1/(2*A2));\nmu=A1*sigma^2;\nA=exp(A0+mu^2/(2*sigma^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/11733-gaussian-curve-fit/mygaussfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7633884710729312}} {"text": "function heated_plate ( epsilon, output_filename )\n\n%*****************************************************************************80\n%\n% Purpose:\n%\n% MAIN is the main program for HEATED_PLATE.\n%\n% Discussion:\n%\n% This code solves the steady state heat equation on a rectangular region.\n%\n% The sequential version of this program needs approximately\n% 18/eps iterations to complete. \n%\n%\n% The physical region, and the boundary conditions, are suggested\n% by this diagram;\n%\n% W = 0\n% +------------------+\n% | |\n% W = 100 | | W = 100\n% | |\n% +------------------+\n% W = 100\n%\n% The region is covered with a grid of M by N nodes, and an N by N\n% array W is used to record the temperature. The correspondence between\n% array indices and locations in the region is suggested by giving the\n% indices of the four corners:\n%\n% I = 0\n% [0][0]-------------[0][N-1]\n% | |\n% J = 0 | | J = N-1\n% | |\n% [M-1][0]-----------[M-1][N-1]\n% I = M-1\n%\n% The steady state solution to the discrete heat equation satisfies the\n% following condition at an interior grid point:\n%\n% W[Central] = (1/4) * ( W[North] + W[South] + W[East] + W[West] )\n%\n% where \"Central\" is the index of the grid point, \"North\" is the index\n% of its immediate neighbor to the \"north\", and so on.\n% \n% Given an approximate solution of the steady state heat equation, a\n% \"better\" solution is given by replacing each interior point by the\n% average of its 4 neighbors - in other words, by using the condition\n% as an ASSIGNMENT statement:\n%\n% W[Central] <= (1/4) * ( W[North] + W[South] + W[East] + W[West] )\n%\n% If this process is repeated often enough, the difference between successive \n% estimates of the solution will go to zero.\n%\n% This program carries out such an iteration, using a tolerance specified by\n% the user, and writes the final estimate of the solution to a file that can\n% be used for graphic processing.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 July 2010\n%\n% Author:\n%\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Michael Quinn,\n% Parallel Programming in C with MPI and OpenMP,\n% McGraw-Hill, 2004,\n% ISBN13: 978-0071232654,\n% LC: QA76.73.C15.Q55.\n%\n% Parameters:\n%\n% Commandline argument 1, real EPSILON, the error tolerance. \n%\n% Commandline argument 2, string OUTPUT_FILENAME, the name of the file into which\n% the steady state solution is written when the program has completed.\n%\n% Local parameters:\n%\n% Local, real DIFF, the norm of the change in the solution from \n% one iteration to the next.\n%\n% Local, real MEAN, the average of the boundary values, used \n% to initialize the values of the solution in the interior.\n%\n% Local, real U(M,N), the solution at the previous iteration.\n%\n% Local, real W(M,N), the solution computed at the latest \n% iteration.\n%\n m = 500;\n n = 500;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HEATED_PLATE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' A program to solve for the steady state temperature distribution\\n' );\n fprintf ( 1, ' over a rectangular plate.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial grid of %d by %d points.\\n', m, n );\n%\n% Read EPSILON from the command line or the user.\n%\n if ( nargin < 1 )\n epsilon = input ( ' Enter EPSILON, the error tolerance.' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The iteration will repeat until the change is <= %e\\n', epsilon );\n%\n% Read OUTPUT_FILENAME from the command line or the user.\n%\n if ( nargin < 2 )\n output_filename = input ( ...\n ' Enter OUTPUT_FILENAME, the name of the output file.' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The steady state solution will be written to \"%s\".\\n', ...\n output_filename );\n%\n% Set the boundary values, which don't change. \n%\n w(2:m-1,1) = 100.0;\n w(2:m-1,n) = 100.0;\n w(m,1:n) = 100.0;\n w(1,1:n) = 0.0;\n%\n% Average the boundary values, to come up with a reasonable\n% initial value for the interior.\n%\n mean = ( ...\n sum ( w(2:m-1,1) ) ...\n + sum ( w(2:m-1,n) ) ...\n + sum ( w(m,1:n) ) ...\n + sum ( w(1,1:n) ) ) ...\n / ( 2 * m + 2 * n - 4 );\n%\n% Initialize the interior solution to the mean value.\n%\n w(2:m-1,2:n-1) = mean;\n%\n% iterate until the new solution W differs from the old solution U\n% by no more than EPSILON.\n%\n iterations = 0;\n iterations_print = 1;\n diff = epsilon;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Iteration Change\\n' );\n fprintf ( 1, '\\n' );\n\n tic;\n\n while ( epsilon <= diff )\n\n u(1:m,1:n) = w(1:m,1:n);\n\n w(2:m-1,2:n-1) = 0.25 * ( ...\n u(1:m-2,2:n-1) ...\n + u(3:m,2:n-1) ...\n + u(2:m-1,1:n-2) ...\n + u(2:m-1,3:n) );\n\n diff = max ( max ( abs ( u(1:m,1:n) - w(1:m,1:n) ) ) );\n\n iterations = iterations + 1;\n\n if ( iterations == iterations_print )\n fprintf ( 1, ' %8d %14f\\n', iterations, diff );\n iterations_print = 2 * iterations_print;\n end\n\n end\n\n wtime = toc;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %8d %14f\\n', iterations, diff );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Error tolerance achieved.\\n' );\n fprintf ( 1, ' Wallclock time = %f\\n', wtime );\n%\n% Write the solution to the output file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n fprintf ( output_unit, '%d\\n', m );\n fprintf ( output_unit, '%d\\n', n );\n for i = 1 : m\n for j = 1 : n\n fprintf (output_unit, ' %f', w(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n\n fclose ( output_unit );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solution written to the output file \"%s\".\\n', output_filename );\n%\n% Terminate.\n%\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HEATED_PLATE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/heated_plate/heated_plate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.763361701128041}} {"text": "function X=solveSylvesterEq(A,B,C)\n%%SOLVESYLVESTEREQ Solve the Sylester equation A*X+X*B=C for X, where A, B,\n% and C can be real or complex. This implementation only works\n% when a unique solution for X exists, which is the case when\n% none of the eigenvalues of A and B when summed together equals\n% 0.\n%\n%INPUTS: A A pXp matrix.\n% B An rXr matrix.\n% C A pXr matrix.\n%\n%OUTPUTS: X The pXr matrix solving A*X+X*B=C.\n%\n%This function implements the Bartels-Stewart algorithm of [1]. The back\n%substitution algorithm of Algorithm 7.6.2 in [2] is used for the second\n%half of the algorithm, which also means that upper-triangular Schur\n%decompositions are used for the first half of the algorithm.\n%\n%EXAMPLE:\n%In this example, we solve a Sylvester equation and show that the result\n%Tolerance is about 7e-14, which is good agreement.\n% A=[3, 0, 0, 23;\n% -2, 5, -14, -6;\n% 11, 11, -7, 7;\n% -10, 15, -10, -1];\n% B=[8, 4, 2, 6;\n% -7, -1, 1, 8;\n% -14, -1, 15, -2;\n% -14, 14, -8, 2];\n% C=[16, 3, 6, 8;\n% 3, 11, 8, 11;\n% 6, 8, 6, 13;\n% 8, 11, 13, 1];\n% X=solveSylvesterEq(A,B,C);\n% AbsTol=max(max(abs(A*X+X*B-C)))\n%\n%REFERENCES\n%[1] R. H. Bartels and G. W. Stewart, \"Algorithm 432: Solution of the\n% matrix equation AX+XB=C [F4],\" Communications of the ACM, pp. 820-826,\n% Sep. 1972.\n%[2] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: The Johns Hopkins Press, 2013.\n%\n%December 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%We use the complex Schur decomposition. If we used the real one, then\n%Ap and Bp are not guaranteed to be upper triangular if the matrices have\n%complex eigenvalues.\n[U,Ap]=schur(A,'complex');\n[V,Bp]=schur(B,'complex'); \nCp=U'*C*V;\n\n%Solve the transformed system using Algorithm 6.7.2 of [1].\nBp=-Bp;\n\nr=size(Ap,1);\np=size(Bp,1);\n\nI=eye(r,r);\n\nfor k=1:r\n Cp(1:p,k)=Cp(1:p,k)+Cp(1:p,1:(k-1))*Bp(1:(k-1),k);\n z=(Ap-Bp(k,k)*I)\\Cp(1:p,k);\n Cp(1:p,k)=z;\nend\n\n%Cp hold the transformed result. Now undo the transformation.\nX=U*Cp*V';\n\nif(isreal(A)&&isreal(B)&&isreal(C))\n %If all of the inputs are real, then Cp should be real, not accounting\n %for finite precision limits.\n X=real(X);\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/solveSylvesterEq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7633616994416386}} {"text": "function w = Lambert_W(x,branch)\n% Lambert_W Functional inverse of x = w*exp(w).\n% w = Lambert_W(x), same as Lambert_W(x,0)\n% w = Lambert_W(x,0) Primary or upper branch, W_0(x)\n% w = Lambert_W(x,-1) Lower branch, W_{-1}(x)\n%\n% See: http://blogs.mathworks.com/cleve/2013/09/02/the-lambert-w-function/\n\n% Copyright 2013 The MathWorks, Inc.\n\n% Effective starting guess\nif nargin < 2 || branch ~= -1\n w = ones(size(x)); % Start above -1\nelse \n w = -2*ones(size(x)); % Start below -1\nend\nv = inf*w;\n\n% Haley's method\nwhile any(abs(w - v)./abs(w) > 1.e-8)\n v = w;\n e = exp(w);\n f = w.*e - x; % Iterate to make this quantity zero\n w = w - f./((e.*(w+1) - (w+2).*f./(2*w+2)));\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43419-the-lambert-w-function/Lambert_W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.763327617195355}} {"text": "function x = Adj_Evaluate_FT(y,shift,boxlen,center,w)\n% Adj_Evaluate_FT -- 1d unequispaced adjoint Fourier transform\n% (with windowing). Adjoint of Evaluate_FT. \n% Usage:\n% x = Evaluate_FT(y,shift,boxlen,center,w)\n% Inputs:\n% y\t vector of length 2n\n% shift vector of shifts\n% boxlen half length of interval around each value of shift\n% center boolean variable: 0/1 = unbiased/biased FT\n% w tapering window of size 2*boxlen\n% Outputs:\n% x vector of length: n\n% Description: \n% For w = 1, evaluates the Adj FT of a signal irregularly\n% sampled in frequency omega(j,k) = shift(j) + k, -boxlen <= k\n% 1\n if nargout > 2\n sig = 1./(1+exp(-yXw));\n g = -X.'*(y.*(1-sig));\n else\n g = -X.'*(y./(1+exp(yXw)));\n end\nend\n\nif nargout > 2\n H = X.'*diag(sparse(sig.*(1-sig)))*X;\nend\n\nif nargout > 3\n T = zeros(p,p,p);\n for j1 = 1:p\n for j2 = 1:p\n for j3 = 1:p\n T(j1,j2,j3) = sum(y(:).^3.*X(:,j1).*X(:,j2).*X(:,j3).*sig.*(1-sig).*(1-2*sig));\n end\n end\n end\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/tools/minFunc/logistic/LogisticLoss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7632796988766426}} {"text": "% Mathematics Q2791227\n% https://math.stackexchange.com/questions/2301266\n% Proximal Operator of Huber Loss Function (For L1 Regularized Huber Loss)\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 20/03/2020\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 0; % IQR/2;\n\nx2 = log(r);\ny2 = log(n);\n\ns(indx2)= [];\nx2(indx2) = [];\ny2(indx2) = [];\n\n%std is the variance of the slope according to OLS theory\n\nX = [ones(size(x2)) x2];\nbeta = pinv(X)*y2;\nC = pinv(X'*X);\ne=y2-X*pinv(X)*y2;\nsigma = e'*e*C;\nsigma = sqrt(sigma);\n\ndimension = -beta(2);\nstandard_dev = sigma(2,2);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31951-fractal-volatility-of-financial-time-series/fractalvol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7632782872072466}} {"text": "function toms446_test04 ( )\n\n%*****************************************************************************80\n%\n%% TOMS446_TEST04 tests EDCHEB, which evaluates the derivative of a Chebyshev series.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2011\n%\n% Author:\n%\n% John Burkardt\n%\n nf = 5;\n npl = 10;\n\n nx = 6;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TOMS446_TEST04\\n' );\n fprintf ( 1, ' Test EDCHEB, which evaluates the \\n' );\n fprintf ( 1, ' derivative of a Chebyshev series.\\n' );\n\n x = cheby ( nf, npl, @functn );\n\n for j = 1 : nf\n\n x2(1:npl) = x(1:npl,j);\n\n fprintf ( 1, '\\n' );\n if ( j == 1 )\n fprintf ( 1, ' d/dx Sin(x)\\n' );\n elseif ( j == 2 )\n fprintf ( 1, ' d/dx Cos(x)\\n' );\n elseif ( j == 3 )\n fprintf ( 1, ' d/dx Sin(2x)\\n' );\n elseif ( j == 4 )\n fprintf ( 1, ' d/dx Cos(2x)\\n' );\n elseif ( j == 5 )\n fprintf ( 1, ' d/dx x^5\\n' );\n end\n\n fprintf ( 1, '\\n' );\n\n for k = 1 : nx\n\n xval = 2.0 * ( k - 1 ) / ( nx - 1 ) - 1.0;\n\n fxj = functn_d ( xval );\n\n fval = edcheb ( xval, x2, npl );\n\n fprintf ( 1, ' %10.4f %10.4f %10.4f\\n', xval, fxj(j), fval );\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/toms446/toms446_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.763257494636344}} {"text": "function p=v_normcdflog(x,m,s)\n%V_NORMCDFLOG calculates log of Normal Cumulative Distribution function p=(x,m,s)\n%\n% Inputs: \n%\n% X Input data (vector or matrix)\n% M Mean of Normal distribution [default 0]\n% S Std deviation of Normal distribution [default 1]\n%\n% Outputs: \n%\n% P P = log(normcdf(X)); same size as X\n%\n% The routine gives accurate values even if X is large and negative\n\n% Copyright (C) Mike Brookes 2016\n% Version: $Id: v_normcdflog.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\nif isempty(a)\n a=0.996;\n% f=@(x) -0.5*(x.^2+log(2*pi))-real(log(-(a+x.^2)./x))-real(log(normcdf(x)));\n% b=fzero(f,-22); % cutoff value for conventional formula\n b=-22.2491306156561; % precalculated value\nend\nif nargin>2\n x=(x-m)/s;\nelseif nargin>1\n x=x-m;\nend\nt=xj edge pairs (these do not generate triangles). The number of \n% false pairs is the main diagonal of A^2. Thus the maximum possible \n% number of triangles = (2 edges)*([ALL PAIRS] - [FALSE PAIRS])\n% = 2 * (K(K-1)/2 - diag(A^2))\n% = K(K-1) - 2(diag(A^2))\n\nS = A+A.'; % symmetrized input graph\nK = sum(S,2); % total degree (in + out)\ncyc3 = diag(S^3)/2; % number of 3-cycles (ie. directed triangles)\nCYC3 = K.*(K-1)-2*diag(A^2); % number of all possible 3-cycles\nT = sum(cyc3)./sum(CYC3); % transitivity\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/transitivity_bd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7630873650492446}} {"text": " function [fun, d1, d2] = ir_poly2_fun(order, varargin)\n%function [fun, d1, d2] = ir_poly2_fun(order, [options])\n%|\n%| create anonymous functions @(x,y) with all the terms in a 2d polynomial\n%| up to given order, e.g. [1+0*x x y ...]\n%| also return partial derivatives w.r.t. x and y\n%|\n%| in\n%|\torder\n%|\n%| options\n%|\tmaxdegree\tmaximum of sum of degrees (default: 2*order)\n%|\tdc\t\tset to 1 to include dc (constant) term (default: 1)\n%|\n%| out\n%|\tfun\t\tuse fun(x, y) to evaluate the polynomial\n%|\td1,d2\t\tlikewise, for 1st partial derivatives thereof\n%|\n%| Copyright 2005-6-18, Jeff Fessler, The University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(order, 'test'), ir_poly2_fun_test, return, end\n\narg.maxdegree = []; % se below\narg.dc = true;\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.maxdegree), arg.maxdegree = 2 * order; end\n\nstr = '';\nd1 = '';\nd2 = '';\nfor i2=0:order\n\tfor i1=0:order\n\t\tif i1+i2 == 0 && ~arg.dc\n\t\t\tcontinue\n\t\tend\n\t\tif i1 + i2 > arg.maxdegree\n\t\t\tcontinue\n\t\tend\n\n\t\tstr = [str sprintf(' (x.^%d).*(y.^%d)', i1, i2)];\n\t\tif i1 == 0\n\t\t\ts1 = '0*x';\n\t\telse\n\t\t\ts1 = sprintf('%d*x.^%d', i1, i1-1);\n\t\tend\n\t\tif i2 == 0\n\t\t\ts2 = '0*y';\n\t\telse\n\t\t\ts2 = sprintf('%d*y.^%d', i2, i2-1);\n\t\tend\n\t\td1 = [d1 sprintf(' (%s).*(y.^%d)', s1, i2)];\n\t\td2 = [d2 sprintf(' (x.^%d).*(%s)', i1, s2)];\n\tend\nend\nstr = ['[ ' str ' ]'];\nd1 = ['[ ' d1 ' ]'];\nd2 = ['[ ' d2 ' ]'];\n\n% create appropriate anonymous functions\nfun = ir_str2func(['@(x,y) ' str]);\nd1 = ir_str2func(['@(x,y) ' d1]);\nd2 = ir_str2func(['@(x,y) ' d2]);\n\n\n% ir_poly2_fun_test()\nfunction ir_poly2_fun_test\n[fun d1 d2] = ir_poly2_fun(1, 'dc', 0);\nx = 1:5; y = 2:6; fun(x,y); d1(x,y); d2(x,y);\n[fun d1 d2] = ir_poly2_fun(2, 'maxdegree', 3);\nfun(x,y); d1(x,y); d2(x,y);\nif im\n\tpr fun\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/ir_poly2_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.8976952934758465, "lm_q1q2_score": 0.7630151376243318}} {"text": "function [PErrorOutput, PErrorOutputmean, PErrorOutputvar] = PError(N,Ptrue,Pestimate)\n\n% This function computes the proportion erros per pixel per endmember \n% given true and estimated proportion values.\n%\n% SYNTAX : [PErrorOutput, PErrorOutputmean, PErrorOutputvar] = PError(N,Ptrue,Pestimate)\n%\n% INPUTS \n% N: Total number of data points. N=N1*N2 in hyperspectral\n% image data.\n% Ptrue: True proportion values. N*M, where M is the number of\n% endmembers.\n% Pestimate: Estimated proportion values. N*M.\n% OUTPUTS\n% PErrorOutput: PError per pixel\n% PErrorOutputmean: Mean of PErrorOutput, PError per pixel per\n% endmember. (This is the result in the Tables in the paper)\n% PErrorOutputvar: Variance of PErrorOutput across endmembers.\n%\n% This product is Copyright (c) 2014 University of Missouri\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\n% are met:\n%\n% 1. Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n% 2. 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% 3. 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 THE UNIVERSITY OF MISSOURI AND\n% CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,\n% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n% DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS\n% BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n% LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,\n% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n% 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 M = size(Ptrue,2);\n t = (Ptrue- Pestimate).^2;\n PErrorOutput = sum(sum(t)) / N; % PError per pixel\n \n\nPErrorOutputmean = PErrorOutput/M; %Mean of PErrorOutput, PError per pixel per endmember\nPErrorOutputvar= var(PErrorOutput); %Variance of PErrorOutput\n\n%%Plot histogram across iterations for one N. FOR DEMO PURPOSES.\n% figure(100);\n% plot(PErrorOutput);\n% xlabel('N');ylabel('PError');\n% title('Plot of PErrorOutput');\n% figure(200);\n% hist(PErrorOutput);\n% xlabel('PError');ylabel('# of Data Points');\n% title('Histogram of PErrorOutput');\n\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/BCM/PError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7630151325848907}} {"text": "%demo for affine_fit\n%Author: Adrien Leygue\n%Date: December 3 2014\nclose all\nclear all\nfigure;\n%generate points that lie approximately in the Z=0 plane\nN = 10;\n[X,Y] = meshgrid(linspace(0,1,N));\nXYZ_1 = [X(:) Y(:) 0.05*randn(N^2,1)];\nplot3(XYZ_1(:,1),XYZ_1(:,2),XYZ_1(:,3),'r.');\nhold on\n%compute the normal to the plane and a point that belongs to the plane\n[n_1,~,p_1] = affine_fit(XYZ_1);\n\n%generate points that lie approximately in the Z=X plane\n%the normal vector is\nn_2_exact = [-sqrt(2)/2 0 sqrt(2)/2];\nN = 12;\n[X,Y] = meshgrid(linspace(0,1,N));\nXYZ_2 = [X(:) Y(:) X(:)] + bsxfun(@times,0.05*randn(N^2,1),n_2_exact);\nplot3(XYZ_2(:,1),XYZ_2(:,2),XYZ_2(:,3),'b.');\n\n\n%compute the normal to the plane and a point that belongs to the plane\n[n_2,V_2,p_2] = affine_fit(XYZ_2);\n\n%plot the two points p_1 and p_2\nplot3(p_1(1),p_1(2),p_1(3),'ro','markersize',15,'markerfacecolor','red');\nplot3(p_2(1),p_2(2),p_2(3),'bo','markersize',15,'markerfacecolor','blue');\n\n%plot the normal vector\nquiver3(p_1(1),p_1(2),p_1(3),n_1(1)/3,n_1(2)/3,n_1(3)/3,'r','linewidth',2)\nh = quiver3(p_2(1),p_2(2),p_2(3),n_2(1)/3,n_2(2)/3,n_2(3)/3,'b','linewidth',2)\n\n%plot the two adjusted planes\n[X,Y] = meshgrid(linspace(0,1,3));\n\n%first plane\nsurf(X,Y, - (n_1(1)/n_1(3)*X+n_1(2)/n_1(3)*Y-dot(n_1,p_1)/n_1(3)),'facecolor','red','facealpha',0.5);\n\n%second plane\n%NB: if the plane is vertical the above method cannot be used, one should\n%use the secont output of affine_fit which contains a base of the plane.\n%this is illustrated below\n%S1 and S2 are the coordinates of the plane points in the basis made of the\n%columns ov V_2\n[S1,S2] = meshgrid([-1 0 1]);\n%generate the pont coordinates\nX = p_2(1)+[S1(:) S2(:)]*V_2(1,:)';\nY = p_2(2)+[S1(:) S2(:)]*V_2(2,:)';\nZ = p_2(3)+[S1(:) S2(:)]*V_2(3,:)';\n%plot the plane\nsurf(reshape(X,3,3),reshape(Y,3,3),reshape(Z,3,3),'facecolor','blue','facealpha',0.5);\n\nxlabel('x');\nylabel('y');\nzlabel('z');\naxis equal\n%compute the angle between the planes in [0 90] degrees\nangle = acosd(dot(n_1,n_2));\nif angle>90\n angle = 180-angle;\nend\nangle\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/affine_fit/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7630151262263505}} {"text": "function y = huber_circ( x, DIM, varargin )\n\n%HUBER_CIRC Huber penalty function with circular symmetry.\n% For a vector X, HUBER_CIRC(X) computes the Huber penalty function\n%\n% HUBER_CIRC(X) = NORM(X,2)^2 if NORM(X,2)<=1,\n% 2*NORM(X,2)-1 if NORM(X,2)>=1.\n%\n% For matrices and N-D arrays, the penalty function is applied to the\n% first dimens\n%\n% HUBER_CIRC(X,[],M) computes the penalty function with halfwidth M,\n% M.^2.*HUBER_CIRC(X./M). M must be real and positive.\n%\n% HUBER_CIRC(X,[],M,T) computes the penalty function with halfwidth M\n% and concomitant scale T:\n%\n% HUBER_CIRC(X,[],M,T) = T.*HUBER_CIRC(X./T,[],M) if T > 0\n% +Inf if T <= 0\n%\n% See the help file for HUBER for information about this usage.\n%\n% If X is a matrix, the penalty function is applied to the columns of the\n% matrix X, and a row vector is returned. If X is an N-D matrix, the \n% penalties are computed along the first non-singleton dimension.\n%\n% HUBER_CIRC(X,DIM), HUBER_CIRC(X,DIM,M), and HUBER_CIRC(X,DIM,M,T) \n% computes the penalty along the dimension DIM.\n%\n% Disciplined convex programming information:\n% HUBER_CIRC is jointly convex in X and T. It is nonomonotonic in X \n% and nonincreasing in T. Therefore, when used in CVX specifications, \n% X must be affine and T must be concave (or affine). T must be real.\n% X, on the other hand, may be real or complex.\n\nif ~cvx_isaffine( x ),\n error( 'Disciplined convex programming error:\\n HUBER_CIRC is nonmonotonic in X, so X must be affine.', 1 ); %#ok\nend\nif nargin < 2, DIM = []; end\ny = huber_pos( norms( x, DIM ), varargin{:} );\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/huber_circ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7630151204883814}} {"text": "function h = ksizeHall(npd)\n%\n% Find kernel size according to \"plug-in\" method of \n% Hall, Marron, Sheather, Jones (91)\n% \n%\n\n% Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt\n\n x = getPoints(npd);\n [N1,N2] = size(x);\n sig = std(x,0,2); % estimate sigma (standard)\n lamS= .7413 * iqr(x')'; % find sigma by interquartile range lam\n if (max(lamS)==0) lamS=sig; end; % replace sigma est. if possible\n BW = 1.0592 * lamS * N2^(-1/(4+N1));\n BW = repmat(BW,[1,N2]);\n \n dX = repmat(permute(x,[1,3,2]),[1,N2,1]); % compute Xi-Xj for all i,j\n for i=1:N2, \n dX(:,:,i) = (dX(:,:,i)-x)./BW;\n end;\n for i=1:N2, dX(:,i,i) = 2e22; end;\n dX = reshape(dX,[N1,N2*N2]);\n\n% use that to find I2 and I3\n I2=h_findI2(N2,dX,BW(:,1)); % I2 = \\hat R( f^(2) ) = \\int f^(2)^2 dx\n I3=h_findI3(N2,dX,BW(:,1)); % I3 = \\hat R( f^(3) )\n\n% for Gaussian Kernel, we evaluate to find:\n% RK = 1.0/(2^N1) * 1.0/pi^(N1/2.0); % R(K) = \\int K^2(x) dx\n% mu2 = 1.0; % \\mu_i = \\int x^i K(x) dx\n% mu4 = 3.0^N1;\n switch (npd.type)\n case 0, RK = 0.282095; mu2 = 1.000000; mu4 = 3.000000; % Gauss\n case 1, RK = 0.600000; mu2 = 0.199994; mu4 = 0.085708; % Epanetch\n case 2, RK = 0.250002; mu2 = 1.994473; mu4 = 23.299070;% Laplace\n end;\n\n J1 = RK/mu2^2 .* 1./I2; \n J2 = (mu4 * I3) ./ (20 * mu2) .* 1./I2; \n h = (J1/N2).^(1.0/5) + J2.*(J1/N2).^(3.0/5); \n\n\n\n% Let us estimate R(f^(p)) by R( \\hat f^(p) )\n% (f is the original density to be est'd; f^(p) is its pth derivative)\n% Let L be the kernel function for this second estimator, with bandwidth alpha\n%\n% Ip = \\int f^(p)^2_\\alpha(x) dx \n% = [(-1)^p/n^2] \\sum_i \\sum_j L^(p)_\\alpha * L^(p)_\\alpha\n% = [(-1)^p/(n^2 \\alpha^(2p+1))] \\sum_i \\sum_j (L^(p) * L^(p))( (Xi-Xj)/\\alpha )\n%\n% Take L to be a Gaussian kernel; we then evaluate L^(p) by:\n%\n % L^(p)(x) = (-1)^p H_p(x) L(x)\n % H_p(x) = x H_{p-1}(x) - (p-1)H_{p-2}(x)\n % p=2 =>\n % H_2(x) = x H_1(x) - H_0(x) = x * x - 1\n % => L^(2)(x) = (x^2 - 1) * L(x)\n % p=3 =>\n % H_3(x) = x H_2(x) - 2*H_1(x) = x*(x^2-1) - 2*x\n % => L^(3)(x) = (x^3 - 3x) * L(x)\n %\n \nfunction I2 = h_findI2(n,dXa,alpha)\n%% load ksizeHSJM.mat;\n%% xInd = fix(Nquant * (dXa-Xmin) / (Xmax-Xmin));\n%% xInd = max(xInd,1); xInd = min(xInd,Nquant);\n%% s = sum( L2data(xInd) ,2);\n% s = sum( (dXa.^2 -1) .* 1/sqrt(2*pi) .* exp(-.5*dXa.^2) , 2);\n s = sum( (dXa.^2 -1) .* 1/sqrt(2*pi) .* repmat(exp(-.5*sum(dXa.^2,1)),[size(dXa,1),1]) , 2);\n I2=s./((n*(n-1))*alpha.^5);\n\nfunction I3 = h_findI3(n,dXb,beta)\n%% load ksizeHSJM.mat;\n%% xInd = fix(Nquant * (dXb-Xmin) / (Xmax-Xmin));\n%% xInd = max(xInd,1); xInd = min(xInd,Nquant);\n%% s = sum( L3data(xInd) , 2); \n% s = sum( (dXb.^3 -3*dXb) .* 1/sqrt(2*pi) .* exp(-.5*dXb.^2) , 2);\n s = sum( (dXb.^3 -3*dXb) .* 1/sqrt(2*pi) .* repmat(exp(-.5*sum(dXb.^2,1)),[size(dXb,1),1]) , 2);\n I3 = -s./((n*(n-1))*beta.^7);\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/render_pipeline/kde/matlab_kde_package/private/ksizeHall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8397339596505966, "lm_q1q2_score": 0.7629973127125855}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\n\nfor i = 1:length(lambda_vec)\n lambda = lambda_vec(i);\n [theta] = trainLinearReg(X, y, lambda);\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nend\n\n% =========================================================================\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.9019206785067698, "lm_q1q2_score": 0.762972977034966}} {"text": "function chebyshev1_rule ( order, a, b, filename )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV1_RULE generates a Gauss-Chebyshev type 1 quadrature rule.\n%\n% Discussion:\n%\n% This program computes a standard Gauss-Chebyshev type 1 quadrature rule\n% and writes it to a file.\n%\n% The user specifies:\n% * the ORDER (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% 28 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBYSHEV1_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a Gauss-Chebyshev type 1 rule for approximating\\n' );\n fprintf ( 1, ' Integral ( A <= x <= B ) f(x) / sqrt ( ( x - A ) * ( B - x ) ) dx\\n' );\n fprintf ( 1, ' of order ORDER.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies ORDER, A, B, and FILENAME.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER 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, ' filename_w.txt - the weight file\\n' );\n fprintf ( 1, ' filename_x.txt - the abscissa file.\\n' );\n fprintf ( 1, ' filename_r.txt - the region file.\\n' );\n%\n% Initialize the parameters.\n%\n alpha = 0.0;\n beta = 0.0;\n%\n% Get ORDER.\n%\n if ( nargin < 1 )\n order = input ( ' Enter the rule order ORDER: ' );\n elseif ( ischar ( order ) )\n order = str2num ( order );\n end\n%\n% Get 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 specifies the ''root name'' of the quadrature files).\\n' );\n filename = input ( ' Enter the value of FILENAME as a quoted string: ' );\n end\n%\n% Input summary.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER = %d\\n', order );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' FILENAME = \"%s\".\\n', filename );\n%\n% Construct the rule.\n%\n kind = 2;\n alpha = 0.0;\n beta = 0.0;\n [ x, w ] = cgqf ( order, kind, alpha, beta, a, b );\n%\n% Write the rule.\n%\n r = [ a, b ]';\n rule_write ( order, filename, x, w, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBYSHEV1_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ t, wts ] = cdgqf ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CDGQF computes a Gauss quadrature formula with default A, B and simple knots.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with a classical weight function with default values for A and B,\n% and only simple knots.\n%\n% There are no moments checks and no printing is done.\n%\n% Use routine EIQFS to evaluate a quadrature computed by CGQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n parchk ( kind, 2 * nt, alpha, beta );\n%\n% Get the Jacobi matrix and zero-th moment.\n%\n [ aj, bj, zemu ] = class_matrix ( kind, nt, alpha, beta );\n%\n% Compute the knots and weights.\n%\n [ t, wts ] = sgqf ( nt, aj, bj, zemu );\n\n return\nend\nfunction [ t, wts ] = cgqf ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% CGQF computes knots and weights of a Gauss quadrature formula.\n%\n% Discussion:\n%\n% The user may specify the interval (A,B).\n%\n% Only simple knots are produced.\n%\n% The user may request that the routine print the knots and weights,\n% and perform a moment check.\n%\n% Use routine EIQFS to evaluate this quadrature formula.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula for default values of A and B.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n%\n% Scale the quadrature rule.\n%\n [ t, wts ] = scqf ( nt, t, mlt, wts, nt, ndx, kind, alpha, beta, a, b );\n\n return\nend\nfunction [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n end\n\n return\nend\nfunction [ d, z ] = imtqlx ( n, d, e, z )\n\n%*****************************************************************************80\n%\n%% IMTQLX diagonalizes a symmetric tridiagonal matrix.\n%\n% Discussion:\n%\n% This routine is a slightly modified version of the EISPACK routine to\n% perform the implicit QL algorithm on a symmetric tridiagonal matrix.\n%\n% The authors thank the authors of EISPACK for permission to use this\n% routine.\n%\n% It has been modified to produce the product Q' * Z, where Z is an input\n% vector and Q is the orthogonal matrix diagonalizing the input matrix.\n% The changes consist (essentialy) of applying the orthogonal transformations\n% directly to Z as they are generated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Roger Martin, James Wilkinson,\n% The Implicit QL Algorithm,\n% Numerische Mathematik,\n% Volume 12, Number 5, December 1968, pages 377-383.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real D(N), the diagonal entries of the matrix.\n%\n% Input, real E(N), the subdiagonal entries of the\n% matrix, in entries E(1) through E(N-1). \n%\n% Input, real Z(N), a vector to be operated on.\n%\n% Output, real D(N), the diagonal entries of the diagonalized matrix.\n%\n% Output, real Z(N), the value of Q' * Z, where Q is the matrix that \n% diagonalizes the input symmetric tridiagonal matrix.\n%\n itn = 30;\n\n prec = eps;\n\n if ( n == 1 )\n return\n end\n\n e(n) = 0.0;\n\n for l = 1 : n\n\n j = 0;\n\n while ( 1 )\n\n for m = l : n\n\n if ( m == n )\n break\n end\n\n if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) )\n break\n end\n\n end\n\n p = d(l);\n\n if ( m == l )\n break\n end\n\n if ( j == itn )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IMTQLX - Fatal error!\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n error ( 'IMTQLX - Fatal error!' );\n end\n\n j = j + 1;\n g = ( d(l+1) - p ) / ( 2.0 * e(l) );\n r = sqrt ( g * g + 1.0 );\n g = d(m) - p + e(l) / ( g + r8_sign ( g ) * abs ( r ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ii = 1 : mml\n\n i = m - ii;\n f = s * e(i);\n b = c * e(i);\n\n if ( abs ( f ) >= abs ( g ) )\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e(i+1) = f * r;\n s = 1.0 / r;\n c = c * s;\n else\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e(i+1) = g * r;\n c = 1.0 / r;\n s = s * c;\n end\n\n g = d(i+1) - p;\n r = ( d(i) - g ) * s + 2.0 * c * b;\n p = s * r;\n d(i+1) = g + p;\n g = c * r - b;\n f = z(i+1);\n z(i+1) = s * z(i) + c * f;\n z(i) = c * z(i) - s * f;\n\n end\n\n d(l) = d(l) - p;\n e(l) = g;\n e(m) = 0.0;\n\n end\n\n end\n\n for ii = 2 : n\n\n i = ii - 1;\n k = i;\n p = d(i);\n\n for j = ii : n\n if ( d(j) < p )\n k = j;\n p = d(j);\n end\n end\n\n if ( k ~= i )\n d(k) = d(i);\n d(i) = p;\n p = z(i);\n z(i) = z(k);\n z(k) = p;\n end\n\n end\n\n return\nend\nfunction parchk ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PARCHK checks parameters ALPHA and BETA for classical weight functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the highest moment to\n% be calculated. This value is only needed when KIND = 8.\n%\n% Input, real ALPHA, BETA, the parameters, if required\n% by the value of KIND.\n%\n if ( kind <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND <= 0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.\n%\n if ( 3 <= kind && alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= KIND and ALPHA <= -1.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check BETA for Jacobi.\n%\n if ( kind == 4 && beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 4 and BETA <= -1.0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA and BETA for rational.\n%\n if ( kind == 8 )\n tmp = alpha + beta + m + 1.0;\n if ( 0.0 <= tmp || tmp <= beta )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 8 but condition on ALPHA and BETA fails.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n end\n\n return\nend\nfunction value = r8_sign ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIGN returns the sign of an R8.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose sign is desired.\n%\n% Output, real VALUE, the sign of X.\n%\n if ( 0 <= x )\n value = +1.0;\n else\n value = -1.0;\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction rule_write ( order, filename, x, w, r )\n\n%*****************************************************************************80\n%\n%% RULE_WRITE writes a quadrature rule to a file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, string FILENAME, specifies the output files.\n% write files 'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining \n% weights, abscissas, and region.\n%\n% Input, real X(ORDER), the abscissas.\n%\n% Input, real W(ORDER), the weights.\n%\n% Input, real R(2), the region.\n%\n filename_x = strcat ( filename, '_x.txt' );\n filename_w = strcat ( filename, '_w.txt' );\n filename_r = strcat ( filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' Creating quadrature files.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Root\" file name is \"%s\".\\n', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight file will be \"%s\".\\n', filename_w );\n fprintf ( 1, ' Abscissa file will be \"%s\".\\n', filename_x );\n fprintf ( 1, ' Region file will be \"%s\".\\n', filename_r );\n\n r8mat_write ( filename_w, 1, order, w' );\n r8mat_write ( filename_x, 1, order, x' );\n r8mat_write ( filename_r, 1, 2, r' );\n\n return\nend\nfunction [ t, wts ] = scqf ( nt, t, mlt, wts, nwts, ndx, kind, alpha, ...\n beta, a, b )\n\n%*****************************************************************************80\n%\n%% SCQF scales a quadrature formula to a nonstandard interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the original knots.\n%\n% Input, integer MLT(NT), the multiplicity of the knots.\n%\n% Input, real WTS(NWTS), the weights.\n%\n% Input, integer NWTS, the number of weights.\n%\n% Input, integer NDX(NT), used to index the array WTS.\n% For more details see the comments in CAWIQ.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the scaled knots.\n%\n% Output, real WTS(NWTS), the scaled weights.\n%\n temp = eps;\n\n parchk ( kind, 1, alpha, beta )\n\n if ( kind == 1 )\n\n al = 0.0;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 2 )\n\n al = -0.5;\n be = -0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 3 )\n\n al = alpha;\n be = alpha;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 4 )\n\n al = alpha;\n be = beta;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 5 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / b;\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 6 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / sqrt ( b );\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 7 )\n\n al = alpha;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 8 )\n\n if ( a + b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' A + B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = a + b;\n al = alpha;\n be = beta;\n\n elseif ( kind == 9 )\n\n al = 0.5;\n be = 0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n end\n\n p = slp^( al + be + 1.0 );\n\n for k = 1 : nt\n\n t(k) = shft + slp * t(k);\n l = abs ( ndx(k) );\n\n if ( l ~= 0 )\n tmp = p;\n for i = l : l + mlt(k) - 1\n wts(i) = wts(i) * tmp;\n tmp = tmp * slp;\n end\n end\n\n end\n\n return\nend\nfunction [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/chebyshev1_rule/chebyshev1_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7629729704233611}} {"text": "function value = r8_exponential_01_pdf ( rval )\n\n%*****************************************************************************80\n%\n%% R8_EXPONENTIAL_01_PDF: PDF of a standard exponential distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2013\n%\n% Author:\n%\n% John Burkardt.\n%\n% Parameters:\n%\n% Input, real RVAL, the point where the PDF is evaluated.\n%\n% Output, real VALUE, the value of the PDF.\n%\n if ( rval < 0.0 )\n value = 0.0;\n else\n value = exp ( - rval );\n end\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pdflib/r8_exponential_01_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7629729701078172}} {"text": "function square_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% SQUARE_MONTE_CARLO_TEST01 estimates integrals over 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 e_test = [ ...\n 0, 0; ...\n 2, 0; ...\n 0, 2; ...\n 4, 0; ...\n 2, 2; ...\n 0, 4; ...\n 6, 0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQUARE_MONTE_CARLO_TEST01\\n' );\n fprintf ( 1, ' Use SQUARE01_SAMPLE to estimate integrals \\n' );\n fprintf ( 1, ' along the interior of the unit square in 2D.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N' );\n fprintf ( 1, ' 1' );\n fprintf ( 1, ' X^2' );\n fprintf ( 1, ' Y^2' );\n fprintf ( 1, ' X^4' );\n fprintf ( 1, ' X^2Y^2' );\n fprintf ( 1, ' Y^4' );\n fprintf ( 1, ' X^6\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = square01_sample ( n, seed );\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e(1:2) = e_test(1:2,j);\n\n value = monomial_value ( 2, n, e, x );\n\n result = square01_area ( ) * sum ( value(1:n) ) / n;\n\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * n;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact' );\n\n for j = 1 : 7\n\n e(1:2) = e_test(1:2,j);\n\n result = square01_monomial_integral ( e );\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/square_monte_carlo/square_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7629729638959813}} {"text": "function dz = cartPoleDynamicsHumanReadable(z,u,p)\n% dz = cartPoleDynamicsHumanReadable(z,u,p)\n%\n% This function computes the first-order dynamics of the cart-pole.\n%\n% INPUTS:\n% z = [4, n] = [x;q;dx;dq] = state of the system\n% u = [1, n] = horizontal force applied to the cart\n% p = parameter struct\n% .g = gravity\n% .m1 = cart mass\n% .m2 = pole mass\n% .l = pendulum length\n% OUTPUTS:\n% dz = dz/dt = time derivative of state\n%\n%\n\n% x = z(1,:); %Cart position (Not used in dynamics)\nq = z(2,:); % pendulum (pole) angle, measure from gravity vector\ndx = z(3,:); % cart velocity\ndq = z(4,:); %pendulum angle rate\n\n% Unpack the physical parameters\nl = p.l; %Pendulum length\nm1 = p.m1; % cart mass\nm2 = p.m2; % pole mass\ng = p.g; %Gravity acceleration\n\n% The following expressions were derived using the symbolic math toolbox,\n% in the script: Derive_cartPole.m\n% Typically I use the automatically generated code, but I've written out\n% the code in a more readable way here for tutorial purposes.\n\nmEff = m1 + m2 - m2.*cos(q).^2;\ncentr = dq.^2.*l.*m2.*sin(q);\nddx = (u + centr + g.*m2.*cos(q).*sin(q))./mEff;\nddq = -(u.*cos(q) + (m1 + m2)*g*sin(q) + centr.*cos(q))./(l.*mEff);\n\ndz = [dx;dq;ddx;ddq];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/MatlabAnimationTutorial/Derive_CartPole/cartPoleDynamicsHumanReadable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7628765302823509}} {"text": "function [ vX ] = ProxL1NormSum( vY, paramGamma, paramB )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = ProxL1NormSum( vY, paramGamma, paramB )\n% Solving the Least Squares Problem with L1 Regualarization (LASOO) with\n% Linear Equality Constraints (Sum of Elements) - Prox Operator.\n% Input:\n% - vY - Input Vector.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - paramGamma - Parameter Gamma - L2 Regularization Factor.\n% Sets the coefficient of the L1 Term.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: [0, inf).\n% - paramB - Parameter B - Equality Constarint Parameter.\n% Sets the scalar constarint of the equality\n% condition.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - vX - Output Vector.\n% The vector whichi minizes teh objective function\n% and its sum of elements equals to paramB.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. Efficient Solvers for Sparse Subspace Clustering - https://arxiv.org/abs/1804.06291.\n% 2. https://math.stackexchange.com/a/2886715/33.\n% Remarks:\n% 1. S\n% TODO:\n% 1. U.\n% Release Notes:\n% - 1.0.000 18/08/2018 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\ndebugMode = OFF;\n\nnumElements = size(vY, 1);\n\nvB = sort([vY - paramGamma; vY + paramGamma], 'ascend');\niMin = 1; % paramB)\n iMin = idxJ;\n else\n iMax = idxJ;\n end\nend\n\nif(debugMode == ON)\n plot(vB(iMin), sum( ProxL1Norm(vY - vB(iMin), paramGamma) ) - paramB, 'o');\n plot(vB(iMax), sum( ProxL1Norm(vY - vB(iMax), paramGamma) ) - paramB, 'o');\nend\n\n% Once the section is found there a closed form solution.\n% Within the section [vB(iMin), vB(iMax)] the function has constant slope\n% and for any paramBeta \\in (vB(iMin), vB(iMax)) the function sign(vY -\n% paramBeta) is constant.\n% Hence sign(vY - paramBeta) .* max(abs(vY - paramBeta) - paramGamma), 0)\n% equals to (Only at the support, where max(abs(vY - paramBeta) -\n% paramGamma), 0) doesn't vanish) vY - paramBeta - paramGamam * sign().\n% Looking when this sum equals to paramB happens:\n% 1 / length(vSupport) * sumvY(vSupport) - \n\nparamBeta = (vB(iMin) + vB(iMax)) / 2;\nvX = ProxL1Norm(vY - paramBeta, paramGamma);\nvS = (vX ~= 0);\nparamBeta = (sum(vY(vS) - paramGamma * sign(vX(vS))) - paramB) / sum(vS); \nvX = ProxL1Norm(vY - paramBeta, paramGamma);\n\n\nend\n\n\nfunction [ vX ] = ProxL1Norm( vY, paramLambda )\n\nvX = sign(vY) .* max(abs(vY) - paramLambda, 0);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q2886713/ProxL1NormSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7628765236737893}} {"text": "function pdf = pearson_05_pdf ( x, a, b, c )\n\n%*****************************************************************************80\n%\n%% PEARSON_05_PDF evaluates the Pearson 5 PDF.\n%\n% Formula:\n%\n% PDF(X)(A,B) = A**B * ( X - C )**(-B-1)\n% * exp ( - A / ( X - C ) ) / Gamma ( B )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n% C < X\n%\n% Input, real A, B, C, the parameters of the PDF.\n% 0.0 < A, 0.0 < B.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x <= c )\n pdf = 0.0;\n else\n pdf = a^b * ( x - c )^( - b - 1.0 ) * exp ( - a / ( x - c ) ) / gamma ( b );\n end\n\n return\nend\n", "meta": {"author": "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/pearson_05_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7628765230254058}} {"text": "function [x y] = BipolarCoordinates(Xi,Eta,a) \n\n% a is radii that defies height of the domain\n% a > 0\n\n% Check the input arguments and set default values\n\nif nargin == 2\n a = 1. ;\nend\nr = Xi ;\ns = pi*(Eta-1/2) ;\n\nx = (a*sinh(r))/(cosh(r)+cos(s)) ;\ny = (a*sin(s))/(cosh(r)+cos(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/40618-grid-generation/GridGeneration/BipolarCoordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7627495465752411}} {"text": "function a_cum = i4vec_cum ( n, a )\n\n%*****************************************************************************80\n%\n%% I4VEC_CUM computes the cumulative sum of the entries of an I4VEC.\n%\n% Discussion:\n%\n% An I4VEC is a vector of I4's.\n%\n% Example:\n%\n% Input:\n%\n% A = (/ 1, 2, 3, 4 /)\n%\n% Output:\n%\n% A_CUM = (/ 1, 3, 6, 10 /)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, integer A(N), the vector to be summed.\n%\n% Output, integer A_CUM(1:N), the cumulative sum of the entries of A.\n%\n a_cum(1) = a(1);\n\n for i = 2 : n\n a_cum(i) = a_cum(i-1) + a(i);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4vec_cum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.7626976374779765}} {"text": "function qwv_2d_test02 ( )\n\n%*****************************************************************************80\n%\n%% QWV_2D_TEST02 tests QWV_2D for Padua points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = -1.0;\n b = +1.0;\n c = -1.0;\n d = +1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QWV_2D_TEST02:\\n' );\n fprintf ( 1, ' Compute the weights associated with an interpolatory\\n' );\n fprintf ( 1, ' quadrature rule defined by N=(T+1)*(T+2)/2 points,\\n' );\n fprintf ( 1, ' exact for polynomials of total degree T or less.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Interval = [%g,%g]\\n', a, b );\n fprintf ( 1, ' Y Interval = [%g,%g]\\n', c, d );\n\n for t = 0 : 10\n\n n = ( ( t + 1 ) * ( t + 2 ) ) / 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Degree T = %d\\n', t );\n fprintf ( 1, ' Number of points N = %d\\n', n );\n\n [ x, y ] = padua_point_set ( t );\n%\n% Compute the weights.\n%\n w = qwv_2d ( t, n, a, b, c, d, x, y );\n\n r8vec_print_16 ( n, w, ' Weights:' );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_weights_vandermonde_2d/qwv_2d_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7626976262835343}} {"text": "function [xi,w]=firstOrder3DCubPoints()\n%%FIRSTORDER3DCUBPOINTS Generate first-order cubature points\n% for integration over a 3-dimensional cube with vertices of \n% (1,-1,-1), (-1,-1,-1), (-1,1,-1), (1,1,-1), (1,-1,1),\n% (-1,-1,1), (-1,1,1), and (1,1,1).\n%\n%INPUTS: None\n%\n%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard\n% cube.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard cube (8).\n%\n%This function implements the points given in [1] (1 point). This point is\n%just the origin with a weight of 8.\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nw=8;\nxi=[0;0;0];\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Cube_Space/Cube/firstOrder3DCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7626976134642455}} {"text": "function p = er_ftest(dof1, dof2, F, dof2max)\n%\n% p = er_ftest(dof1, dof2, F, )\n%\n% Computes p-value given F-value. p and F can be vectors.\n% dof1 = dof of numerator (Number of Rows in RM)\n% dof2 = dof of denominator (DOF)\n%\n% Ref: Numerical Rec in C, pg 229.\n%\n% ras, 05/05; based on Ftest in fs-fast code.\n\nif(nargin ~= 3 & nargin ~= 4)\n msg = 'Usage: p = FTest(dof1, dof2, F, )'; \n error(msg);\n return;\nend\n\nif(length(dof1) > 1)\n error('dof1 must be a scalar');\nend\nif(length(dof2) > 1) \n error('dof2 must be a scalar');\nend\n\nif(nargin == 4) dof2 = min(dof2,dof2max); end\n\n\nz = dof2./(dof2 + dof1 * F);\n\n\n% 08/05/04: temp debug stuff, b/c of a funny session\nif any(z(:) < 0 | z(:) > 1 | isnan(z(:))) | ~isreal(z)\n fprintf('any < 0?: %i \\n',any(z(:) < 0))\n fprintf('any > 1?: %i \\n',any(z(:) > 1))\n fprintf('Isnan?: %i \\n',any(isnan(z(:))))\n fprintf('~Isreal?: %i \\n',~isreal(z))\n z = 0.5 * ones(size(z)); % temp hack so that betainc doesn't fail\nend\n% fprintf('DEBUG: Z ranges from %f to %f \\n',min(z(:)),max(z(:)));\n\np = betainc(z, dof2/2, dof1/2);\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/EventRelated/er_ftest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7626854615547043}} {"text": "function [ x,y ] = latlong2xy( lat, long, ref_lat, ref_long )\n% converts lat/long coordinates to cartesian x,y, output in km\n% ref_lat and ref_long is the geodetic reference point for plane approximation of the earth surface\n\nearth_circumf = 40074; % km\n\ny = (lat - ref_lat)/360 * earth_circumf;\nx = (long - ref_long)/360 * cos(ref_lat*pi/180) * earth_circumf;\n\nend\n\n", "meta": {"author": "DC9ST", "repo": "tdoa-evaluation-rtlsdr", "sha": "3e7791adca1179b0a0be715b240caa0ad01d09c7", "save_path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr", "path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr/tdoa-evaluation-rtlsdr-3e7791adca1179b0a0be715b240caa0ad01d09c7/functions/latlong2xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7626683046110208}} {"text": "function alpha = dfaScalingExponent(x, minBoxSize, maxBoxSize, pflag)\n%\n% varargout = dfaScalingExponent(xminBoxSize, midBoxSize, maxBoxSize, pflag) \n% calculates the detrended fluctuation analysis estimate of the scaling \n% exponent alpha. \n%\n% INPUTS\n% x : A Nx1 vector containing the series to be analyzed\n% minBoxSize : Smallest box width (default: 4)\n% maxBoxSize : Largest box width (default: N/4)\n% pflag : (Optional) pflag=1 plot, pflag=0 \n% OUTPUTS \n% alpha : estimate of scaling exponent, +\n% minBoxSize <= n <= maxBoxSize\n%\n% The raw time series x(i) is first integrated to give y(i); i=1,...,N. \n% For each length scale, n, y(i) is divided into segments of equal length, n.\n% In each segment, the data is detrended by subtracting the local linear least \n% squares fit, yn(k). The root-mean-square fluctuation of this integrated \n% and detrended time series is given by \n% F(n) = sqrt( (1/N) sum_{k=1}^N [y(k) - yn(k)]^2 )\n% We calculate the average fluctuation F(n) for each segment n. \n% If the scaling approximately given by F(n) = c n^alpha, \n% we can estimate alpha by calculating the slope of log F(n) versus log n.\n% Such a linear relationship on a log-log plot indicates the presence of \n% power law (fractal) scaling. \n% A log-log plot of F(n) against n is provided when pflag=1. Default: plag=0.\n% Peng C-K, Buldyrev SV, Havlin S, Simons M, Stanley HE, Goldberger AL. \n% Mosaic organization of DNA nucleotides. Phys Rev E 1994;49:1685-1689.\n%\n%\n% 09-20-2017 Modified by Giulia Da Poian (GDP) to be included in the Physionet \n% HRV Toolkit for Matlab. (Original function name: dfa)\n%\n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% Copyright (c) 2005 Patrick E. McSharry (patrick@mcsharry.net)\n%\n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n\nif nargin < 2 || isempty(minBoxSize)\n minBoxSize = 4;\nend\nif nargin < 3 || isempty(maxBoxSize)\n maxBoxSize = length(x)/4;\nend\nif nargin < 4\n pflag = 0;\nend\n\nif size(x,1)= 0 has r rows and \n% r = semi-nonnegative rank of M. \n%\n% See Corollary 3 in \n% N. Gillis, A. Kumar, Exact and Heuristic Algorithms for Semi-Nonnegative \n% Matrix Factorization, arXiv, 2014\n% \n% ****** Input ******\n% M : m-by-n matrix \n%\n% ****** Output ******\n% seminnrank : the (numerical) semi-nonnegative rank of M\n% (U,V) : M = UV, V >= 0 and U (resp. V) has 'seminnrank' columns\n% (resp. rows)\n\nr = rank(M); \nif issparse(M) ~= 1\n [U,S,V] = svd(M); \n V = V(:,1:r)'; \nelse\n [U,S,V] = svds(M,r); \n V = V'; \nend\n\n[y,eflag] = linsys_semiNMF(V,0); \nif eflag == 1\n seminnrank = r; \n if nargout >= 2\n V = LPinitSemiNMF(M,r); \n U = M/V; \n end\nelse\n seminnrank = r + 1; \n if nargout >= 2\n [U,V] = SVDinitSemiNMF(M,r+1); \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/nmf-deep/Deep-Semi-NMF-master/matlab/approx_seminmf/seminonnegativerank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7624902508831172}} {"text": "% Copyright (C) 2016, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction direct_kinematics_symbolic_KUKA_LBR\n% link lengths\n\nsyms q1 q2 q3 q4 q5 q6 Q7\nrobot = load_robot('KUKA', 'LBR_IIWA_R820_7DOF')\n\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n% matrices DH\nA01 = dh_sym(q1, d(1), a(1), alpha(1));\nA12 = dh_sym(q2, d(2), a(2), alpha(2));\nA23 = dh_sym(q3, d(3), a(3), alpha(3));\nA34 = dh_sym(q4, d(4), a(4), alpha(4));\nA45 = dh_sym(q5, d(5), a(5), alpha(5));\nA56 = dh_sym(q6, d(6), a(6), alpha(6));\nA67 = dh_sym(q7, d(7), a(7), alpha(7));\n\nA02 = A01*A12;\nA03 = A02*A23;\nA04 = A03*A34;\nA05 = A04*A45;\nA06 = A05*A56;\nA07 = A06*A67;\n\nA07 = simplify(A07)\n \nA03 = simplify(A03)\n\n\n\n\nfunction A = dh_sym(theta, d, a, alpha)\nsyms q1 q2 q3 q4 q5 q6\n% avoid almost zero elements in cos(alpha) and sin(alpha)\nca = cos(alpha);\nsa = sin(alpha);\nif abs(ca) < 1e-6\n ca = 0;\nend\nif abs(sa) < 1e-6\n sa = 0;\nend\n\n\nA=[cos(theta) -ca*sin(theta) sa*sin(theta) a*cos(theta);\n sin(theta) ca*cos(theta) -sa*cos(theta) a*sin(theta);\n 0 sa ca d;\n 0 0 0 1];\n \n\n \n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/book/direct_kinematics_symbolic_KUKA_LBR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7624680206167047}} {"text": "function circle_inout ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_INOUT plots data in and out of a circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_INOUT:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Make a scatterplot of two sets of data representing\\n' );\n fprintf ( 1, ' points in the unit square that are also in or not in\\n' );\n fprintf ( 1, ' the unit circle.\\n' );\n%\n% Read the data.\n%\n xy_in = load ( 'circle_in.txt' );\n [ n_in, dim ] = size ( xy_in );\n\n xy_out = load ( 'circle_out.txt' );\n [ n_out, dim ] = size ( xy_out );\n\n n = n_in + n_out;\n%\n% Report on the estimate for pi:\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of points inside the circle = %d\\n', n_in );\n fprintf ( 1, ' Number outside = %d\\n', n_out );\n fprintf ( 1, ' Total = %d\\n', n );\n fprintf ( 1, ' Estimate for PI = %d\\n', 4 * n_in / n );\n%\n% Set up points on a circle\n%\n n = 50;\n center = [ 0.0, 0.0 ];\n radius = 1.0;\n theta1 = 0.0;\n theta2 = 90.0;\n\n xy_circ = circle_arc ( n, center, radius, theta1, theta2 );\n%\n% Plot the data.\n%\n plot ( xy_in(:,1), xy_in(:,2), 'b.', ...\n xy_out(:,1), xy_out(:,2), 'r.', ...\n xy_circ(:,1), xy_circ(:,2), 'r-', 'LineWidth', 2 );\n grid on\n axis ( [ 0.0, 1.0, 0.0, 1.0 ] )\n axis equal\n axis square\n xlabel ( '<--- X --->' );\n ylabel ( '<--- Y --->' );\n title ( 'Random points inside/outside the unit circle' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_INOUT:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\nfunction xy_circ = circle_arc ( n, center, radius, theta1, theta2 )\n\n%*****************************************************************************80\n%\n%% CIRCLE_ARC samples points on a circular arc.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sample points.\n%\n% Input, real CENTER(2), the center of the circle.\n%\n% Input, real RADIUS, the radius of the circle.\n%\n% Input, real THETA1, THETA2, the angular coordinates of the first and\n% last points on the arc, in degrees.\n%\n% Output, real XY_CIRC(N,2), points along the arc.\n%\n t = pi * linspace ( theta1, theta2, n ) / 180;\n t = t';\n\n xy_circ = zeros ( n, 2 );\n\n xy_circ(:,1) = center(1) + radius * cos ( t(:,1) );\n xy_circ(:,2) = center(2) + radius * sin ( t(:,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/graphics_examples/circle_inout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.762457767105871}} {"text": "function s = hermite_integral ( p )\n\n%*****************************************************************************80\n%\n%% HERMITE_INTEGRAL evaluates a monomial Hermite integral.\n%\n% Discussion:\n%\n% Integral ( -oo < x < +oo ) x^p exp(-x^2) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 18 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer P, the exponent. \n% 0 <= P.\n%\n% Output, real S, the value of the integral.\n%\n if ( mod ( p, 2 ) == 0 )\n s = r8_factorial2 ( p - 1 ) * sqrt ( pi ) / 2.0 ^ ( p / 2 );\n else\n s = 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/exactness/hermite_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7624259387931772}} {"text": "function A = minimum_spanning_tree(C1, C2)\n%\n% Find the minimum spanning tree using Prim's algorithm.\n% C1(i,j) is the primary cost of connecting i to j.\n% C2(i,j) is the (optional) secondary cost of connecting i to j, used to break ties.\n% We assume that absent edges have 0 cost.\n% To find the maximum spanning tree, used -1*C.\n% See Aho, Hopcroft & Ullman 1983, \"Data structures and algorithms\", p 237.\n\n% Prim's is O(V^2). Kruskal's algorithm is O(E log E) and hence is more efficient\n% for sparse graphs, but is implemented in terms of a priority queue.\n\n% We partition the nodes into those in U and those not in U.\n% closest(i) is the vertex in U that is closest to i in V-U.\n% lowcost(i) is the cost of the edge (i, closest(i)), or infinity is i has been used.\n% In Aho, they say C(i,j) should be \"some appropriate large value\" if the edge is missing.\n% We set it to infinity.\n% However, since lowcost is initialized from C, we must distinguish absent edges from used nodes.\n\nn = length(C1);\nif nargin==1, C2 = zeros(n); end\nA = zeros(n);\n\nclosest = ones(1,n);\nused = zeros(1,n); % contains the members of U\nused(1) = 1; % start with node 1\nC1(find(C1==0))=inf;\nC2(find(C2==0))=inf;\nlowcost1 = C1(1,:);\nlowcost2 = C2(1,:);\n\nfor i=2:n\n ks = find(lowcost1==min(lowcost1));\n k = ks(argmin(lowcost2(ks)));\n A(k, closest(k)) = 1;\n A(closest(k), k) = 1;\n lowcost1(k) = inf;\n lowcost2(k) = inf;\n used(k) = 1;\n NU = find(used==0);\n for ji=1:length(NU)\n for j=NU(ji)\n if C1(k,j) < lowcost1(j)\n\tlowcost1(j) = C1(k,j);\n\tlowcost2(j) = C2(k,j);\n\tclosest(j) = k;\n end\n end\n end\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/graph/minimum_spanning_tree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8688267745399466, "lm_q1q2_score": 0.7623753242177265}} {"text": "%gs_top_to_bottom test top_to_bottom Gauss-Seidel iteration\n% IFISS scriptfile: HCE; 28 January 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n\n% Top-to-bottom Gauss-Seidel iterative solution of system Asupg x = fsupg\n% starting with zero initial guess, for problem defined on n x n grid.\n\n% For Figure 4.4 of Chapter 4:\n% generate benchmark problem with cd_testproblem (using prescribed\n% outflow for Example 3.1.1), plot residual using command\n% semilogy(stats(:,1),stats(:,2)/stats(1,2));\n\nQ = triu(Asupg,-1);\nxgs = zeros(length(fsupg),1);\n\nnf = norm(fsupg);\nr = fsupg - Asupg*xgs;\nnr = norm(r);\nits = 0;\nstats = [its,nr];\nfprintf('\\n%5i %15.3e\\n', its, nr);\n\ntol = 1.d-6;\n\n[L,U] = lu(Q);\nwhile nr/nf > tol,\n xgs = xgs + U\\(L\\r);\n r = fsupg - Asupg*xgs;\n nr = norm(r);\n its = its + 1;\n stats = [stats;[its,nr]];\n fprintf('%5i %15.3e\\n', its, nr); \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/toms866/solvers/ch4_code/gs_top_to_bottom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500234942118}} {"text": "%Finite Element Method 101-2\n%National Taiwan University\n%2D Elasticity problem\n\n%%clear memory\nclose all; clc; clear all;\nformat long;\n%% Load Mesh for Lab 10\n[nodeCoordinates,elementNodes]=Mesh_Lab10('T3');\n% node coordinates are given in mm\nNodePerElement=3;\nnumberNodes=length(nodeCoordinates);\nnumberElements=length(elementNodes);\n\n%% Import BCs\n\n% Essential BC's\nGDof = 2*numberNodes;\nprescribedDof = [1,2,3,4];\n\n% Natural BC's\nforce = zeros(GDof,1);\nforce(end) = -10; % 10 [kN]\n\n%% Import material and section properties\nE = 3E7; % [GPa]\npoisson = 0.3; %[-]\nthickness = 1; % [mm]\n\n%% Evalute force vector\n%force=formForceVectorT3(GDof,naturalBCs,surfaceOrientation,...\n% elementNodes,nodeCoordinates,P,thickness);\n\n%% Construct Stiffness matrix for T3 element\nD=E/(1-poisson^2)*[1 poisson 0;poisson 1 0;0 0 (1-poisson)/2];\n\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);\nscaleFactor=1.E5;\ndrawingMesh(nodeCoordinates+scaleFactor*[displacements(1:2:2*numberNodes) ...\n displacements(2:2:2*numberNodes)],elementNodes,'T3','r--');\n\n% Computes elements stresses\nfor e=1:numberElements \n numNodePerElement = length(elementNodes(e,:));\n numEDOF = 2*numNodePerElement;\n elementDof=zeros(1,numEDOF);\n for i = 1:numNodePerElement\n elementDof(2*i-1)=2*elementNodes(e,i)-1;\n elementDof(2*i)=2*elementNodes(e,i); \n end\n \n % B matrix\n x1 = nodeCoordinates(elementNodes(e,1),1);\n y1 = nodeCoordinates(elementNodes(e,1),2);\n x2 = nodeCoordinates(elementNodes(e,2),1);\n y2 = nodeCoordinates(elementNodes(e,2),2);\n x3 = nodeCoordinates(elementNodes(e,3),1);\n y3 = nodeCoordinates(elementNodes(e,3),2);\n A = 1/2*det([1 x1 y1; 1 x2 y2; 1 x3 y3]);\n B = 1/(2*A).*[y2-y3 0 y3-y1 0 y1-y2 0;\n 0 x3-x2 0 x1-x3 0 x2-x1;\n x3-x2 y2-y3 x1-x3 y3-y1 x2-x1 y1-y2];\n \n stress=D*B*displacements(elementDof);\n vonmises=sqrt(0.5*((stress(1)-(stress(2)))^2+(stress(2))^2+(stress(1))^2+6*(stress(3))^2));\n fprintf('\\n Stress in element % u \\n',e)\n fprintf('Sigma_xx : %0 .6f \\n',stress(1))\n fprintf('Sigma_yy : %0 .6f \\n',stress(2))\n fprintf('Sigma_xy : %0 .6f \\n',stress(3))\n fprintf('Vonmises : %0 .6f \\n',vonmises)\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/FEM/Lab10_T3/Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7623500224188348}} {"text": "function [h,h1,h2] = maxflatI(K,M)\n% [h,h1,h2] = maxflatI(K,M)\n% Maxflat Type-I FIR filter \n% 2K zeros at z=-1\n% 2M zeros away from z=-1\n% h = conv(h1,h2); \n% h1 : all zeros at z=-1\n% h2 : all other zeros\n%\n% Note: if K = M+1, then h is halfband.\n%\n% Reference:\n% O. Herrmann, \"On the approximation problem in Nonrecursive\n% Digital Filter Design\", IEEE Trans. on Circuit Theory,\n% Vol. 18, No. 3, May 1971, pp. 411-413\n%\n% % Example\n% [h,h1,h2] = maxflatI(4,6);\n\n% Ivan Selesnick\n% selesi@nyu.edu\n% NYU - School of Engineering\n\n\nh2 = 1;\nhi = 1;\nc = 1;\nfor k = 1:M\n hi = conv(hi,[-1 2 -1]/4);\n c = c*(K-1+k)/k;\n h2 = [0 h2 0] + c*hi;\nend\n\nh1 = 1;\nfor k = 1:2*K\n h1 = conv(h1,[1 1]/2);\nend\n\nh = conv(h1,h2);\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/maxflatI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.762350020424917}} {"text": "function [ g ] = gsp_design_regular(G, param)\n%GSP_DESIGN_REGULAR Create a regular filterbank\n% Usage: g = gsp_design_regular( G );\n% g = gsp_design_regular( G, param );\n% \n% Inputs parameters:\n% G : Graph structure or lmax\n% param : Structure of optional parameters\n%\n% Outputs parameters:\n% g : filterbank\n%\n% This function creates a parseval filterbank of $2$ filters. The low-pass\n% filter is defined by a function $f_l(x)$ between $0$ and $2$. For\n% $d = 0$.\n%\n% .. f_l(x) = sin(pi/4*x)\n%\n% .. math:: f_{l}= \\sin\\left( \\frac{\\pi}{4} x \\right)\n%\n% For $d = 1$ \n%\n% .. f_l(x) = sin( pi/4 * (1+sin(pi/2*(x-1))) )\n%\n% .. math:: f_{l}= \\sin\\left( \\frac{\\pi}{4} \\left( 1+ \\sin\\left(\\frac{\\pi}{2}(x-1)\\right) \\right) \\right)\n%\n% For $d = 2$ \n%\n% .. f_l(x) = sin( pi/4 * ( 1 + sin( pi/2 * sin(pi/2*(x-1) ) ) )\n%\n% .. math:: f_{l}= \\sin\\left( \\frac{\\pi}{4} \\left( 1+ \\sin\\left(\\frac{\\pi}{2} \\sin\\left(\\frac{\\pi}{2}(x-1)\\right)\\right) \\right) \\right)\n%\n% And so on for the other degrees $d$.\n%\n% The high pass filter is adapted to obtain a tight frame.\n%\n% This function will compute the maximum eigenvalue of the laplacian. To\n% be more efficient, you can precompute it using::\n%\n% G = gsp_estimate_lmax(G);\n%\n% Example:::\n%\n% G = gsp_sensor(100);\n% G = gsp_estimate_lmax(G);\n% g = gsp_design_regular(G); \n% gsp_plot_filter(G,g); \n% [A,B] = gsp_filterbank_bounds(G,g)\n%\n% *param* is an optional structure containing the following fields\n%\n% * *param.verbose*: verbosity level. 0 no log - 1 display warnings.\n% (default 1) \n% * *param.d*: Degree. See equation for mor informations. (default 3)\n%\n\n% Author: Nathanael Perraudin, David Shuman\n% Date : 21 June 2014\n% Testing: test_filter\n\n\nif nargin < 2\n param = struct;\nend\n\n\nif ~isfield(param,'verbose'), param.verbose = 1; end\nif ~isfield(param,'d'), param.d = 3; end\n\nif isstruct(G)\n if ~isfield(G,'lmax')\n if param.verbose\n fprintf('GSP_DESIGN_REGULAR has to compute lmax \\n')\n end\n G = gsp_estimate_lmax(G);\n end\n lmax = G.lmax;\nelse\n lmax = G;\nend\n\n\n\n\nd = param.d;\n\ng = cell(2,1);\ng{1} = @(x) regular(x*(2/lmax),d);\ng{2} = @(x) real(sqrt(1-(regular(x*(2/lmax),d)).^2));\n\nend\n\n\nfunction y = regular(val,d)\n\n\nif d==0\n y = sin(pi/4*val);\nelse\n output = sin(pi*(val-1)/2);\n for k=2:d\n output = sin(pi*output/2);\n end\n y = sin(pi/4*(1+output));\nend\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_design_regular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7623273916489314}} {"text": "%--------------------------------------------------------\n% FIR filter design via local moving window LS fitting -\n% A magic smooth and derivative formula generator. -\n% By Dr Yangquan Chen\t\t08-07-1999 -\n% Email=; URL=http://www.crosswinds.net/~yqchen/\n% ------------------------------------------------------- \n% Purpose: general FIR design via local LS fitting. \n% total taps = nL+nR+1\n% Format: function [c]=sgfilter(nL,nR,M,id)\n% -nL -nL+1 -1 nR\n% FIR=c(1)z +c(2)z +...+c(nL)z +...+c(nL+nR+1)z\n%\n% nR\n% ------\n% \\ j\n% > c(nL+1+j) z\n% /\n% ------\n% j=-nL\n% M: the order of LS fit at the moving window of [-nL, ... , nR]\n% id: index for the derivative order\n%\t\t0: smooth filter, \n%\t\t1: 1st order differentiator,\n% \t\t2: 2nd order differentiator, ... \n% NOTE: M>=id, set M=(2~4)*(id+1) for reliably results.\n%\t\t to do LS fit, MM)\n disp('Error in id! (id(nL+nR))\n disp('Error in M! (M<=nL+nR)');return;\nend\n\nA=zeros(nL+nR+1,M+1);\nfor i=-nL:nR;\n for j=0:M;\n A(i+nL+1,j+1)=i^j;\n end\nend\nh=zeros(M+1,1);\n%h(1)=1;\nh(id+1)=1;\nb=inv(A'*A)*h;\nc=zeros(nL+nR+1,1);\nfor n=-nL:nR\n nm=n.^[0:M];\n c(n+nL+1)=nm*b;\nend\n% coefficient for smoothing\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/3514-savitzky-golay-smoothing-filter/sgfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7623253928462611}} {"text": "% Created by Dwight Nwaigwe April 2011\n%\tThis program uses the ensemble kalman filter to estimate a system's state.\n%\tThe state is x_new=f(x,u)+w, where u some input, w the\n%\tGaussian distributed process noise, and f is a nonlinear function. The measurement \n%\tis y_new=h(x)+v where h is a nonlinear function and v Gaussian distributed measurement noise. \n\n\n% The algorithm used in this code is referenced from the following:\n% S Gillijns et. al., \"What Is the Ensemble Kalman Filter and How Well Does it Work?\"\n% Proceedings of the 2006 American Control Conference,\n% Minneapolis, Minnesota, USA, June 14-16, 2006, pp 4448-4453.\n\n\nfunction [x_tr,x_estbar,ybar]= ensemblekfilter(f,h,x_tr,x_ini,w,z,num_iterations) \n\n\n% Example\n\n% The state and measurement in this example is taken from Dan Simon, \"Kalman Filtering\", \n% Embedded Systems Programming,2001.\n% \n%\n%\tsyms x1 x2; %variables must be named x1...xn\n%\tf=[x1+.1*x2+.005;x2+.1];\n%\th=[x1];\n%\tx_tr=[1;1]; %initial value of state\n%\tx_ini=ones(2,20); %ensemble of initial estimate of the state\n%\tw=[10^-3; .02]; %process noise standard deviation\n%\tz=[10]; %measurement noise standard deviation\n%\tnum_iterations=600;\n% \tnum_members=20;\n% \t[a,b,c]=ensemblekfilter(f,h,x_tr,x_ini,w,z,num_iterations);\n\n\n[dummy,num_members]=size(x_ini);\np1=length(f);\nm1=length(h);\nvar_vector=[];\nxvec=[];\nx_estvec=[];\nyvec=[];\nx_est=x_ini;\n\nfor j=1:p1 %create vector containing variables x1 to xn\n eval(sprintf(' syms x%d', j));\n var_vector=[var_vector sprintf('x%d ',j)];\n end\nvar_vector=strcat('[',var_vector);\nvar_vector=strcat(var_vector,']');\n\nZcov=eye(m1); %create measurement noise covariance matrix\nfor j=1:m1\n Zcov(j,j)=z(j)^2;\nend\n\n\nfor i=1:num_iterations \n\n x_tr=subs(f,var_vector,x_tr)+w.*randn(p1,1); %compute true value of state at next time step\n \n for j=1:num_members\n W(:,j)=w.*randn(p1,1); %create process noise\n Z(:,j)=z.*randn(m1,1); %create measurement noise\n x_est(:,j)=subs(f,var_vector,x_est(:,j))+W(:,j); %forecast state\n y(:,j)=subs(h,var_vector,x_tr)+Z(:,j); %make measurement\n y_for(:,j)=subs(h,var_vector,x_est(:,j)); %forecast measurement\n end\n\n x_estbar=mean(x_est,2); \n ybar=mean(y,2);\n y_forbar=mean(y_for,2);\n\n for j=1:p1\n Ex(j,:)=[x_est(j,:)-x_estbar(j)];\n end\n\n for j=1:m1\n Ey(j,:)=[y_for(j,:)-y_forbar(j)];\n end\n\n Pxy=Ex*Ey'/(num_members-1);\n Pyy=Ey*Ey'/(num_members-1)+Zcov; %The addition of Zcov to Pyy is not done in Gillijns et. al but I use it here in case num_members=2 or Pyy is nearly singular\n K=Pxy*inv(Pyy);\n x_est=x_est+K*(y-y_for);\n xvec=[xvec x_tr];\n x_estvec=[x_estvec x_estbar];\n yvec=[yvec ybar];\n if i==num_iterations\n x_estbar=mean(x_est,2);\n end\nend\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31093-ensemble-kalman-filter/ensemblekfilter/ensemblekfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7623253883853695}} {"text": "function n = fitNormal(data, show_graph)\n%FITNORMAL - Fit a plane to the set of coordinates\n%\n%For a passed list of points in (x,y,z) cartesian coordinates,\n%find the plane that best fits the data, the unit vector\n%normal to that plane with an initial point at the average\n%of the x, y, and z values.\n%\n% :param data: Matrix composed of of N sets of (x,y,z) coordinates\n% with dimensions Nx3\n% :type data: Nx3 matrix\n%\n% :param show_graph: Option to display plot the result (default false)\n% :type show_graph: logical\n%\n% :return n: Unit vector that is normal to the fit plane\n% :type n: 3x1 vector\n\t\n\tif nargin == 1\n\t\tshow_graph = false;\n\tend\n\t\n\tfor i = 1:3\n\t\tX = data;\n\t\tX(:,i) = 1;\n\t\t\n\t\tX_m = X' * X;\n\t\tif det(X_m) == 0\n\t\t\tcan_solve(i) = 0;\n\t\t\tcontinue\n\t\tend\n\t\tcan_solve(i) = 1;\n\t\t\n\t\t% Construct and normalize the normal vector\n\t\tcoeff = (X_m)^-1 * X' * data(:,i);\n\t\tc_neg = -coeff;\n\t\tc_neg(i) = 1;\n\t\tcoeff(i) = 1;\n\t\tn(:,i) = c_neg / norm(coeff);\n\t\t\n\tend\n\t\n\tif sum(can_solve) == 0\n\t\terror('Planar fit to the data caused a singular matrix.')\n\t\treturn\n\tend\n\t\n\t% Calculating residuals for each fit\n\tcenter = mean(data);\n\toff_center = [data(:,1)-center(1) data(:,2)-center(2) data(:,3)-center(3)];\n\tfor i = 1:3\n\t\tif can_solve(i) == 0\n\t\t\tresidual_sum(i) = NaN;\n\t\t\tcontinue\n\t\tend\n\t\t\n\t\tresiduals = off_center * n(:,i);\n\t\tresidual_sum(i) = sum(residuals .* residuals);\n\t\t\n\tend\n\t\n\t% Find the lowest residual index\n\tbest_fit = find(residual_sum == min(residual_sum));\n\t\n\t% Possible that equal mins so just use the first index found\n\tn = n(:,best_fit(1));\n\t\n\tif ~show_graph\n\t\treturn\n\tend\n\t\n\trange = max(max(data) - min(data)) / 2;\n\tmid_pt = (max(data) - min(data)) / 2 + min(data);\n\txlim = [-1 1]*range + mid_pt(1);\n\tylim = [-1 1]*range + mid_pt(2);\n\tzlim = [-1 1]*range + mid_pt(3);\n\n\tL=plot3(data(:,1),data(:,2),data(:,3),'ro','Markerfacecolor','r'); % Plot the original data points\n\thold on;\n\tset(get(L, 'Parent'),'DataAspectRatio',[1 1 1],'XLim',xlim,'YLim',ylim,'ZLim',zlim);\n\t\n\tnorm_data = [mean(data); mean(data) + (n' * range)];\n\t\n\t% Plot the original data points\n\tL=plot3(norm_data(:,1),norm_data(:,2),norm_data(:,3),'b-','LineWidth',3);\n\tset(get(get(L,'parent'),'XLabel'),'String','x','FontSize',14,'FontWeight','bold')\n\tset(get(get(L,'parent'),'YLabel'),'String','y','FontSize',14,'FontWeight','bold')\n\tset(get(get(L,'parent'),'ZLabel'),'String','z','FontSize',14,'FontWeight','bold')\n\ttitle(sprintf('Normal Vector: <%0.3f, %0.3f, %0.3f>',n),'FontWeight','bold','FontSize',14)\n\tgrid on;\n\taxis square;\n\thold off;\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/37775-plane-fitting-and-normal-calculation/fitNormal/fitNormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7623253883853693}} {"text": "function [isinside,pt,coord]=linextriangle(p0,p1,plane)\n% [isinside,pt,coord]=linextriangle(p0,p1,plane)\n%\n% calculate the intersection of a 3d line (passing two points)\n% with a plane (determined by 3 points)\n%\n% author: Qianqian Fang \n% date: 12/12/2008\n%\n% parameters: \n% p0: a 3d point in form of (x,y,z)\n% p1: another 3d point in form of (x,y,z), p0 and p1 determins the line\n% plane: a 3x3 matrix, each row is a 3d point in form of (x,y,z)\n% this is used to define a plane\n% outputs:\n% isinside: a boolean variable, 1 for the intersection is within the \n% 3d triangle determined by the 3 points in plane; 0 is outside\n% pt: the coordinates of the intersection pint\n% coord: 1x3 vector, if isinside=1, coord will record the barycentric \n% coordinate for the intersection point within the triangle; \n% otherwise it will be all zeros.\n%\n% for degenerated lines or triangles, this will stop\n%\n% Please find more information at http://iso2mesh.sf.net/cgi-bin/index.cgi?metch\n%\n% this function is part of \"metch\" toobox, see COPYING for license\n\n[a,b,c,d]=getplanefrom3pt(plane);\n\nif(a*a+b*b+c*c==0.0)\n error('degenerated plane');\nend\n\ndl_n=sum([a b c].*(p1-p0));\n\nif(dl_n==0.0)\n error('degenerated line');\nend\n\n% solve for the intersection point\nt=-(a*p0(1)+b*p0(2)+c*p0(3)+d)/dl_n;\npt=p0+(p1-p0)*t;\n\n\ndist=sum(abs(diff(plane)));\n[md,imax]=sort(dist);\nif(md(2)==0.0)\n error('degenerated triangle');\nend\ngoodidx=imax(2:end);\n\nptproj=pt(goodidx);\nmat0=[plane(:,goodidx)',ptproj';1 1 1 1];\n\nisinside=0;\ncoord=[0 0 0];\n\ndet1=det(mat0(:,[4 2 3],:));\ndet2=det(mat0(:,[1 4 3],:));\nif(det1*det2<0) \n return; \nend\ndet3=det(mat0(:,[1 2 4],:));\nif(det2*det3<0) \n return;\nend\nif(det1*det3<0) \n return;\nend\nisinside=1;\ndet0=det(mat0(:,1:3));\n\ncoord=[det1 det2 det3]/det0;\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/linextriangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7623253871192319}} {"text": "function value = cc_abscissa ( order, i )\n\n%*****************************************************************************80\n%\n%% CC_ABSCISSA returns the I-th abscissa of the Clenshaw Curtis rule.\n%\n% Discussion:\n%\n% Our convention is that the abscissas are numbered from left to\n% right.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, integer I, the index of the desired abscissa. 1 <= I <= ORDER.\n%\n% Output, real VALUE, the value of the I-th abscissa in the \n% rule of order ORDER.\n%\n if ( order < 1 )\n value = - Inf;\n elseif ( i < 1 | order < i )\n value = - Inf;\n elseif ( order == 1 )\n value = 0.0;\n elseif ( 2 * ( order - i ) == order - 1 )\n value = 0.0;\n else\n value = cos ( ( order - i ) * pi / ( order - 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/sandia_sparse/cc_abscissa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.7622516915863098}} {"text": "function fe = spline_pchip_val ( n, x, f, d, ne, xe )\n\n%*****************************************************************************80\n%\n%% SPLINE_PCHIP_VAL evaluates a piecewise cubic Hermite function.\n%\n% Description:\n%\n% This routine may be used by itself for Hermite interpolation, or as an\n% evaluator for SPLINE_PCHIP_SET.\n%\n% This routine evaluates the cubic Hermite function at the points XE.\n%\n% Most of the coding between the call to CHFEV and the end of\n% the IR loop could be eliminated if it were permissible to\n% assume that XE is ordered relative to X.\n%\n% CHFEV does not assume that X1 is less than X2. Thus, it would\n% be possible to write a version of SPLINE_PCHIP_VAL that assumes a strictly\n% decreasing X array by simply running the IR loop backwards\n% and reversing the order of appropriate tests.\n%\n% The present code has a minor bug, which I have decided is not\n% worth the effort that would be required to fix it.\n% If XE contains points in [X(N-1),X(N)], followed by points less than\n% X(N-1), followed by points greater than X(N), the extrapolation points\n% will be counted (at least) twice in the total returned in IERR.\n%\n% The evaluation will be most efficient if the elements of XE are\n% increasing relative to X; that is, for all J <= K,\n% X(I) <= XE(J)\n% implies\n% X(I) <= XE(K).\n%\n% If any of the XE are outside the interval [X(1),X(N)],\n% values are extrapolated from the nearest extreme cubic,\n% and a warning error is returned.\n%\n% This routine was originally named \"PCHFE\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Fred Fritsch.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Fred Fritsch, Ralph Carlson,\n% Monotone Piecewise Cubic Interpolation,\n% SIAM Journal on Numerical Analysis,\n% Volume 17, Number 2, April 1980, pages 238-246.\n%\n% Parameters:\n%\n% Input, integer N, the number of data points. N must be at least 2.\n%\n% Input, real X(N), the strictly increasing independent\n% variable values.\n%\n% Input, real F(N), the function values.\n%\n% Input, real D(N), the derivative values.\n%\n% Input, integer NE, the number of evaluation points.\n%\n% Input, real XE(NE), points at which the function is to\n% be evaluated.\n%\n% Output, real FE(NE), the values of the cubic Hermite\n% function at XE.\n%\n\n%\n% Check arguments.\n%\n if ( n < 2 )\n ierr = -1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' Number of data points less than 2.\\n' );\n error ( 'SPLINE_PCHIP_VAL - Fatal error!' );\n end\n\n for i = 2 : n\n if ( x(i) <= x(i-1) )\n ierr = -3;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' X array not strictly increasing.\\n' );\n error ( 'SPLINE_PCHIP_VAL - Fatal error!' );\n end\n end\n\n if ( ne < 1 )\n ierr = -4;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' Number of evaluation points less than 1.\\n' );\n fe = [];\n return\n end\n\n ierr = 0;\n%\n% Loop over intervals.\n% The interval index is IL = IR-1.\n% The interval is X(IL) <= X < X(IR).\n%\n j_first = 1;\n ir = 2;\n\n while ( 1 )\n%\n% Skip out of the loop if have processed all evaluation points.\n%\n if ( ne < j_first )\n break\n end\n%\n% Locate all points in the interval.\n%\n j_save = ne + 1;\n\n for j = j_first : ne\n if ( x(ir) <= xe(j) )\n j_save = j;\n if ( ir == n )\n j_save = ne + 1;\n end\n break\n end\n end\n%\n% Have located first point beyond interval.\n%\n j = j_save;\n\n nj = j - j_first;\n%\n% Skip evaluation if no points in interval.\n%\n if ( nj ~= 0 )\n%\n% Evaluate cubic at XE(J_FIRST:J-1).\n%\n [ fe(j_first:j-1), next, ierc ] = chfev ( x(ir-1), x(ir), f(ir-1), ...\n f(ir), d(ir-1), d(ir), nj, xe(j_first:j-1) );\n\n if ( ierc < 0 )\n ierr = -5;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' Error return from CHFEV.\\n' );\n error ( 'SPLINE_PCHIP_VAL - Fatal error!' );\n end\n%\n% In the current set of XE points, there are NEXT(2) to the right of X(IR).\n%\n if ( next(2) ~= 0 )\n\n if ( ir < n )\n ierr = -5;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' IR < N.\\n' );\n error ( 'SPLINE_PCHIP_VAL - Fatal error!' );\n end\n%\n% These are actually extrapolation points.\n%\n ierr = ierr + next(2);\n\n end\n%\n% In the current set of XE points, there are NEXT(1) to the left of X(IR-1).\n%\n if ( next(1) ~= 0 )\n%\n% These are actually extrapolation points.\n%\n if ( ir <= 2 )\n ierr = ierr + next(1);\n else\n\n j_new = -1;\n\n for i = j_first : j-1\n if ( xe(i) < x(ir-1) )\n j_new = i;\n break\n end\n end\n\n if ( j_new == -1 )\n ierr = -5;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\\n' );\n fprintf ( 1, ' Could not bracket the data point.\\n' );\n error ( 'SPLINE_PCHIP_VAL - Fatal error!' );\n end\n%\n% Reset J. This will be the new J_FIRST.\n%\n j = j_new;\n%\n% Now find out how far to back up in the X array.\n%\n for i = 1 : ir-1\n if ( xe(j) < x(i) )\n break\n end\n end\n%\n% At this point, either XE(J) < X(1) or X(i-1) <= XE(J) < X(I) .\n%\n% Reset IR, recognizing that it will be incremented before cycling.\n%\n ir = max ( 1, i-1 );\n\n end\n\n end\n\n j_first = j;\n\n end\n\n ir = ir + 1;\n\n if ( n < ir )\n break\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/spline/spline_pchip_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002789, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7621636519233203}} {"text": "% DEMO -- Chebyshev Polynomial Interpolation and Differentiation\n% UPDATED -- October 28, 2013\n% Written by Matthew Kelly, Cornell University\n%\n% This script demonstrates how chebyshev interpolants can be used to get\n% accurate derivate information. \n%\n\n%% General Settings\nclear; clc;\n\n%What order should the approximation be?\norder = 34; %Low = 25, %Med = 1000, %High = 100000\n\n%How many points should be used for error calculations and plotting?\nnTime = 1000;\n\n%What domain should we be looking at?\nd = [0,1.3];\n\n%Time for use in plots\ntime = linspace(d(1),d(2),nTime);\n\n% %The following version of time will yield more accurate results and a\n% %faster runtime because the points in time do not line up exactly with\n% the chebyshev grid points.\n% time = linspace(d(1)-1e-4, d(2)+2e-4,nTime); \n\n%% DEMO -- Fit to analytic function\n\n%Set up analytic function\nIO.domain = d;\nIO.userFunc = @testFunction;\n\n%Get the values at each of the chebyshev nodes\nf = chebyshevFit(IO, order); %Chebyshev Values\ntic\n[y,Dy,DDy,DDDy] = chebyshevInterpolate(f,time,d); %Approximation\ntoc\n\n%get the exact (analytic) solution for each derivative\n[g,Dg,DDg,DDDg] = testFunction(time);\n\n%Show results\nfigure(401); clf; \nsubplot(4,2,1);\n plot(time,y,'b-','LineWidth',2) \n title(['function approximation - order ' num2str(order)]);\nsubplot(4,2,3)\n plot(time,Dy,'b-','LineWidth',2) \n title(['derivative approximation - order ' num2str(order)]);\nsubplot(4,2,5)\n plot(time,DDy,'b-','LineWidth',2) \n title(['second derivative approximation - order ' num2str(order)]);\nsubplot(4,2,7)\n plot(time,DDDy,'b-','LineWidth',2) \n title(['third derivative approximation - order ' num2str(order)]);\nsubplot(4,2,2);\n semilogy(time,abs(g-y)) \n title('error in function');\nsubplot(4,2,4)\n semilogy(time,abs(Dg-Dy)) \n title('error in derivative');\nsubplot(4,2,6)\n semilogy(time,abs(DDg-DDy)) \n title('error in second derivative');\nsubplot(4,2,8)\n semilogy(time,abs(DDDg-DDDy)) \n title('error in third derivative');\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/chebyshevPolynomials/DEMO_2_derivatives.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7621636499552648}} {"text": "function [ x, seed ] = ball_unit_sample_nd ( n, seed )\n\n%*****************************************************************************80\n%\n%% BALL_UNIT_SAMPLE_ND picks a random point in the unit ball in ND.\n%\n% Discussion:\n%\n% N-1 random Givens rotations are applied to the point ( 1, 0, 0, ..., 0 ).\n%\n% The I-th Givens rotation is in the plane of coordinate axes I and I+1,\n% and has the form:\n%\n% [ cos ( theta ) - sin ( theta ) ] * x(i) = x'(i)\n% [ sin ( theta ) cos ( theta ) ] x(i+1) x'(i+1)\n%\n% Finally, a scaling is applied to set the point at a distance R\n% from the center, in a way that results in a uniform distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 June 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N), the random point.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n x(1) = 1.0;\n x(2:n) = 0.0;\n\n for i = 1 : n-1\n\n [ r, seed ] = r8_uniform_01 ( seed );\n random_cosine = 2.0 * r - 1.0;\n [ r, seed ] = r8_uniform_01 ( seed );\n random_sign = 2 * floor ( 2.0 * r ) - 1;\n [ r, seed ] = r8_uniform_01 ( seed );\n random_sine = random_sign * sqrt ( 1.0 - random_cosine * random_cosine );\n\n xi = x(i);\n x(i ) = random_cosine * xi;\n x(i+1) = random_sine * xi;\n\n end\n\n [ r, seed ] = r8_uniform_01 ( seed );\n\n r = r^( 1.0 / n );\n\n x(1:n) = r * x(1:n);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/ball_unit_sample_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7621562752828898}} {"text": "%% Learns the weights of a perceptron and displays the results.\nfunction [w] = learn_perceptron(neg_examples_nobias,pos_examples_nobias,w_init,w_gen_feas)\n%% \n% Learns the weights of a perceptron for a 2-dimensional dataset and plots\n% the perceptron at each iteration where an iteration is defined as one\n% full pass through the data. If a generously feasible weight vector\n% is provided then the visualization will also show the distance\n% of the learned weight vectors to the generously feasible weight vector.\n% Required Inputs:\n% neg_examples_nobias - The num_neg_examples x 2 matrix for the examples with target 0.\n% num_neg_examples is the number of examples for the negative class.\n% pos_examples_nobias - The num_pos_examples x 2 matrix for the examples with target 1.\n% num_pos_examples is the number of examples for the positive class.\n% w_init - A 3-dimensional initial weight vector. The last element is the bias.\n% w_gen_feas - A generously feasible weight vector.\n% Returns:\n% w - The learned weight vector.\n%%\n\n%Bookkeeping\nnum_neg_examples = size(neg_examples_nobias,1);\nnum_pos_examples = size(pos_examples_nobias,1);\nnum_err_history = [];\nw_dist_history = [];\n\n%Here we add a column of ones to the examples in order to allow us to learn\n%bias parameters.\nneg_examples = [neg_examples_nobias,ones(num_neg_examples,1)];\npos_examples = [pos_examples_nobias,ones(num_pos_examples,1)];\n\n%If weight vectors have not been provided, initialize them appropriately.\nif (~exist('w_init','var') || isempty(w_init))\n w = randn(3,1);\nelse\n w = w_init;\nend\n\nif (~exist('w_gen_feas','var'))\n w_gen_feas = [];\nend\n\n%Find the data points that the perceptron has incorrectly classified\n%and record the number of errors it makes.\niter = 0;\n[mistakes0, mistakes1] = eval_perceptron(neg_examples,pos_examples,w);\nnum_errs = size(mistakes0,1) + size(mistakes1,1);\nnum_err_history(end+1) = num_errs;\nfprintf('Number of errors in iteration %d:\\t%d\\n',iter,num_errs);\nfprintf(['weights:\\t', mat2str(w), '\\n']);\nplot_perceptron(neg_examples, pos_examples, mistakes0, mistakes1, num_err_history, w, w_dist_history);\nkey = input('', 's');\nif (key == 'q')\n return;\nend\n\n%If a generously feasible weight vector exists, record the distance\n%to it from the initial weight vector.\nif (length(w_gen_feas) ~= 0)\n w_dist_history(end+1) = norm(w - w_gen_feas);\nend\n\n%Iterate until the perceptron has correctly classified all points.\nwhile (num_errs > 0)\n iter = iter + 1;\n\n %Update the weights of the perceptron.\n w = update_weights(neg_examples,pos_examples,w);\n\n %If a generously feasible weight vector exists, record the distance\n %to it from the current weight vector.\n if (length(w_gen_feas) ~= 0)\n w_dist_history(end+1) = norm(w - w_gen_feas);\n end\n\n %Find the data points that the perceptron has incorrectly classified.\n %and record the number of errors it makes.\n [mistakes0, mistakes1] = eval_perceptron(neg_examples,pos_examples,w);\n num_errs = size(mistakes0,1) + size(mistakes1,1);\n num_err_history(end+1) = num_errs;\n\n fprintf('Number of errors in iteration %d:\\t%d\\n',iter,num_errs);\n fprintf(['weights:\\t', mat2str(w), '\\n']);\n plot_perceptron(neg_examples, pos_examples, mistakes0, mistakes1, num_err_history, w, w_dist_history);\n key = input('', 's');\n if (key == 'q')\n break;\n end\nend\n\n%WRITE THE CODE TO COMPLETE THIS FUNCTION\nfunction [w] = update_weights(neg_examples, pos_examples, w_current)\n%% \n% Updates the weights of the perceptron for incorrectly classified points\n% using the perceptron update algorithm. This function makes one sweep\n% over the dataset.\n% Inputs:\n% neg_examples - The num_neg_examples x 3 matrix for the examples with target 0.\n% num_neg_examples is the number of examples for the negative class.\n% pos_examples- The num_pos_examples x 3 matrix for the examples with target 1.\n% num_pos_examples is the number of examples for the positive class.\n% w_current - A 3-dimensional weight vector, the last element is the bias.\n% Returns:\n% w - The weight vector after one pass through the dataset using the perceptron\n% learning rule.\n%%\nw = w_current;\nnum_neg_examples = size(neg_examples,1);\nnum_pos_examples = size(pos_examples,1);\nfor i=1:num_neg_examples\n this_case = neg_examples(i,:);\n x = this_case'; %Hint\n activation = this_case*w;\n if (activation >= 0)\n %YOUR CODE HERE\n w = w - x;\n end\nend\nfor i=1:num_pos_examples\n this_case = pos_examples(i,:);\n x = this_case';\n activation = this_case*w;\n if (activation < 0)\n %YOUR CODE HERE\n w = w + x;\n end\nend\n\nfunction [mistakes0, mistakes1] = eval_perceptron(neg_examples, pos_examples, w)\n%% \n% Evaluates the perceptron using a given weight vector. Here, evaluation\n% refers to finding the data points that the perceptron incorrectly classifies.\n% Inputs:\n% neg_examples - The num_neg_examples x 3 matrix for the examples with target 0.\n% num_neg_examples is the number of examples for the negative class.\n% pos_examples- The num_pos_examples x 3 matrix for the examples with target 1.\n% num_pos_examples is the number of examples for the positive class.\n% w - A 3-dimensional weight vector, the last element is the bias.\n% Returns:\n% mistakes0 - A vector containing the indices of the negative examples that have been\n% incorrectly classified as positive.\n% mistakes0 - A vector containing the indices of the positive examples that have been\n% incorrectly classified as negative.\n%%\nnum_neg_examples = size(neg_examples,1);\nnum_pos_examples = size(pos_examples,1);\nmistakes0 = [];\nmistakes1 = [];\nfor i=1:num_neg_examples\n x = neg_examples(i,:)';\n activation = x'*w;\n if (activation >= 0)\n mistakes0 = [mistakes0;i];\n end\nend\nfor i=1:num_pos_examples\n x = pos_examples(i,:)';\n activation = x'*w;\n if (activation < 0)\n mistakes1 = [mistakes1;i];\n end\nend\n\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/Assignment1/learn_perceptron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7621562726298479}} {"text": "function mu_pq = moment_central ( n, x, y, p, q )\n\n%*****************************************************************************80\n%\n%% MOMENT_CENTRAL computes central moments of a polygon.\n%\n% Discussion:\n%\n% The central moment Mu(P,Q) is defined by\n%\n% Mu(P,Q) = Integral ( polygon ) (x-Alpha(1,0))^p (y-Alpha(0,1))^q dx dy\n% / Area ( polygon )\n%\n% where\n%\n% Alpha(1,0) = Integral ( polygon ) x dx dy / Area ( polygon )\n% Alpha(0,1) = Integral ( polygon ) y dx dy / Area ( polygon )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carsten Steger,\n% On the calculation of arbitrary moments of polygons,\n% Technical Report FGBV-96-05,\n% Forschungsgruppe Bildverstehen, Informatik IX,\n% Technische Universitaet Muenchen, October 1996.\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices of the polygon.\n%\n% Input, real X(N), Y(N), the vertex coordinates.\n%\n% Input, integer P, Q, the indices of the moment.\n%\n% Output, real MU_PQ, the unnormalized moment Mu(P,Q).\n%\n alpha_10 = moment_normalized ( n, x, y, 1, 0 );\n alpha_01 = moment_normalized ( n, x, y, 0, 1 );\n\n mu_pq = 0.0;\n\n for i = 0 : p\n for j = 0 : q\n\n alpha_ij = moment_normalized ( n, x, y, i, j );\n\n mu_pq = mu_pq + r8_mop ( p + q - i - j ) ...\n * r8_choose ( p, i ) * r8_choose ( q, j ) ...\n * alpha_10 ^ ( p - i ) * alpha_01 ^ ( q - j ) * alpha_ij;\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/polygon_integrals/moment_central.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.762041987522038}} {"text": "function [I_dx, I_dy] = sobel5x5(img)\n%SOBEL5X5 Apply Sobel–Feldman filter over input image\n% Sobel filters are discrete differentiation operator. They are used to \n% compute an approximation of the gradient of an image intensity function\n%\n% INPUT:\n% - img(image): Given input image\n%\n% OUTPUT:\n% - I_dx: gradient of image along x-axis\n% - I_dy: gradient of image along y-axis\n\n% sobel kernels\nsobel_kernel1 = [1, 4, 6, 4, 1];\nsobel_kernel2 = [1, 2, 0, -2, -1];\ndivisor = 48;\n\n% gradient along x\nI_dx = conv2(sobel_kernel2', sobel_kernel1, img, 'valid');\nI_dx = uint8(I_dx / divisor + 128);\n\n% gradient along y\nI_dy = conv2(sobel_kernel1', sobel_kernel2, img, 'valid');\nI_dy = uint8(I_dy / divisor + 128);\n\n% imshowpair(I_dx, I_dy, 'montage');\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/featureProcessing/filters/sobel5x5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263197, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7619869450816518}} {"text": "function a = minij ( m, n )\n\n%*****************************************************************************80\n%\n%% MINIJ returns the MINIJ matrix.\n%\n% Formula:\n%\n% A(I,J) = min ( I, J )\n%\n% Example:\n%\n% N = 5\n%\n% 1 1 1 1 1\n% 1 2 2 2 2\n% 1 2 3 3 3\n% 1 2 3 4 4\n% 1 2 3 4 5\n%\n% Properties:\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is positive definite.\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% The inverse of A is tridiagonal.\n%\n% The eigenvalues of A are\n%\n% LAMBDA(I) = 0.5 / ( 1 - cos ( ( 2 * I - 1 ) * pi / ( 2 * N + 1 ) ) ),\n%\n% For N = 12, the characteristic polynomial is\n% P(X) = X**12 - 78 X**11 + 1001 X**10 - 5005 X**9 + 12870 X**8\n% - 19448 X**7 + 18564 X**6 - 11628 X**5 + 4845 X**4 - 1330 X**3\n% + 231 X**2 - 23 X + 1.\n%\n% (N+1)*ONES(N) - A also has a tridiagonal inverse.\n%\n% Gregory and Karney consider the matrix defined by\n%\n% B(I,J) = N + 1 - MAX(I,J)\n%\n% which is equal to the MINIJ matrix, but with the rows and\n% columns reversed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% Example 3.12, Example 4.14,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, 1969, page 41, page 74, \n% LC: QA263.G68.\n%\n% Daniel Rutherford,\n% Some continuant determinants arising in physics and chemistry II,\n% Proceedings of the Royal Society Edinburgh,\n% Volume 63, A, 1952, pages 232-241.\n%\n% John Todd,\n% Basic Numerical Mathematics, Vol. 2: Numerical Algebra,\n% Academic Press, 1977, page 158.\n%\n% Joan Westlake,\n% A Handbook of Numerical Matrix Inversion and Solution of \n% Linear Equations,\n% John Wiley, 1968,\n% ISBN13: 978-0471936756,\n% LC: QA263.W47.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns \n% of the matrix.\n%\n% Output, real A(M,N), the matrix.\n%\n for i = 1 : m\n for j = 1 : n\n a(i,j) = min ( i, j );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/correlation/minij.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7619593279457577}} {"text": "function [rlvm, frvals, frvecs, trnsfrmd, mn, dv] = TSTL_pca(data, mode, maxpercent, sil)\n\n% [rlvm, frvals, frvecs, trnsfrmd, mn, dv] = pca(data, mode, maxpercent, silent)\n%\n% principal component analysis of column orientated data set \n% \n% input arguments :\n%\n% - each row of data is one 'observation', e.g. the sample values of\n% all channels in a multichannel measurement at one point in time\n%\n% - mode can be one of the following : 'normalized' (default), 'mean', 'raw'\n% - in mode 'normalized' each column of data is centered by removing its mean\n% and then normalized by dividing through its standard deviation before\n% the covariance matrix is calculated\n% - in mode 'mean' only the mean of every column of data is removed\n% - in mode 'raw' no preprocessing is applied to data\n%\n% - maxpercent gives the limit of the accumulated percentage of the resulting\n% eigenvalues, default is 95 %\n%\n% - silent is an optional flag which supresses output of text and plot on the matlab\n% screen. Returned values (see below) are in no way affected\n%\n% output arguments :\n%\n% - rlvm : number of relevant modes to reach maxpercent\n% - frvals : first rlvm relevant eigenvalues \n% - frvecs : first rlvm relevant eigenvectors (eigenmodes, or principal components)\n% - trnsfrmd : data points transformed to the coordinate system given be the eigenvectors \n% - mn : mean of the original data set (only in mode 'mean' and 'normalized')\n% - dv : standard deviation of the original data set (only in mode 'normalized')\n%\n% \n% To compute an approximation of data : data = trnsfrmd * frvecs'\n%\n% Christian Merkwirth (cmerk) Maerz 1997\n% cmerk Jan. 1998\n\nglobal silent\n\nif nargin < 1, help(mfilename); end\n\nif nargin < 2\n\tmode = 'normalized';\nend\nif nargin < 3\n\tmaxpercent = 95;\nend\nif nargin < 4\n\tsilent = 0;\nelse\n\tsilent = 1;\nend\n\n%rang = rank(data);\n[n,m] = size(data);\n\nprintline('principal component analysis')\nprintline(['on data set of size ' num2str(n) 'x' num2str(m)]);\t% ' with rank ' num2str(rang)])\nprintline(['eigenvalues are computed up to ' num2str(maxpercent) ' percent']);\n\nmaxpercent = maxpercent/100;\nmode = lower(mode); \t\t% no problems with uppercase letters \n\n\nif strncmp(mode, 'r',1)\n\tmode = 'raw';\n\tprintline('no data preprocessing');\nelseif strncmp(mode, 'm',1)\n\tmode = 'mean';\n\tprintline('removing mean from data set');\n\tmn = mean(data);\n\tdata = data - repmat(mn, n, 1);\nelse\n\tmode = 'normalized';\n\tprintline('removing mean and normalizing data');\n\tmn = mean(data);\n\tdv = std(data);\n\tdata = data - repmat(mn, n, 1);\n\tdata = data ./ repmat(dv, n, 1);\nend\n\n%sum(mean(data))/m\t% test\n%sum(std(data))/m\t% test\n\nif n>m\n\tprintline('using direct method to compute covariance matrix');\n\tK = data' * data; % oder K = corrcoef(data)\n\t[Q,D] = eig(K);\n else\n printline('using indirect method to compute covariance matrix');\n \tC = data * data';\n \t[Q,D] = eig(C);\t \nend\n\n[evalues,index] = sort(diag(D));\nevalues = flipud(evalues);\nindex = flipud(index);\n\ntotal = sum(evalues);\nrlvm = min(find(cumsum(evalues) >= (total*maxpercent)));\n\nif isempty(rlvm)\t\t\t% in case percentage was choosen ober 100 %,\n\trlvm = length(evalues); % return all eigenvalues\nend\n\nfrvals = evalues(1:rlvm);\n\nif n>m\n\tfrvecs = Q(:, index(1:rlvm));\n\ttrnsfrmd=data*frvecs;\n else\n \tscalefac = 1./ sqrt(evalues(1:rlvm));\n \tfor i = 1:rlvm\n \t\tP(:,i) = Q(:,index(i)) * scalefac(i);\n \tend\n \tfrvecs = data' * P; % '\n\ttrnsfrmd=C*P;\nend\n\nif silent~=1\n\tbar(100*frvals/total);\n\ttitle('Eigenvalues in percent');\nend\n\n\nfunction printline(string)\nglobal silent\nif silent~=1\n\tdisp(string)\nend\n\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/utils/TSTOOLpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7619197508532846}} {"text": "function [xnew, Vnew, loglik, VVnew] = kalman_update(A, C, Q, R, y, x, V, varargin)\n% KALMAN_UPDATE Do a one step update of the Kalman filter\n% [xnew, Vnew, loglik] = kalman_update(A, C, Q, R, y, x, V, ...)\n%\n% INPUTS:\n% A - the system matrix\n% C - the observation matrix \n% Q - the system covariance \n% R - the observation covariance\n% y(:) - the observation at time t\n% x(:) - E[X | y(:, 1:t-1)] prior mean\n% V(:,:) - Cov[X | y(:, 1:t-1)] prior covariance\n%\n% OPTIONAL INPUTS (string/value pairs [default in brackets])\n% 'initial' - 1 means x and V are taken as initial conditions (so A and Q are ignored) [0]\n% 'u' - u(:) the control signal at time t [ [] ]\n% 'B' - the input regression matrix\n%\n% OUTPUTS (where X is the hidden state being estimated)\n% xnew(:) = E[ X | y(:, 1:t) ] \n% Vnew(:,:) = Var[ X(t) | y(:, 1:t) ]\n% VVnew(:,:) = Cov[ X(t), X(t-1) | y(:, 1:t) ]\n% loglik = log P(y(:,t) | y(:,1:t-1)) log-likelihood of innovatio\n\n% set default params\nu = [];\nB = [];\ninitial = 0;\n\nargs = varargin;\nfor i=1:2:length(args)\n switch args{i}\n case 'u', u = args{i+1};\n case 'B', B = args{i+1};\n case 'initial', initial = args{i+1};\n otherwise, error(['unrecognized argument ' args{i}])\n end\nend\n\n% xpred(:) = E[X_t+1 | y(:, 1:t)]\n% Vpred(:,:) = Cov[X_t+1 | y(:, 1:t)]\n\nif initial\n if isempty(u)\n xpred = x;\n else\n xpred = x + B*u;\n end\n Vpred = V;\nelse\n if isempty(u)\n xpred = A*x;\n else\n xpred = A*x + B*u;\n end\n Vpred = A*V*A' + Q;\nend\n\ne = y - C*xpred; % error (innovation)\nn = length(e);\nss = length(A);\nS = C*Vpred*C' + R;\nSinv = inv(S);\nss = length(V);\nloglik = gaussian_prob(e, zeros(1,length(e)), S, 1);\nK = Vpred*C'*Sinv; % Kalman gain matrix\n% If there is no observation vector, set K = zeros(ss).\nxnew = xpred + K*e;\nVnew = (eye(ss) - K*C)*Vpred;\nVVnew = (eye(ss) - K*C)*A*V;\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/kalman_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7619197448743759}} {"text": "% stein9 0-1 integer program from MIPLIB 2.0 by George Nemhauser et al.,\n% solving a nine item Steiner triple system\n% See, e.g., http://miplib.zib.de/miplib2/miplib/stein9.mps.gz\n\nclear;\n\n% the (dense) 0-1 matrix with the constraints\n% the first twelve constraints are of the form \n% the last constraints gives a trivial bound on the objective and is actually redundant\nmatrix = [\n0, 1, 1, 1, 0, 0, 0, 0, 0;...\n1, 0, 1, 0, 1, 0, 0, 0, 0;...\n1, 1, 0, 0, 0, 1, 0, 0, 0;...\n0, 0, 0, 0, 1, 1, 1, 0, 0;...\n0, 0, 0, 1, 0, 1, 0, 1, 0;...\n0, 0, 0, 1, 1, 0, 0, 0, 1;...\n1, 0, 0, 0, 0, 0, 0, 1, 1;...\n0, 1, 0, 0, 0, 0, 1, 0, 1;...\n0, 0, 1, 0, 0, 0, 1, 1, 0;...\n1, 0, 0, 1, 0, 0, 1, 0, 0;...\n0, 1, 0, 0, 1, 0, 0, 1, 0;...\n0, 0, 1, 0, 0, 1, 0, 0, 1;...\n1, 1, 1, 1, 1, 1, 1, 1, 1;...\n];\n\n% all constraints are of the type a_1*x_1+...+a9*x_9 >= b\n% In SCIP, constraints are represented as left hand side <= linear sum <= right hand side\n% Hence, the left hand sides are all finite, the right hand sides are plus infinity\nlhs = [1,1,1,1,1,1,1,1,1,1,1,1,4]';\nrhs = [1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20,1e+20]';\n\n% the variables are binary, hence, the lower bounds are zero, the upper bounds are one\nlb = [0,0,0,0,0,0,0,0,0]';\nub = [1,1,1,1,1,1,1,1,1]';\n\n% all variables are binary decision variables (you put an item into the system or not)\n% the goal is to minimize the number of used variables/items\nvartype = ['b','b','b','b','b','b','b','b','b'];\nobj = [1,1,1,1,1,1,1,1,1]';\nobjsense = 'min';\n\n% call SCIP\n[bestsol, objval] = scip(matrix, lhs, rhs, obj, lb, ub, vartype, objsense);\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/scipoptsuite-3.0.2/scip-3.0.2/interfaces/matlab/stein9_ip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7619197428814064}} {"text": "function C = cumsummat(N, dom, disc)\n%CUMSUMMAT Indefinite integration matrix.\n% C = CUMSUMMAT(N) returns the NxN indefinite integration matrix associated\n% with the Chebyshev spectral collocation method at second-kind Chebyshev\n% points. By convection, the arbitrary constant is chosen so that the result\n% is zero at -1. See CHEBCOLLOC2.CUMSUMMAT for further details.\n%\n% D = CUMSUMMAT(N, DOM) scales the indefinite integration matrix D to the\n% domain DOM. DOM should be a 1x2 vector.\n%\n% D = CUMSUMMAT(N, DOM, DISC) or CUMSUMMAT(N, DISC) returns the indefinite\n% integration matrix associated with the OPDISCRETIZATION DISC.\n%\n% See also CUMSUM, CHEBCOLLOC2.DIFFMAT, DIFFMAT.\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 the inputs:\nif ( (nargin == 2) )\n if ( isa(dom, 'function_handle') || ischar(dom) )\n disc = dom;\n dom = cheboppref().domain;\n else\n disc = chebcolloc2();\n end\nelseif ( nargin == 1 )\n disc = chebcolloc2();\n dom = cheboppref().domain;\nend\n% Ensure DISC is a discretization:\nif ( ischar(disc) )\n disc = str2func(disc);\nend\nif ( isa(disc, 'function_handle') )\n disc = disc();\nend\n% No breakpoints allowed:\nif ( numel(dom) > 2 )\n dom = dom([1 end]);\n warning('CHEBFUN:cumsummat:noBreaks', ...\n 'CUMSUMMAT does not support domains with breakpoints.');\nend\n\n%% Call DISC.DIFFMAT(N) and scale appropriately.\nscl = .5*(dom(end) - dom(1));\nC = scl*disc.cumsummat(N);\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/cumsummat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7619008951997369}} {"text": "function a = gfpp_inverse ( n, alpha )\n\n%*****************************************************************************80\n%\n%% GFPP_INVERSE returns the inverse of the GFPP matrix.\n%\n% Example:\n%\n% N = 5, ALPHA = 1\n%\n% 0.5000 -0.2500 -0.1250 -0.0625 -0.0625\n% 0 0.5000 -0.2500 -0.1250 -0.1250\n% 0 0 0.5000 -0.2500 -0.2500\n% 0 0 0 0.5000 -0.5000\n% 0.5000 0.2500 0.1250 0.0625 0.0625\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real ALPHA, determines subdiagonal elements.\n%\n% Output, real A(N,N), the inverse matrix.\n%\n [ p, l, u ] = gfpp_plu ( n, alpha );\n \n p_inverse = p';\n\n l_inverse = tri_l1_inverse ( n, l );\n\n u_inverse = tri_u_inverse ( n, u );\n\n a = u_inverse * l_inverse * p_inverse;\n \n return\nend\n", "meta": {"author": "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/gfpp_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7619008873514552}} {"text": "function a = daub4_matrix ( n )\n\n%*****************************************************************************80\n%\n%% DAUB4_MATRIX returns the DAUB4 matrix.\n%\n% Discussion:\n%\n% The DAUB4 matrix is the Daubechies wavelet transformation matrix\n% with 4 coefficients.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be at least 4, and a multiple of 2.\n%\n% Output, real A(N,N), the matrix.\n%\n c = [ 0.4829629131445341E+00; ...\n 0.8365163037378079E+00; ...\n 0.2241438680420133E+00; ...\n -0.1294095225512603E+00 ];\n\n if ( n < 4 || mod ( n, 2 ) ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DAUB4_MATRIX - Fatal error!\\n' );\n fprintf ( 1, ' N must be at least 4 and a multiple of 2.\\n' );\n error ( 'DAUB4_MATRIX - Fatal error!' );\n end\n\n a = zeros ( n, n );\n\n for i = 1 : 2 : n - 1\n\n a(i,i) = c(1);\n a(i,i+1) = c(2);\n a(i,i4_wrap(i+2,1,n)) = c(3);\n a(i,i4_wrap(i+3,1,n)) = c(4);\n\n a(i+1,i) = c(4);\n a(i+1,i+1) = - c(3);\n a(i+1,i4_wrap(i+2,1,n)) = c(2);\n a(i+1,i4_wrap(i+3,1,n)) = - c(1);\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wavelet/daub4_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7619008837123881}} {"text": "function [V_sorted, S_sorted] = sorted_eig(X, direction)\n%SORTED_EIG Compute the sorted eigenvalue decomposition of a square matrix\n%\n% Inputs:\n% X: matrix to decompose\n% direction: 'ascend','descend' for ordering of eigenvectors and\n% eigenvalues\n%\n% Outputs:\n% V_sorted: matrix of eigenvectors sorted according to the\n% eigenvalues\n% S_sorted: diagonal matrix of sorted eigenvalues\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% SORTED_EIG.M - 5/10/2016\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% \n\nif nargin<2, direction = 'descend'; end\n\nif size(X,1) ~= size(X,2)\n error('input matrix should be square')\nend\n\n[V, S] = eig(X);\n[~, perm] = sort(diag(S), 1, direction);\nS_sorted = S(perm, perm); V_sorted = V(:, perm);\n\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Array-Processing", "sha": "f08bed9b80ce580f9056fd6573ab0c08588ebc11", "save_path": "github-repos/MATLAB/polarch-Spherical-Array-Processing", "path": "github-repos/MATLAB/polarch-Spherical-Array-Processing/Spherical-Array-Processing-f08bed9b80ce580f9056fd6573ab0c08588ebc11/sorted_eig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7618808225074817}} {"text": "function a = lock ( n )\n\n%*****************************************************************************80\n%\n%% LOCK returns the number of codes for a lock with N buttons.\n%\n% Discussion:\n%\n% A button lock has N numbered buttons. To open the lock, groups\n% of buttons must be pressed in the correct order. Each button\n% may be pushed no more than once. Thus, a code for the lock is\n% an ordered list of the groups of buttons to be pushed.\n%\n% For this discussion, we will assume that EVERY button is pushed\n% at some time, as part of the code. To count the total number\n% of codes, including those which don't use all the buttons, then\n% the number is 2 * A(N), or 2 * A(N) - 1 if we don't consider the\n% empty code to be valid.\n%\n% Examples:\n%\n% If there are 3 buttons, then there are 13 possible \"full button\" codes:\n%\n% (123)\n% (12) (3)\n% (13) (2)\n% (23) (1)\n% (1) (23)\n% (2) (13)\n% (3) (12)\n% (1) (2) (3)\n% (1) (3) (2)\n% (2) (1) (3)\n% (2) (3) (1)\n% (3) (1) (2)\n% (3) (2) (1)\n%\n% and, if we don't need to push all the buttons, every \"full button\" code above\n% yields a distinct \"partial button\" code by dropping the last set of buttons:\n%\n% ()\n% (12)\n% (13)\n% (23)\n% (1)\n% (2)\n% (3)\n% (1) (2)\n% (1) (3)\n% (2) (1)\n% (2) (3)\n% (3) (1)\n% (3) (2)\n%\n% First values:\n%\n% N A(N)\n% 0 1\n% 1 1\n% 2 3\n% 3 13\n% 4 75\n% 5 541\n% 6 4683\n% 7 47293\n% 8 545835\n% 9 7087261\n% 10 102247563\n%\n% Recursion:\n%\n% A(I) = sum ( 0 <= J < I ) Binomial ( I, N-J ) * A(J)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Velleman, Gregory Call,\n% Permutations and Combination Locks,\n% Mathematics Magazine,\n% Volume 68, Number 4, October 1995, pages 243-253.\n%\n% Parameters:\n%\n% Input, integer N, the maximum number of lock buttons.\n%\n% Output, integer A(1:N+1), the number of lock codes.\n%\n if ( n < 0 )\n a = [];\n return\n end\n\n a(1) = 1;\n\n for i = 1 : n\n a(i+1) = 0;\n for j = 0 : i-1\n a(i+1) = a(i+1) + i4_choose ( i, i-j ) * a(j+1);\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/lock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7617963619171614}} {"text": "function pols = ortho2eva0 ( mmax, z )\n\n%*****************************************************************************80\n%\n%% ORTHO2EVA0 evaluates the orthonormal polynomials on the triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 28 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, integer MMAX, the maximum order to which the polynomials are\n% to be evaluated.\n%\n% Input, real Z(2), the coordinates of the evaluation point.\n%\n% Output, real POLS((mmax+1)*(mmax+2)/2), the orthogonal\n% polynomials evaluated at the point Z.\n%\n zero = 0.0;\n sqrt2 = sqrt ( 2.0 );\n sqrt3 = sqrt ( 3.0 );\n r11 = -1.0 / 3.0;\n r12 = -1.0 / sqrt3;\n r21 = - 1.0 / 3.0;\n r22 = 2.0 / sqrt3;\n\n a = z(1);\n b = z(2);\n%\n% Map the reference triangle to the right\n% triangle with the vertices (-1,-1), (1,-1), (-1,1)\n%\n x = r11 + r12 * b + a;\n y = r21 + r22 * b;\n%\n% Evaluate the Koornwinder's polynomials via the three term recursion.\n%\n par1 = ( 2.0 * x + 1.0 + y ) / 2.0;\n par2 = ( 1.0 - y ) / 2.0;\n f1 = klegeypols ( par1, par2, mmax );\n\n f2 = zeros(mmax+1,mmax+1);\n for m = 0 : mmax\n par1 = 2 * m + 1;\n f2(1:mmax+1,m+1) = kjacopols ( y, par1, zero, mmax - m );\n end\n\n npols = ( ( mmax + 1 ) * ( mmax + 2 ) ) / 2;\n pols = zeros(npols,1);\n\n kk = 0;\n for m = 0 : mmax\n for n = 0 : m\n kk = kk + 1;\n%\n% Evaluate the polynomial (m-n, n)\n%\n pols(kk) = f1(m-n+1) * f2(n+1,m-n+1);\n%\n% Normalize.\n%\n scale = sqrt ...\n ( ...\n ( ...\n ( 1 + ( m - n ) + n ) * ...\n ( 1 + ( m - n ) + ( m - n ) ) ...\n ) / sqrt3 ...\n );\n\n pols(kk) = pols(kk) * scale;\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_symq_rule/ortho2eva0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7617963586398704}} {"text": "function cgs_test ( )\n\n%*****************************************************************************80\n%\n%% CGS_TEST tests CGS.\n% \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CGS_TEST:\\n' );\n fprintf ( 1, ' CGS uses the Conjugate Gradient Squared \\n' );\n fprintf ( 1, ' iterative method to approximate the solution \\n' );\n fprintf ( 1, ' of a linear system A * x = b.\\n' );\n\n n = 10;\n\n A = zeros ( n, n );\n\n for i = 1 : n\n A(i,i) = 2.0;\n end\n for i = 1 : n-1\n A(i,i+1) = -1;\n end\n for i = 2 : n\n A(i-1,i) = -1;\n end\n x = [ 1 : n ]';\n b = A * x;\n x = ones ( n, 1 );\n\n M = 0;\n max_it = 10;\n tol = 0.0001;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the order of the system is N = %d\\n', n );\n fprintf ( 1, ' The matrix A is the simple tridiagonal -1, 2, -1.\\n' );\n fprintf ( 1, ' The correct solution is x = [ 1, 2, ..., n].\\n' );\n fprintf ( 1, ' The right hand side b is determined by computing A * x.\\n' );\n fprintf ( 1, ' The exact x is then replaced by a vector of all 1''s for\\n' );\n fprintf ( 1, ' use as a starting guess.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Other parameters are set as follows:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The maximum number of steps is %d.\\n', max_it );\n fprintf ( 1, ' The error tolerance is %f\\n', tol );\n\n [ x, error_norm, iter, flag ] = cgs ( A, x, b, M, max_it, tol );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The CGS routine has returned with FLAG = %d\\n', flag );\n if ( flag == 0 )\n fprintf ( 1, ' This indicates that the iteration has converged.\\n' );\n elseif ( flag == 1 ) \n fprintf ( 1, ' This indicates that the iteration has NOT converged.\\n' );\n elseif ( flag == -1 ) \n fprintf ( 1, ' This indicates that the iteration has broken down.\\n' );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of iterations taken was %d\\n', iter );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The L2 norm of the error per iteration:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : iter\n fprintf ( 1, ' %4d %f\\n', i, error_norm(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The computed solution vector X:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %f\\n', i, x(i) );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CGS_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/templates/cgs_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.76178784377944}} {"text": "function tw = trigauss ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% TRIGAUSS computes a trigonometric gaussian quadrature formula.\n%\n% Discussion:\n%\n% This function computes the N+1 angles and weights of a trigonometric \n% gaussian quadrature formula on [ALPHA,BETA], with\n% 0 < BETA - ALPHA <= pi.\n%\n% The formula integrates the canonical trigonometric basis with accuracy \n% from about 10^(-15) (for small omega) to about 10^(-13) (for omega --> pi) \n% up to N = 300.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Gaspare Da Fies, Alvise Sommariva, Marco Vianello\n%\n% Parameters:\n%\n% Input, integer N, the trigonometric degree of exactness.\n%\n% Input, real ALPHA, BETA, the angular interval.\n% 0 < BETA - ALPHA <= pi.\n%\n% Output, real TW(N+1,2) array of angles and weights.\n%\n np1 = n + 1;\n%\n% Compute the half angle subtended by the circle segment.\n%\n omega = ( beta - alpha ) / 2.0;\n%\n% Compute the modified Chebyshev recursion coefficients.\n%\n ab = r_subchebyshev ( np1, omega );\n%\n% Compute the quadrature rule.\n%\n xw_symm_eigw = SymmMw ( np1, ab );\n tw = trigauss_conversion ( xw_symm_eigw, omega );\n%\n% Adjust angles from the reference system to the physical system.\n%\n tw(:,1) = tw(:,1) + ( beta + alpha ) / 2.0;\n\n return\nend\nfunction ab = r_subchebyshev ( n, omega )\n\n%*****************************************************************************80\n%\n%% R_SUBCHEBYSHEV computes the modified Chebyshev recursion coefficients.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n% \n% Gerard Meurant, Alvise Sommariva \n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real OMEGA, the arc angle.\n%\n% Output, real AB(NN,2), the coefficients of the three term recursion.\n% The dimension NN is N + 1 if N is odd, or N if N is even.\n%\n N = n;\n n = n - 1;\n\n if rem ( N, 2 ) == 1\n NN = N + 1; \n nn = n + 1;\n else\n NN = N; \n nn = n;\n end\n%\n% Compute the moments.\n%\n mom = fast_moments_computation ( omega, 2 * nn + 1 );\n%\n% Recurrence coefficients of the monic Chebyshev polynomials.\n%\n abm(:,1) = zeros ( 2 * nn + 1, 1 );\n abm(:,2) = 0.25 * ones ( 2 * nn + 1, 1 ); \n abm(1,2) = pi; \n abm(2,2) = 0.5;\n%\n% Recurrence coefficients for the monic orthogonal polynomials \n% with respect to the weight function\n% w(x) = 2 * sin ( omega / 2 ) / sqrt ( 1 - sin^2 ( omega / 2 ) * x^2 )\n% by the modified Chebyshev algorithm.\n%\n% ab = chebyshev ( NN + 1, mom, abm );\n ab = fast_chebyshev ( NN, mom, abm );\n\n return\nend\nfunction ab = fast_chebyshev ( N, mom, abm )\n\n%*****************************************************************************80\n%\n%% SUBP_MOD_CHEBYSHEV carries out a modified Chebyshev algorithm.\n%\n% Discussion:\n%\n% This works only for the subperiodic weight function.\n%\n% This is a simplified version of a routine by Walter Gautschi.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Parameters:\n%\n% Input, integer N, ?\n%\n% Input, real MOM(2*N), ?\n%\n% Input, real ABM(?), ?\n%\n% Output, real AB(N,2), ?\n%\n ab = zeros(N,2);\n sig = zeros(N+1,2*N);\n\n ab(1,2) = mom(1);\n\n sig(1,1:2*N) = 0; \n sig(2,:) = mom(1:2*N);\n\n for n = 3:N+1\n for m = n-1:2*N-n+2\n sig(n,m) = sig(n-1,m+1) + abm(m,2) * sig(n-1,m-1) - ab(n-2,2) * sig(n-2,m);\n end\n \n ab(n-1,2) = sig(n,n-1) / sig(n-1,n-2);\n end\n\n return\nend\nfunction mom = fast_moments_computation ( omega, n )\n\n%*****************************************************************************80\n%\n%% FAST_MOMENTS_COMPUTATION computes the moments.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Parameters:\n%\n% Input, real OMEGA, the arc angle.\n%\n% Input, integer N, the index of the highest moment to compute.\n%\n% Output, real MOM(1,N+1), the 0-th through N-th moments.\n%\n mom = zeros(1,n+1);\n%\n% Set the first moment.\n%\n mom(1) = 2.0 * omega;\n\n if ( 2 <= n )\n\n if ( omega <= 1/4*pi)\n l = 10;\n elseif ( omega <= 1/2*pi)\n l = 20;\n elseif ( omega <= 3/4*pi)\n l = 40;\n elseif ( omega == pi )\n l = 2*ceil(10*pi);\n else\n l = 2*ceil(10*pi/(pi-omega));\n end\n%\n% Auxilliary vectors.\n%\n temp=(2:2:n+2*l-2);\n temp2=temp.^2-1;\n%\n% Diagonals.\n%\n dl = 1/4 -1./(4*(temp-1));\n dc = 1/2 -1/sin(omega/2)^2 -1./(2*temp2);\n du = 1/4 +1./(4*(temp+1));\n\n d = 4*cos(omega/2)/sin(omega/2)./temp2';\n d(end) = d(end);\n%\n% Solve the tridiagonal system.\n%\n z = tridisolve ( dl(2:end), dc, du(1:end-1 ), d );\n%\n% Set the odd moments.\n%\n mom(3:2:n+1) = z(1:floor(n/2));\n\n end\n\n mom = mom';\n%\n% Normalize.\n%\n M = length ( mom );\n kk = 2.^(-((1:2:M)-2))';\n kk(1) = 1;\n v = ones(M,1);\n v(1:2:M) = kk;\n mom = v .* mom;\n\n return\nend\nfunction xw = SymmMw ( N, ab )\n\n%*****************************************************************************80\n%\n%% SYMMMW computes a quadrature rule for a symmetric weight function.\n%\n% Discussion:\n%\n% This function uses the reduced matrix and eig and\n% computation of weights with the 3-term recurrence.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Gerard Meurant, Alvise Sommariva\n%\n% Reference:\n%\n% Gerard Meurant, Alvise Sommariva,\n% Fast variants of the Golub and Welsch algorithm for symmetric \n% weight functions,\n% Submitted, 2012.\n%\n% Parameters:\n%\n% Input, integer N, the cardinality of the rule.\n%\n% Input, real AB(*,2), the 3-term recurrence for the orthogonal polynomials\n% same as in OPQ. Note that AB(1,2) is the 0th moment.\n%\n% Output, real XW(N,2), the nodes and weights of the quadrature rule.\n%\n N0 = size ( ab, 1 );\n\n if ( N0 < N )\n error('SymmMw: input array ab is too short')\n end\n\n na = norm(ab(:,1));\n\n if na > 0\n error('SymmMw: the weight function must be symmetric')\n end\n%\n% Computation of the reduced matrix in vectors (a,b)\n%\n if mod(N,2) == 0\n even = 1;\n Nc = N / 2;\n else\n even = 0;\n Nc = fix(N / 2) +1;\n end\n\n absd = ab(:,2);\n absq = sqrt(absd);\n\n a = zeros(1,Nc);\n b = a;\n\n switch even\n case 1\n % N even\n a(1) = absd(2);\n b(1) = absq(2) * absq(3);\n \n k = (2:Nc-1);\n a(k) = absd(2*k-1) + absd(2*k);\n b(k) = absq(2*k) .* absq(2*k+1);\n a(Nc) = absd(N) + absd(N-1);\n start = 1;\n \n J = diag(a) + diag(b(1:Nc-1),1) + diag(b(1:Nc-1),-1);\n t = sort(eig(J));\n w = weights_3t(t',a,b);\n%\n% w are the squares of the first components\n%\n w = w' / 2;\n case 0\n % N odd\n a(1) = absd(2);\n b(1) = absq(2) * absq(3);\n \n k = (2:Nc-1);\n a(k) = absd(2*k-1) + absd(2*k);\n b(k) = absq(2*k) .* absq(2*k+1);\n a(Nc) = absd(N);\n start = 2;\n%\n% the first node must be zero\n%\n J = diag(a) + diag(b(1:Nc-1),1) + diag(b(1:Nc-1),-1);\n t = sort(eig(J));\n t(1) = 0;\n w = weights_3t(t',a,b);\n w = [w(1); w(2:end)' / 2];\n otherwise\n error('this is not possible')\n end\n\n xwp = sqrt(t);\n\n xw(:,1) = [-xwp(end:-1:start,1); xwp];\n xw(:,2) = ab(1,2) * ([w(end:-1:start); w]);\n\n return\nend\nfunction tw = trigauss_conversion ( xw, omega )\n\n%*****************************************************************************80\n%\n%% TRIGAUSS_CONVERSION ???\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Gaspare Da Fies, Alvise Sommariva, Marco Vianello\n%\n% Parameters:\n%\n% Input, real XW(?,2), ?\n%\n% Input, real OMEGA, the arc angle.\n%\n% Output, real TW(?,2), the angles and weights for the trigonometic\n% quadrature rule.\n%\n tw(:,1) = 2.0 * asin ( sin ( omega / 2.0 ) * xw(:,1) );\n tw(:,2) = xw(:,2);\n\n return\nend\nfunction w = weights_3t ( t, a, b )\n\n%*****************************************************************************80\n%\n%% WEIGHTS_3T computes squares of the 1st components of eigenvectors.\n%\n% Discussion:\n%\n% The results are computed from the 3-term recurrence relation of \n% the orthogonal polynomials.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Gerard Meurant, Alvise Sommariva\n%\n% Parameters:\n%\n% Input, real T(N), the nodes.\n%\n% Input, real A(N-1), B(N-1), the coefficients of the 3-term recurrence.\n%\n% Output, real W(N), the squares of the first components of the eigenvectors.\n%\n n = length ( t );\n\n P = zeros ( n, n );\n P(1,:) = ones ( 1, n );\n P(2,:) = ( t - a(1) ) / b(1);\n\n for k = 3 : n\n k1 = k - 1;\n k2 = k - 2;\n P(k,:) = ( ( t - a(k1) ) .* P(k1,:) - b(k2) * P(k2,:) ) / b(k1);\n end\n\n P2 = P .* P;\n\n w = 1.0 ./ sum ( P2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/trigauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7617878390686204}} {"text": "function fx = p47_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P47_FUN evaluates the integrand for problem 47.\n%\n% Discussion:\n%\n% The function is singular at the left endpoint.\n%\n% Interval:\n%\n% 0 <= x <= 1\n%\n% Integrand:\n%\n% sqrt ( x ) * ln ( x )\n%\n% Exact Integral:\n%\n% -4/9 = -0.4444...\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Piessens, Elise de Doncker-Kapenga,\n% Christian Ueberhuber, David Kahaner,\n% QUADPACK: A Subroutine Package for Automatic Integration,\n% Springer, 1983, page 101.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n fx(1:n) = sqrt ( x(1:n) ) .* log ( x(1:n) );\n\n i = find ( x == 0.0 );\n fx(i) = 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_int/p47_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7617878367132105}} {"text": "function line_ncc_rule_test02 ( )\n\n%*****************************************************************************80\n%\n%% LINE_NCC_RULE_TEST02 estimates the integral of exp(x) from 0 to 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 10 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = 0.0;\n b = +1.0;\n exact = exp ( b ) - exp ( a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' Use a sequence of NCC rules to compute an estimate Q\\n' );\n fprintf ( 1, ' of the integral:\\n' );\n fprintf ( 1, ' I = integral ( 0 <= x <= 1 ) exp(x) dx.\\n' );\n fprintf ( 1, ' The exact value is:\\n' );\n fprintf ( 1, ' I = %g\\n', exact );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Q |Q-I|\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : 22\n\n [ x, w ] = line_ncc_rule ( n, a, b );\n\n q = w(1:n)' * exp ( x(1:n) );\n error = abs ( exact - q );\n fprintf ( 1, ' %2d %14.6g %14.6g\\n', n, q, error );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/line_ncc_rule/line_ncc_rule_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7617878170732362}} {"text": "% sieveEr: returns a vector with prime numbers from 2 up to N\n% assumes: N >= 2\nfunction y = sieveER(N)\n % precondition\n assert(N >= 2,\"N must be >= 2\")\n tmp = [false,true(1,N-1)]; % indexed by all numbers from 2 up to N\n \n % labels all composite number with false\n for i = 2 : 1 : sqrt(N)\n if (tmp(i))\n for j = i^2 : i : N\n tmp(j) = false;\n endfor\n endif\n endfor\n \n % fills up all prime numbers in vector y\n y = find(tmp);\n \nendfunction\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/Sieve_of_Eratosthenes/sieveER.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7617799544067065}} {"text": "% Prim's minimal spanning tree algorithm\n% Prim's alg idea:\n% start at any node, find closest neighbor and mark edges\n% for all remaining nodes, find closest to previous cluster, mark edge\n% continue until no nodes remain\n%\n% INPUTS: graph defined by adjacency matrix, nxn\n% OUTPUTS: matrix specifying minimum spanning tree (subgraph), nxn\n%\n% Other routines used: isConnected.m\n% GB: Oct 7, 2012\n\nfunction tr = minSpanTree(adj)\n\n% check if graph is connected:\nif not(isConnected(adj)); printf('This graph is not connected. No spanning tree exists.\\n'); return; end\n\nn = length(adj); % number of nodes\ntr = zeros(n); % initialize tree\n\nadj(find(adj==0))=inf; % set all zeros in the matrix to inf\n\nconn_nodes = 1; % nodes part of the min-span-tree\nrem_nodes = [2:n]; % remaining nodes\n\nwhile length(rem_nodes)>0\n \n [minlink]=min(min(adj(conn_nodes,rem_nodes)));\n ind=find(adj(conn_nodes,rem_nodes)==minlink);\n\n [ind_i,ind_j] = ind2sub([length(conn_nodes),length(rem_nodes)],ind(1));\n\n i=conn_nodes(ind_i); j=rem_nodes(ind_j); % gets back to adj indices\n tr(i,j)=1; tr(j,i)=1;\n conn_nodes = [conn_nodes j];\n rem_nodes = setdiff(rem_nodes,j);\n \nend", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/minSpanTree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7617492910835583}} {"text": "function [ r, s, area ] = node_reference_t3 ( )\n\n%*****************************************************************************80\n%\n%% NODE_REFERENCE_T3 returns the basis nodes for the 3 node triangle.\n%\n% Reference Element T3:\n%\n% |\n% 1 3\n% | |\\\n% | | \\\n% S | \\\n% | | \\\n% | | \\\n% 0 1-----2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real R(3), S(3), the coordinates of the basis nodes.\n%\n% Output, real AREA, the area of the element.\n%\n r(1:3) = [ 0.0, 1.0, 0.0 ];\n s(1:3) = [ 0.0, 0.0, 1.0 ];\n\n area = 0.5;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/node_reference_t3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.761633619312221}} {"text": "function score = mutual_info_score(i,si,j,sj,data)\n% G = mutual_info_score(i,si,j,sj,data)\n% Only for tabular node which values are 1,2,...,size .\n% si is size of node i, sj is size of node j.\n% data(i,m) is the node i in the case m.\n% \n% Ref :\n% C. Chow and C. Liu (1968). Approximating discrete probability distributions with dependence trees. \n% IEEE Transactions on Information Theory, 14(3):462--467, May 1968.\n%\n% francois.olivier.c.h@gmail.com, philippe.leray@univ-nantes.fr, wangxiangyang@sjtu.edu.cn\n\n[n N]=size(data);\nNj=hist(data(j,:),1:sj);\nNi=hist(data(i,:),1:si);\nNiNj=Ni'*Nj;\n\nfor k=1:si\n ind=find(data(i,:)==k) ;\n Nij(k,:) = hist(data(j,ind),1:sj);\nend\n\n% sommons les valeurs non-infinies:\nind=find(NiNj~=0 & Nij~=0);\nscore=sum(sum(Nij(ind).*log(N*Nij(ind)./NiNj(ind))/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/mutual_info_score.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7616087830059922}} {"text": "function [ H, f, c ] = trifbank( M, K, R, fs, h2w, w2h )\n% TRIFBANK Triangular filterbank.\n%\n% [H,F,C]=TRIFBANK(M,K,R,FS,H2W,W2H) returns matrix of M triangular filters \n% (one per row), each K coefficients long along with a K coefficient long \n% frequency vector F and M+2 coefficient long cutoff frequency vector C. \n% The triangular filters are between limits given in R (Hz) and are \n% uniformly spaced on a warped scale defined by forward (H2W) and backward \n% (W2H) warping functions.\n%\n% Inputs\n% M is the number of filters, i.e., number of rows of H\n%\n% K is the length of frequency response of each filter \n% i.e., number of columns of H\n%\n% R is a two element vector that specifies frequency limits (Hz), \n% i.e., R = [ low_frequency high_frequency ];\n%\n% FS is the sampling frequency (Hz)\n%\n% H2W is a Hertz scale to warped scale function handle\n%\n% W2H is a wared scale to Hertz scale function handle\n%\n% Outputs\n% H is a M by K triangular filterbank matrix (one filter per row)\n%\n% F is a frequency vector (Hz) of 1xK dimension\n%\n% C is a vector of filter cutoff frequencies (Hz), \n% note that C(2:end) also represents filter center frequencies,\n% and the dimension of C is 1x(M+2)\n%\n% Example\n% fs = 16000; % sampling frequency (Hz)\n% nfft = 2^12; % fft size (number of frequency bins)\n% K = nfft/2+1; % length of each filter\n% M = 23; % number of filters\n%\n% hz2mel = @(hz)(1127*log(1+hz/700)); % Hertz to mel warping function\n% mel2hz = @(mel)(700*exp(mel/1127)-700); % mel to Hertz warping function\n%\n% % Design mel filterbank of M filters each K coefficients long,\n% % filters are uniformly spaced on the mel scale between 0 and Fs/2 Hz\n% [ H1, freq ] = trifbank( M, K, [0 fs/2], fs, hz2mel, mel2hz );\n%\n% % Design mel filterbank of M filters each K coefficients long,\n% % filters are uniformly spaced on the mel scale between 300 and 3750 Hz\n% [ H2, freq ] = trifbank( M, K, [300 3750], fs, hz2mel, mel2hz );\n%\n% % Design mel filterbank of 18 filters each K coefficients long, \n% % filters are uniformly spaced on the Hertz scale between 4 and 6 kHz\n% [ H3, freq ] = trifbank( 18, K, [4 6]*1E3, fs, @(h)(h), @(h)(h) );\n%\n% hfig = figure('Position', [25 100 800 600], 'PaperPositionMode', ...\n% 'auto', 'Visible', 'on', 'color', 'w'); hold on; \n% subplot( 3,1,1 ); \n% plot( freq, H1 );\n% xlabel( 'Frequency (Hz)' ); ylabel( 'Weight' ); set( gca, 'box', 'off' ); \n% \n% subplot( 3,1,2 );\n% plot( freq, H2 );\n% xlabel( 'Frequency (Hz)' ); ylabel( 'Weight' ); set( gca, 'box', 'off' ); \n% \n% subplot( 3,1,3 ); \n% plot( freq, H3 );\n% xlabel( 'Frequency (Hz)' ); ylabel( 'Weight' ); set( gca, 'box', 'off' ); \n%\n% Reference\n% [1] Huang, X., Acero, A., Hon, H., 2001. Spoken Language Processing: \n% A guide to theory, algorithm, and system development. \n% Prentice Hall, Upper Saddle River, NJ, USA (pp. 314-315).\n\n% Author Kamil Wojcicki, UTD, June 2011\n\n\n if( nargin~= 6 ), help trifbank; return; end; % very lite input validation\n\n f_min = 0; % filter coefficients start at this frequency (Hz)\n f_low = R(1); % lower cutoff frequency (Hz) for the filterbank \n f_high = R(2); % upper cutoff frequency (Hz) for the filterbank \n f_max = 0.5*fs; % filter coefficients end at this frequency (Hz)\n f = linspace( f_min, f_max, K ); % frequency range (Hz), size 1xK\n fw = h2w( f );\n\n % filter cutoff frequencies (Hz) for all filters, size 1x(M+2)\n c = w2h( h2w(f_low)+[0:M+1]*((h2w(f_high)-h2w(f_low))/(M+1)) );\n cw = h2w( c );\n\n H = zeros( M, K ); % zero otherwise\n for m = 1:M \n\n % implements Eq. (6.140) on page 314 of [1] \n % k = f>=c(m)&f<=c(m+1); % up-slope\n % H(m,k) = 2*(f(k)-c(m)) / ((c(m+2)-c(m))*(c(m+1)-c(m)));\n % k = f>=c(m+1)&f<=c(m+2); % down-slope\n % H(m,k) = 2*(c(m+2)-f(k)) / ((c(m+2)-c(m))*(c(m+2)-c(m+1)));\n\n % implements Eq. (6.141) on page 315 of [1]\n k = f>=c(m)&f<=c(m+1); % up-slope\n H(m,k) = (f(k)-c(m))/(c(m+1)-c(m));\n k = f>=c(m+1)&f<=c(m+2); % down-slope\n H(m,k) = (c(m+2)-f(k))/(c(m+2)-c(m+1));\n \n end\n\n % H = H./repmat(max(H,[],2),1,K); % normalize to unit height (inherently done)\n % H = H./repmat(trapz(f,H,2),1,K); % normalize to unit area \n\n\n% EOF\n", "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/mfcc/trifbank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7615399629478533}} {"text": "function x = pwPoly4(tGrid,xGrid,dxGrid,t)\n% x = pwPoly4(tGrid,xGrid,t)\n%\n% This function does piece-wise quadratic interpolation of a set of data.\n%\n% INPUTS:\n% tGrid = [1, 2*n-1] = time at each grid point\n% xGrid = [m, 2*n-1] = function value at each grid point\n% dxGrid = [m, 2*n-1] = function slope at each grid point\n% t = [1, k] = vector of query times (must be contained within tGrid)\n%\n% OUTPUTS:\n% x = [m, k] = function value at each query time\n%\n% NOTES: \n% If t is out of bounds, then all corresponding values for x are replaced\n% with NaN\n%\n\nnGrid = length(tGrid);\nif mod(nGrid-1,2)~=0 || nGrid < 3\n error('The number of grid-points must be odd and at least 3');\nend\n\n% Figure out sizes\nn = floor((length(tGrid)-1)/2);\nm = size(xGrid,1);\nk = length(t);\nx = zeros(m, k);\n\n% Figure out which segment each value of t should be on\nedges = [-inf, tGrid(1:2:end), inf];\n[~, bin] = histc(t,edges);\n\n% Loop over each quartic segment\nfor i=1:n\n idx = bin==(i+1);\n if sum(idx) > 0\n gridIdx = 2*(i-1) + [1,2,3];\n x(:,idx) = quartInterp(...\n tGrid(gridIdx), ...\n xGrid(:,gridIdx), ...\n dxGrid(:,gridIdx), ...\n t(idx));\n end\nend\n\n% Replace any out-of-bounds queries with NaN\noutOfBounds = bin==1 | bin==(n+2);\nx(:,outOfBounds) = nan;\n\nend\n\n\nfunction x = quartInterp(tGrid,xGrid,dxGrid,t)\n%\n% This function computes the interpolant over a single interval\n%\n% INPUTS:\n% tGrid = [1, 3] = time at endpoints and midpoint\n% xGrid = [m, 3] = function at endpoints and midpoint\n% dxGrid = [m, 3] = derivative at endpoints and midpoint\n% t = [1, p] = query times, spanned by tGrid\n%\n% OUTPUTS:\n% x = [m, p] = function at query times\n%\n\n% Rescale the query points to be on the domain [-1,1]\nt = 2*(t-tGrid(1))/(tGrid(3)-tGrid(1)) - 1; \n\n% Unpack function and derivative:\nxLow = xGrid(:,1);\nxMid = xGrid(:,2);\nxUpp = xGrid(:,3);\ndxLow = dxGrid(:,1);\ndxUpp = dxGrid(:,3);\n\n% Compute the coefficients:\na = dxUpp/4 - dxLow/4 - xLow/2 + xMid - xUpp/2;\nb = dxLow/4 + dxUpp/4 + xLow/4 - xUpp/4;\nc = dxLow/4 - dxUpp/4 + xLow - 2*xMid + xUpp;\nd = (3*xUpp)/4 - dxUpp/4 - (3*xLow)/4 - dxLow/4;\ne = xMid;\n\n% Evaluate the polynomial for each dimension of the function:\np = length(t);\nm = size(xGrid,1);\nx = zeros(m,p);\nfor i=1:m\n x(i,:) = e(i,:) + t.*(d(i,:) + t.*(c(i,:) + t.*(b(i,:) + t.*a(i,:))));\nend\n\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/pwPoly/pwPoly4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7615399603514762}} {"text": "% This example demonstrates how to use the auxilliary routine\n% (postprocess.m) to calculate the four remaining field\n% components (Hz, Ex, Ey, Ez) once the transverse magnetic\n% field components (Hx, Hy) are known. The waveguide\n% considered here is a uniaxial channel waveguide with the\n% c-axis oriented at pi/4 relative to the x-y axes.\n\nn1 = 1.55;\nn2x = 2.156;\nn2y = 2.232;\nn2z = 2.232;\ntheta = pi/4;\n\ne2xx = n2x^2*cos(theta)^2 + n2y^2*sin(theta)^2;\ne2yy = n2y^2*cos(theta)^2 + n2x^2*sin(theta)^2;\ne2xy = cos(theta)*sin(theta)*(n2x^2-n2y^2);\ne2yx = e2xy;\n\nRx = 0.30;\nRy = 0.20;\nside = 0.20;\n\ndx = 0.0025; % grid size (x)\ndy = dx; % grid size (y)\n\nlambda = 1.00; % wavelength\nnmodes = 1; % number of modes to compute\n\nfprintf (1,'generating index mesh...\\n');\n\n[x,y,xc,yc,nx,ny,epsxx,edges] = ...\n waveguidemeshfull([n1,sqrt(e2xx),n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsxy,edges] = ...\n waveguidemeshfull([0,sqrt(e2xy),0],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsyx,edges] = ...\n waveguidemeshfull([0,sqrt(e2yx),0],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsyy,edges] = ...\n waveguidemeshfull([n1,sqrt(e2yy),n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epszz,edges] = ...\n waveguidemeshfull([n1,n2z,n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n\n% Now we stretch out the mesh at the boundaries:\n[x,y,xc,yc,dx,dy] = stretchmesh(x,y,[80,80,80,80],[4,4,4,4]);\n\n[Hx,Hy,neff] = wgmodes (lambda, n2y, nmodes, dx, dy, epsxx, epsxy, epsyx, epsyy, epszz, '0000');\n\nfprintf(1,'neff = %7.5f\\n',neff);\n\n[Hz,Ex,Ey,Ez] = postprocess (lambda, neff, Hx, Hy, dx, dy, epsxx, epsxy, epsyx, epsyy, epszz, '0000');\n\nfigure(1);\n\nsubplot(231);\ncontourmode(x,y,Hx);\ntitle('Hx');\nfor v = edges, line(v{:}); end\n\nsubplot(232);\ncontourmode(x,y,Hy);\ntitle('Hy');\nfor v = edges, line(v{:}); end\n\nsubplot(233);\ncontourmode(x,y,Hz);\ntitle('Hz');\nfor v = edges, line(v{:}); end\n\nsubplot(234);\ncontourmode(x,y,Ex);\ntitle('Ex');\nfor v = edges, line(v{:}); end\n\nsubplot(235);\ncontourmode(x,y,Ey);\ntitle('Ey');\nfor v = edges, line(v{:}); end\n\nsubplot(236);\ncontourmode(x,y,Ez);\ntitle('Ez');\nfor v = edges, line(v{:}); end\n\nfigure(2);\n\nii = 1;\ncolormap(jet(256));\nhn = abs(interp2(y,x,Hy,side+Ry,0));\nen = abs(interp2(yc,xc,Ex,side+Ry,0));\n\nsubplot(231);\nimagemode(x,y,Hx/hn);\ntitle(sprintf('Hx (mode %d)',ii));\nfor v = edges, line(v{:}); end\n\nsubplot(232);\nimagemode(x,y,Hy/hn);\ntitle(sprintf('Hy (mode %d)',ii));\nfor v = edges, line(v{:}); end\n\nsubplot(233);\nimagemode(x,y,Hz/hn);\ntitle(sprintf('Hz (mode %d)',ii));\nfor v = edges, line(v{:}); end\n\nsubplot(234);\nimagemode(x,y,Ex/en);\ntitle(sprintf('Ex (mode %d)',ii));\nfor v = edges, line(v{:}); end\n\nsubplot(235);\nimagemode(x,y,Ey/en);\ntitle(sprintf('Ey (mode %d)',ii));\nfor v = edges, line(v{:}); end\n\nsubplot(236);\nimagemode(x,y,Ez/en);\ntitle(sprintf('Ez (mode %d)',ii));\nfor v = edges, line(v{:}); end\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/12734-waveguide-mode-solver/examples/fullvector_all_fields.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.761532878437215}} {"text": "function fx = p05_fx ( x )\n\n%*****************************************************************************80\n%\n%% P05_FX evaluates ( x + 3 ) * ( x - 1 )^2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(*), the point at which F is to be evaluated.\n%\n% Output, real FX(*), the value of the function at X.\n%\n fx = ( x + 3.0 ) .* ( x - 1.0 ) .* ( x - 1.0 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_zero/p05_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8918110353738528, "lm_q1q2_score": 0.7615288229597921}} {"text": "function [ f, d, s, t ] = cubic_value ( x )\n\n%*****************************************************************************80\n%\n%% CUBIC_VALUE evaluates a cubic function.\n%\n% Discussion:\n%\n% f(x) = x^3 - 7 x^2 + 10 x\n% d(x) = 3 x^2 - 14 x + 10\n% s(x) = 6 x - 14\n% t(x) = 6\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real F, D, S, T, the value and first three derivatives of\n% the cubic function.\n%\n\n%\n% If X is a vector, force it to be a column vector.\n%\n x = x ( : );\n\n f = 0.0 + x .* ( 10.0 + x .* ( - 7.0 + x * 1.0 ) );\n d = 10.0 + x .* ( - 14.0 + x * 3.0 );\n s = - 14.0 + x * 6.0;\n t = 6.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_cubic/cubic_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7613891231051536}} {"text": "function R=q2dcm(q)\n% Q2DCM(Q) converts quaternions into direction cosine matrices.\n%\n% The resultant DCM(s) will perform the same transformations as the\n% quaternion(s) in Q, i.e.:\n%\n% R*v = qvxform(q, v) \n%\n% where R is the DCM, V is a vector, and Q is the quaternion. Note that\n% for purposes of quaternion-vector multiplication, a vector is treated\n% as a quaterion with a scalar element of zero.\n%\n% If the input, Q, is a vector of quaternions, the output, R, will be\n% 3x3xN where input quaternion Q(k,:) corresponds to output DCM\n% R(:,:,k).\n%\n% Note that the input Q will be processed by QNORM to ensure normality.\n%\n% See also DCM2Q, QNORM.\n\n% Release: $Name: quaternions-1_2_2 $\n% $Revision: 1.13 $\n% $Date: 2002/01/21 06:46:20 $\n \n% Copyright (C) 2000-02, Jay A. St. Pierre. All rights reserved.\n\n\nif nargin~=1\n error('q2dcm() requires one input argument');\nelse\n qtype=isq(q);\n if ( qtype == 0 )\n error(['Invalid input: must be a quaternion or a vector of' ...\n ' quaternions'])\n end\nend\n\n% Make sure input is a column of quaternions\nif( qtype==1 )\n q=q.';\nend\n\n% Make sure quaternion is normalized to prevent skewed DCM\nq=qnorm(q);\n\n% Build quaternion element products\nq1q1=q(:,1).*q(:,1);\nq1q2=q(:,1).*q(:,2);\nq1q3=q(:,1).*q(:,3);\nq1q4=q(:,1).*q(:,4);\n\nq2q2=q(:,2).*q(:,2);\nq2q3=q(:,2).*q(:,3);\nq2q4=q(:,2).*q(:,4);\n\nq3q3=q(:,3).*q(:,3);\nq3q4=q(:,3).*q(:,4);\n \nq4q4=q(:,4).*q(:,4);\n\n% Build DCM\nR(1,1,:) = q1q1 - q2q2 - q3q3 + q4q4;\nR(1,2,:) = 2*(q1q2 + q3q4);\nR(1,3,:) = 2*(q1q3 - q2q4);\n \nR(2,1,:) = 2*(q1q2 - q3q4);\nR(2,2,:) = -q1q1 + q2q2 - q3q3 + q4q4;\nR(2,3,:) = 2*(q2q3 + q1q4);\n \nR(3,1,:) = 2*(q1q3 + q2q4);\nR(3,2,:) = 2*(q2q3 - q1q4);\nR(3,3,:) = -q1q1 - q2q2 + q3q3 + q4q4;\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/q2dcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.761389113243502}} {"text": "% \n%\n% Copyright (c) 2012 University of Crete - Computer Science Department (UOC-CSD)\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\n% Estimate the paramaters of a wrapped normal distribution\n% http://en.wikipedia.org/wiki/Wrapped_normal_distribution\nfunction [m s] = wrappednormestim(angles, dim)\n\n if nargin<2; dim=1; end\n\n expjangle = exp(1j*angles);\n\n z = mean(expjangle, dim);\n\n m = angle(z);\n\n s = sqrt(-2*log(abs(z)));\n\n if nargout==0\n hx = -pi:0.1:pi;\n hy = hist(angles, hx);\n hy = hy./sum(hy);\n\n hold off;\n plot(hx, (hy), 'k');\n hold on;\n p = wrappednormpdf(hx, m, s);\n p = p./sum(p);\n plot(hx, (p), 'b');\n ylim([0 max(p)+0.1]);\n title(['m=' num2str(m) ' s=' num2str(s)]);\n end\n \nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/misc/wrappednormestim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7612276809863049}} {"text": "function hypercube_integrals_test01 ( )\n\n%*****************************************************************************80\n%\n%% HYPERCUBE_INTEGRALS_TEST01: estimate integrals over the unit hypercube 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 m = 3;\n n = 4192;\n test_num = 20;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01\\n' );\n fprintf ( 1, ' Compare exact and estimated integrals\\n' );\n fprintf ( 1, ' over the interior of the unit hypercube in 3D.\\n' );\n%\n% Get sample points.\n%\n seed = 123456789;\n [ x, seed ] = hypercube01_sample ( m, n, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of sample points used is %d\\n', n );\n%\n% Randomly choose exponents.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ex Ey Ez MC-Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n\n [ e, seed ] = i4vec_uniform_ab ( m, 0, 4, seed );\n\n value = monomial_value ( m, n, e, x );\n\n result = hypercube01_volume ( m ) * sum ( value(1:n) ) / n;\n exact = hypercube01_monomial_integral ( m, e );\n error = abs ( result - exact );\n\n fprintf ( 1, ' %2d %2d %2d %14.6g %14.6g %10.2e\\n', ...\n e(1:m), result, exact, error );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hypercube_integrals/hypercube_integrals_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7612166599128202}} {"text": "function [ x, error_norm, iter, flag ] = gs ( A, x, b, max_it, tol )\n\n%*****************************************************************************80\n%\n%% GS solves the linear system Ax=b using the Gauss-Seidel Method. \n%\n% Modified:\n%\n% 02 April 2006\n%\n% Reference:\n%\n% Richard Barrett, Michael Berry, Tony Chan, James Demmel,\n% June Donato, Jack Dongarra, Victor Eijkhout, Roidan Pozo,\n% Charles Romine, Henk van der Vorst\n% Templates for the Solution of Linear Systems: Building Blocks for \n% Iterative Methods, \n% SIAM Publications, 1993.\n%\n% Parameters:\n%\n% Input, real A(N,N), the symmetric positive definite matrix.\n%\n% Input, real X(N), the initial guess vector.\n%\n% Input, real B(N), the right hand side vector.\n%\n% Input, integer MAX_IT, the maximum number of iterations.\n%\n% Input, real TOL, an error tolerance.\n%\n% Output, real X(N), the solution.\n%\n% Output, real ERROR_NORM, the norm of the error.\n%\n% Output, integer ITER, the number of iterations performed.\n%\n% Output, integer FLAG, the return flag.\n% 0 = the solution was found to within the specified tolerance.\n% 1 = a satisfactory solution was not found. The iteration limit\n% was exceeded.\n%\n\n%\n% Initialization.\n%\n flag = 1;\n iter = 0;\n\n bnrm2 = norm ( b );\n if ( bnrm2 == 0.0 )\n bnrm2 = 1.0\n end\n\n r = b - A * x;\n error_norm = norm ( r ) / bnrm2;\n errorhist = [ ];\n errorhist(1) = error_norm;\n\n if ( error_norm < tol )\n flag = 0;\n return\n end\n%\n% Split the matrix.\n%\n w = 1.0;\n [ M, N, b ] = split ( A, b, w, 3 );\n\n for iter = 1 : max_it\n\n x_1 = x;\n%\n% Update the approximation.\n%\n x = M \\ ( N * x + b );\n%\n% Compute the error.\n%\n error_norm = norm ( x - x_1 ) / norm ( x );\n errorhist(iter+1) = error_norm;\n%\n% Check for convergence.\n%\n if ( error_norm <= tol )\n flag = 0;\n break \n end\n\n end\n\n error_norm = errorhist;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/templates/gs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7611264471274282}} {"text": "function h = r8mat_house_pre ( n, a, row, col )\n\n%*****************************************************************************80\n%\n%% R8MAT_HOUSE_PRE computes a Householder pre-multiplier matrix.\n%\n% Discussion:\n%\n% H(ROW,COL) has the property that the COL-th column of\n% H(ROW,COL)*A is zero from entry ROW+1 to the end.\n%\n% In the most common case, where a QR factorization is being computed,\n% ROW = COL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrices.\n%\n% Input, real A(N,N), the matrix whose Householder matrix\n% is to be computed.\n%\n% Input, integer ROW, COL, specify the location of the\n% entry of the matrix A which is to be preserved. The entries in\n% the same column, but higher rows, will be zeroed out if A is\n% premultiplied by H.\n%\n% Output, real H(N,N), the Householder matrix.\n%\n\n%\n% Set up the vector V.\n%\n a_col(1:row-1,1) = 0.0;\n a_col(row:n,1) = a(row:n,col);\n\n v = r8vec_house_column ( n, a_col, row );\n%\n% Form the matrix H(V).\n%\n h = r8mat_house_form ( n, v );\n\n return\nend\n", "meta": {"author": "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_pre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.761126444495001}} {"text": "function [result] = mc(x)\n\n%MC calculates the medcouple, a robust measure of skewness.\n%\n% The medcouple is described in:\n% Brys, G., Hubert, M. and Struyf, A. (2004),\n% \"A Robust Measure of Skewness\",\n% Journal of Computational and Graphical Statistics,\n% 13, 996-1017. \n%\n% Required input arguments:\n% x : Data matrix.\n% Rows of x represent observations, and columns represent variables. \n% Missing values (NaN's) and infinite values (Inf's) are allowed, since observations (rows) \n% with missing or infinite values will automatically be excluded from the computations.\n% \n% The output of MC is a vector containing the medcouple for each column\n% of the data matrix x.\n%\n% Example:\n% result = mc([chi2rnd(5,1000,1) trnd(3,1000,1)]);\n%\n% This function is part of LIBRA: the Matlab Library for Robust Analysis,\n% available at: \n% http://wis.kuleuven.be/stat/robust.html\n%\n% Written by Guy Brys\n% Last Update: 31/07/2007\n\nif (nargin<1)\n error('No input arguments')\nend\n[n,p] = size(x);\nif n==1\n x = x';\n p = 1;\nend\nx(sum(~isfinite(x),2)>0,:)=[];\nn = size(x,1);\nif (n>50000)\n error('When there are more than 50000 observations, the MC may be uncomputable due to memory limitations.')\nelseif (n>100)\n result = mcc(x);\nelseif n==0\n error('Due to missing values, the data matrix is empty and the MC can not be computed.')\nelse\n result = 0.5*(-mcc(repmat(max(x),size(x,1),1)-x)+mcc(x));\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/LIBRA/mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7610764858297671}} {"text": "function fx = p18_fx ( x )\n\n%*****************************************************************************80\n%\n%% P18_FX evaluates the function for problem 18.\n%\n% Discussion:\n%\n% F(X) = 10^14 * (x-1)^7, but is written in term by term form.\n%\n% This polynomial becomes difficult to evaluate accurately when \n% written this way.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 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% Parameters:\n%\n% Input, real X(*), the point at which F is to be evaluated.\n%\n% Output, real FX(*), the value of the function at X.\n%\n fx = 10.0^14 * ( ...\n x.^7 ...\n - 7 * x.^6 ...\n + 21 * x.^5 ...\n - 35 * x.^4 ...\n + 35 * x.^3 ...\n - 21 * x.^2 ...\n + 7 * x ...\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_zero/p18_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7610754748961717}} {"text": "function M=movwv2at(N,Np);\n%MOVWV2AT Oscillating structure of the interferences of the WVD. \n%\tM=MOVWV2AT(N,Np) generates the movie frames illustrating the \n%\tinfluence of the distance between two components on the oscillating\n%\tstructure of the interferences of the WVD. \n%\n%\tN : number of points for the signal;\n%\tNp : number of snapshots (default : 9)\n%\tM : matrix of movie frames.\n%\n%\tExample : \n%\t M=movwv2at(128,15); movie(M,10);\n\n%\tO. Lemoine - May 1996.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif nargin<1,\n error('At least one argument required');\nelseif nargin==1,\n Np=9;\nend\nNp=odd(Np);\n\nM = moviein(Np);\n\nc = Np/0.2;\n\nampl=amgauss(N/2,N/2,N/2); \n\nfor k=1:(Np+1)/2,\n sig=[ampl.*fmconst(N/2,0.25-(k-1)/c);ampl.*fmconst(N/2,0.25+(k-1)/c)];\n [tfr,t,f]=tfrwv(sig); \n Max=max(max(tfr));V=[0.1 0.3 0.5 0.7 0.9]*Max;\n contour(t,f,tfr,V);xlabel('Time'); ylabel('Frequency'); \n title('Wigner-Ville distribution'); axis('xy')\n M(:,k) = getframe;\nend\n\nfor k=(Np+3)/2:Np,\n M(:,k) = M(:,Np+1-k);\nend\n\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/movwv2at.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7610158088752664}} {"text": "function rank = gray_code_rank ( n, t )\n\n%*****************************************************************************80\n%\n%% GRAY_CODE_RANK computes the rank of a Gray code element.\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% 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 digits in each element.\n% N must be positive.\n%\n% Input, integer T(N), an element of the Gray code.\n% Each entry T(I) is either 0 or 1.\n%\n% Output, integer RANK, the rank of the element.\n%\n\n%\n% Check.\n%\n ierror = gray_code_check ( n, t );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GRAY_CODE_RANK - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal.\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'GRAY_CODE_RANK - Fatal error!' );\n end\n\n rank = 0;\n b = 0;\n\n for i = n - 1 : -1 : 0\n\n if ( t(n-i) ~= 0 )\n b = 1 - b;\n end\n\n if ( b == 1 )\n rank = rank + 2^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/combo/gray_code_rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.7610158057055808}} {"text": "function [centroid, dimension_weight, class] = Subspace_Kmeans(data, iteration, K, beta, 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);\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)\nall_matrix = zeros(size(data,1),size(data,2));\nfor i = 1:size(data,1)\n all_matrix(i,:) = (m(c(i,1),:)-data(i,:)) .* (m(c(i,1),:)-data(i,:));\nend\nJ = 0;\n\nfor i = 1:K\n class_matrix = all_matrix(c==i,:); % pick out data in all_matrix that corresponds to class i\n t_sum = sum(class_matrix,1) + 1e-9; % adding a small positive constant to make weights computatable\n J = J + (alpha(i,:).^beta) * t_sum';\n if(size(class_matrix,1)>0)\n for j = 1:size(alpha,2) \n % variables used to avoid redundant calculation\n tt_numerator = t_sum(1,j);\n t_denominator = sum(tt_numerator./t_sum,2);\n alpha(i,j) = 1/((t_denominator+1e-9)^(1/(beta-1)));\n end\n else\n continue;\n end\nend\n\n% Normalize\nfor i = 1:size(alpha,1)\n alpha(i,:) = alpha(i,:)./(sum(alpha(i,:),2));\nend\n\nend\n\nfunction [result] = classify(m,alpha,data)\n\nresult = zeros(size(data,1),1);\n\n% Construct temporary matrix for efficiently computing dimention-weighted distance\nmatrix = zeros(size(m,1),size(data,2));\n\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 \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/Subspace_Kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7610106584861087}} {"text": "% The Hurst exponent\n%--------------------------------------------------------------------------\n% The first 20 lines of code are a small test driver.\n% You can delete or comment out this part when you are done validating the \n% function to your satisfaction.\n%\n% Bill Davidson, quellen@yahoo.com\n% 13 Nov 2005\n\nfunction []=hurst_exponent()\ndisp('testing Hurst calculation');\n\nn=100;\ndata=rand(1,n);\nplot(data);\n\nhurst=estimate_hurst_exponent(data);\n\n[s,err]=sprintf('Hurst exponent = %.2f',hurst);disp(s);\n\n%--------------------------------------------------------------------------\n% This function does dispersional analysis on a data series, then does a \n% Matlab polyfit to a log-log plot to estimate the Hurst exponent of the \n% series.\n%\n% This algorithm is far faster than a full-blown implementation of Hurst's\n% algorithm. I got the idea from a 2000 PhD dissertation by Hendrik J \n% Blok, and I make no guarantees whatsoever about the rigor of this approach\n% or the accuracy of results. Use it at your own risk.\n%\n% Bill Davidson\n% 21 Oct 2003\n\nfunction [hurst] = estimate_hurst_exponent(data0) % data set\n\ndata=data0; % make a local copy\n\n[M,npoints]=size(data0);\n\nyvals=zeros(1,npoints);\nxvals=zeros(1,npoints);\ndata2=zeros(1,npoints);\n\nindex=0;\nbinsize=1;\n\nwhile npoints>4\n \n y=std(data);\n index=index+1;\n xvals(index)=binsize;\n yvals(index)=binsize*y;\n \n npoints=fix(npoints/2);\n binsize=binsize*2;\n for ipoints=1:npoints % average adjacent points in pairs\n data2(ipoints)=(data(2*ipoints)+data((2*ipoints)-1))*0.5;\n end\n data=data2(1:npoints);\n \nend % while\n\nxvals=xvals(1:index);\nyvals=yvals(1:index);\n\nlogx=log(xvals);\nlogy=log(yvals);\n\np2=polyfit(logx,logy,1);\nhurst=p2(1); % Hurst exponent is the slope of the linear fit of log-log plot\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/9842-hurst-exponent/hurst_exponent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7610106470328166}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\n\n\n\n\n\n\n% =========================================================================\n\n[probability indices] = max(sigmoid(all_theta * X'));\np = indices';\n\nend\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7609692678280211}} {"text": "function value = r4_modp ( x, y )\n\n%*****************************************************************************80\n%\n%% R4_MODP returns the nonnegative remainder of R4 division.\n%\n% Discussion:\n%\n% If\n% REM = R4_MODP ( X, Y )\n% RMULT = ( X - REM ) / Y\n% then\n% X = Y * RMULT + REM\n% where REM is always nonnegative.\n%\n% The MOD function computes a result with the same sign as the\n% quantity being divided. Thus, suppose you had an angle A,\n% and you wanted to ensure that it was between 0 and 360.\n% Then mod(A,360.0) would do, if A was positive, but if A\n% was negative, your result would be between -360 and 0.\n%\n% On the other hand, R4_MODP(A,360.0) is between 0 and 360, always.\n%\n% Example:\n%\n% I J MOD R4_MODP R4_MODP Factorization\n%\n% 107 50 7 7 107 = 2 * 50 + 7\n% 107 -50 7 7 107 = -2 * -50 + 7\n% -107 50 -7 43 -107 = -3 * 50 + 43\n% -107 -50 -7 43 -107 = 3 * -50 + 43\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 09 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number to be divided.\n%\n% Input, real Y, the number that divides X.\n%\n% Output, real VALUE, the nonnegative remainder when X is divided by Y.\n%\n if ( y == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_MODP - Fatal error!\\n' );\n fprintf ( 1, ' R4_MODP ( X, Y ) called with Y = %f\\n', y );\n error ( 'R4_MODP - Fatal error!' );\n end\n\n value = mod ( x, y );\n\n if ( value < 0.0 )\n value = value + abs ( y );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r4lib/r4_modp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.7609692648933418}} {"text": "function [cCombo,dataRecur]=getNextRucksackFill(param1,N)\n%%GETNEXTRUCKSACKFILL Get the next combination of items with given positive\n% weights that will fit into a rucksack (knapsack, backpack)\n% with a capacity of N. This goes through all feasible\n% combinations (starting with putting nothing in the bag).\n% Going through all feasible combinations is not an efficient\n% approach to determining the set of items that can be placed\n% into the bag to maximize its weight.\n%\n%INPUTS: param1 To generate the first combination (which will be the empty\n% set - put nothing in the bag) this is w, an nX1 vector\n% holding the weights of each of the items that can be placed\n% in the bag. All weights>0, but need not be integer. \n% Otherwise, this is the dadaRecur output from the previous\n% call to this function.\n% N The capacity of the rucksack. N>0.\n%\n%OUTPUTS: cCombo The tX1 vector of indices of the items in w that form the\n% current combination of elements that fit into the\n% rucksack. An empty matrix is the first set (out nothing\n% in) and is also returned when the final value has been\n% passed.\n% dataRecur A data structure that can be passed to this function on\n% subsequent calls to get the next value in the sequence. If\n% an empty matrix is reurned, then the final value in the\n% sequence has been passed.\n%\n%This function implements Algorithm F of Section 7.2.1.3 of [1].\n%\n%EXAMPLE:\n%This displays all of the combination indices for a simple problem.\n% w=[1;1.5;5;3;1.5];\n% N=6;\n% [cCombo,dataRecur]=getNextRucksackFill(w,N);\n% while(~isempty(dataRecur))\n% cCombo\n% [cCombo,dataRecur]=getNextRucksackFill(dataRecur);\n% end\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%If we are getting the first filling possibility (the empty sack).\nif(nargin==2)\n w=param1;%The set of all-positive weights.\n [w,idx]=sort(w,'ascend');\n\n n=length(w);\n deltaJ=w(2:n)-w(1:(n-1));\n\n %The extra one at the beginning is for unassigned weights.\n c=zeros(n+1,1);\n\n %Step F1, Initialize\n t=0;\n c(0+1)=n;\n r=N;\n %The initial combination is the empty set.\n cCombo=[];\n dataRecur.w=w;\n dataRecur.idx=idx;\n dataRecur.deltaJ=deltaJ;\n dataRecur.c=c;\n dataRecur.r=r;\n dataRecur.t=t;\n return;\nelse\n dataRecur=param1;\n w=dataRecur.w;\n idx=dataRecur.idx;\n deltaJ=dataRecur.deltaJ;\n c=dataRecur.c;\n r=dataRecur.r;\n t=dataRecur.t;\nend\n\n%Step F3, try to add w(0).\nif(c(t+1)>0&&r>=w(0+1))\n t=t+1;\n c(t+1)=0;\n r=r-w(0+1);\n\n %Step F2, visit the current combination.\n cCombo=idx(c(2:(t+1))+1);\n dataRecur.t=t;\n dataRecur.c=c;\n dataRecur.r=r;\n return;\nend\n\nwhile(1)\n if(t==0)%We have passed the last combination.\n cCombo=[];\n dataRecur=[];\n return;\n end\n\n if(c(t-1+1)>c(t+1)+1&&r>=deltaJ(c(t+1)+1))\n %Step F4\n c(t+1)=c(t+1)+1;\n r=r-deltaJ(c(t+1));\n %Step F2, visit the current combination.\n cCombo=idx(c(2:(t+1))+1);\n dataRecur.t=t;\n dataRecur.c=c;\n dataRecur.r=r;\n return\n else\n %Step F5\n r=r+w(c(t+1)+1);\n t=t-1;\n end\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Combinatorics/getNextRucksackFill.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7609692547403455}} {"text": "function [ cluster_center, seed ] = cluster_initialize_3 ( dim_num, ...\n point_num, cluster_num, point, seed )\n\n%*****************************************************************************80\n%\n%% CLUSTER_INITIALIZE_3 initializes the cluster centers to random values.\n%\n% Discussion:\n%\n% In this case, each point is randomly assigned to a cluster, and\n% the cluster centers are then computed as the centroids of the points \n% in the cluster.\n%\n% Random integers for this function can be generated by the MATLAB\n% function randi(), or by the source code i4_uniform();\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% Parameters:\n%\n% Input, integer DIM_NUM, the number of spatial dimensions.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, integer CLUSTER_NUM, the number of clusters.\n%\n% Input, real POINT(DIM_NUM,POINT_NUM), the coordinates \n% of the points.\n%\n% Input, integer SEED, a seed for the random \n% number generator.\n%\n% Output, real CLUSTER_CENTER(DIM_NUM,CLUSTER_NUM), \n% the coordinates of the cluster centers.\n%\n% Output, integer SEED, a seed for the random \n% number generator.\n%\n\n%\n% Assign one point to each cluster center.\n%\n for i = 1 : cluster_num\n cluster_center(1:dim_num,i) = point(1:dim_num,i);\n end\n\n cluster_population(1:cluster_num) = 1;\n%\n% The rest of the points get assigned randomly.\n%\n for i = cluster_num + 1 : point_num\n if ( 0 )\n [ j, seed ] = i4_uniform ( 1, cluster_num, seed );\n else\n j = randi ( [ 1, cluster_num ], 1, 1 );\n end\n cluster_center(1:dim_num,j) = cluster_center(1:dim_num,j) + point(1:dim_num,i);\n cluster_population(j) = cluster_population(j) + 1;\n end\n%\n% Now average the points to get the centroid.\n%\n for i = 1 : cluster_num\n cluster_center(1:dim_num,i) = cluster_center(1:dim_num,i) ...\n / cluster_population(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/kmeans/cluster_initialize_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.760969251963508}} {"text": "function q = simpqual ( p, t, type )\n\n%*****************************************************************************80\n%\n%% SIMPQUAL computes the simplex quality.\n%\n% Discussion:\n%\n% If TYPE = 1, the quality measure used computes the ratio of\n% the radii of the inscribed and circumscribed circles or spheres.\n%\n% Only dimensions 1, 2 and 3 can be handled. In 1D, the quality is always 1.\n%\n% Licensing:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, real P(NP,ND), the coordinates of a set of nodes.\n%\n% Input, integer T(NT,1:ND+1), a list of the nodes which make up each \n% simplex in the mesh.\n%\n% Input, integer TYPE, specifies the quality measure:\n% 1: Compute the radius ratio (default)\n% 2: Use an approximate formula.\n%\n% Output, real Q(NT), the simplex quality measure.\n%\n if ( nargin < 3 )\n type = 1;\n end\n\n switch type\n%\n% RADIUS RATIO\n%\n case 1\n\n switch size ( p, 2 )\n\n case 1\n\n q = ones ( 1, size(t,2) );\n\n case 2\n\n a=sqrt(sum((p(t(:,2),:)-p(t(:,1),:)).^2,2));\n b=sqrt(sum((p(t(:,3),:)-p(t(:,1),:)).^2,2));\n c=sqrt(sum((p(t(:,3),:)-p(t(:,2),:)).^2,2));\n r=1/2*sqrt((b+c-a).*(c+a-b).*(a+b-c)./(a+b+c));\n R=a.*b.*c./sqrt((a+b+c).*(b+c-a).*(c+a-b).*(a+b-c));\n q = 2 * r ./ R;\n\n case 3\n\n d12=p(t(:,2),:)-p(t(:,1),:);\n d13=p(t(:,3),:)-p(t(:,1),:);\n d14=p(t(:,4),:)-p(t(:,1),:);\n d23=p(t(:,3),:)-p(t(:,2),:);\n d24=p(t(:,4),:)-p(t(:,2),:);\n d34=p(t(:,4),:)-p(t(:,3),:);\n v=abs(dot(cross(d12,d13,2),d14,2))/6;\n s1=sqrt(sum(cross(d12,d13,2).^2,2))/2;\n s2=sqrt(sum(cross(d12,d14,2).^2,2))/2;\n s3=sqrt(sum(cross(d13,d14,2).^2,2))/2;\n s4=sqrt(sum(cross(d23,d24,2).^2,2))/2;\n p1=sqrt(sum(d12.^2,2)).*sqrt(sum(d34.^2,2));\n p2=sqrt(sum(d23.^2,2)).*sqrt(sum(d14.^2,2));\n p3=sqrt(sum(d13.^2,2)).*sqrt(sum(d24.^2,2));\n q=216*v.^2./(s1+s2+s3+s4)./sqrt((p1+p2+p3).*(p1+p2-p3).* ...\n (p1+p3-p2).*(p2+p3-p1));\n\n otherwise\n\n error ( 'SIMPQUAL - Dimension not implemented.' );\n end\n%\n% APPROXIMATE FORMULA\n%\n case 2\n\n switch size(p,2)\n\n case 1\n\n q = ones ( 1, size(t,2) );\n\n case 2\n\n d12 = sum((p(t(:,2),:)-p(t(:,1),:)).^2,2);\n d13 = sum((p(t(:,3),:)-p(t(:,1),:)).^2,2);\n d23 = sum((p(t(:,3),:)-p(t(:,2),:)).^2,2);\n q = 4*sqrt(3)*abs(simpvol(p,t))./(d12+d13+d23);\n\n case 3\n\n d12 = sum((p(t(:,2),:)-p(t(:,1),:)).^2,2);\n d13 = sum((p(t(:,3),:)-p(t(:,1),:)).^2,2);\n d14 = sum((p(t(:,4),:)-p(t(:,1),:)).^2,2);\n d23 = sum((p(t(:,3),:)-p(t(:,2),:)).^2,2);\n d24 = sum((p(t(:,4),:)-p(t(:,2),:)).^2,2);\n d34 = sum((p(t(:,4),:)-p(t(:,3),:)).^2,2);\n q = 216*abs(simpvol(p,t))/sqrt(3)./(d12+d13+d14+d23+d24+d34).^(3/2);\n\n otherwise\n\n error ( 'SIMPQUAL - Dimension not implemented.' );\n end\n\n otherwise\n\n error ( 'SIMPQUAL - Incorrect type.' );\n\n end\n\n return\nend\n", "meta": {"author": "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/simpqual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7609631176746848}} {"text": "function A = multiheadAttention(Q, K, V,nvp)\n% multiheadAttention Multi-head Attention\n%\n% A = multiheadAttention(Q, K, V) computes scaled dot product attention\n% for multiple attention heads as outlined in [1] (see Section 3.2.1 and\n% Figure 2). Note that this function computes the attention for multiple\n% attention heads at once for efficiency. Q is a collection of query\n% matrices, K is a collection of key matrices and V is a collection of\n% value matrices. The output A is a collection of attention matrices. See\n% below for details.\n%\n% Inputs:\n% Q - numFeatures-by-numInputSubWords-by-numHeads-by-numObs array of queries.\n% K - numFeatures-by-numAllSubWords-by-numHeads-by-numObs array of keys.\n% V - numFeatures-by-numAllSubWords-by-numHeads-by-numObs array of values.\n%\n% Outputs:\n% A - numFeatures-by-numInputSubWords-by-numHeads-by-numObs array of attention matrices.\n%\n% A = multiheadAttention(Q, K, V, 'PARAM1', VAL1, 'PARAM2', VAL2, ...)\n% specifies the optional parameter name/value pairs:\n%\n% 'CausalMask' - A scalar logical to turn causal masking on or off. Causal\n% masking prevents tokens at time T attending to tokens\n% at time S = K*K'\n% \n% If called with q ~= 0, a first order process is assumed when evaluating\n% the precision (inverse covariance) matrix; i.e., a = a(1)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_Q.m 5838 2014-01-18 18:40:37Z karl $\n \n% default\n%--------------------------------------------------------------------------\ntry, q; catch, q = 0; end\n \nif q\n \n % compute P (precision)\n %----------------------------------------------------------------------\n A = [-a(1) (1 + a(1)^2) -a(1)];\n Q = spdiags(ones(n,1)*A,(-1:1),n,n);\n \nelse\n \n % compute Q (covariance)\n %----------------------------------------------------------------------\n p = length(a);\n A = [1 -a(:)'];\n P = spdiags(ones(n,1)*A,-(0:p),n,n);\n K = inv(P);\n K = K.*(abs(K) > 1e-4);\n Q = K*K';\n Q = toeplitz(Q(:,1));\n \nend\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/thrid-party/spm/VBA_spm_Q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7607189214496775}} {"text": "function c=ref_dstiv(f)\n%REF_DSTIV Reference Discrete Sine Transform type IV\n% Usage: c=ref_dstiv(f);\n%\n%\n\nL=size(f,1);\nW=size(f,2);\n\n% Create weights.\nw=sqrt(2/L);\n\n% Create transform matrix.\nF=zeros(L);\n\nfor m=0:L-1\n for n=0:L-1\n F(m+1,n+1)=w*sin(pi*(n+.5)*(m+.5)/L);\n end;\nend;\n\n% Compute coefficients.\nc=F*f;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_dstiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7607189062777145}} {"text": "function [p,L] = tspsearch(X,m)\n%TSPSEARCH Heuristic method for Traveling Salesman Problem (TSP).\n% [P,L] = TSPSEARCH(X,M) gives a tour P of length L. X is either a\n% coordinate matrix of size Nx2 or Nx3 or a symmetric distance matrix.\n% Euclidian distances are used in the coordinate case. M is an integer\n% in the range 1 to N. Default is M = 1.\n%\n% METHOD\n% M nearest neighbour tours are generated from randomly selected starting\n% points. Each tour is improved by 2-opt heuristics (pairwise exchange of\n% edges) and the best result is selected.\n%\n% EXAMPLES\n%\n% X = rand(100,2);\n% [p,L] = tspsearch(X,100);\n% tspplot(p,X)\n%\n% % Optimal tour length 1620\n% X = load('hex162.dat');\n% [p,L] = tspsearch(X,10);\n% tspplot(p,X)\n%\n% % Optimal tour length 4860\n% X = load('hex486.dat');\n% [p,L] = tspsearch(X);\n% tspplot(p,X)\n\n% Author: Jonas Lundgren 2012\n\n% Check first argument\n[n,dim] = size(X);\nif dim == 2 || dim == 3\n % X is a coordinate matrix, compute euclidian distances\n D = distmat(X);\nelseif n == dim && min(X(:)) >= 0 && isequal(X,X')\n % X is a distance matrix\n D = X;\nelse\n mess = 'First argument must be Nx2, Nx3 or symmetric and nonnegative.';\n error('tspsearch:first',mess)\nend\n\n% Check second argument\nif nargin < 2 || isempty(m)\n m = 1;\nelseif ~isscalar(m) || m < 1 || m > n || fix(m) < m\n mess = 'M must be an integer in the range 1 to %d.';\n error('tspsearch:second',mess,n)\nend\n\n% Starting points for nearest neighbour tours\ns = randperm(n);\n\nLmin = inf;\nfor k = 1:m\n % Nearest neighbour tour\n\tp = greedy(s(k),D);\n % Improve tour by 2-opt heuristics\n\t[p,L] = exchange2(p,D);\n % Keep best tour\n\tif L < Lmin\n Lmin = L;\n pmin = p;\n\tend\nend\n\n% Output\np = double(pmin);\nL = Lmin;\n\n\n%--------------------------------------------------------------------------\nfunction D = distmat(X)\n%DISTMAT Compute euclidian distance matrix from coordinates\n\n[n,dim] = size(X);\nD = zeros(n);\nfor j = 1:n\n for k = 1:dim\n v = X(:,k) - X(j,k);\n D(:,j) = D(:,j) + v.*v;\n end\nend\nD = sqrt(D);\n\n%--------------------------------------------------------------------------\nfunction p = greedy(s,D)\n%GREEDY Travel to nearest neighbour, starting with node s.\n\nn = size(D,1);\np = zeros(1,n,'uint16');\np(1) = s;\n\nfor k = 2:n\n D(s,:) = inf;\n [junk,s] = min(D(:,s)); %#ok\n p(k) = s;\nend\n\n%--------------------------------------------------------------------------\nfunction [p,L] = exchange2(p,D)\n%EXCHANGE2 Improve tour p by 2-opt heuristics (pairwise exchange of edges).\n% The basic operation is to exchange the edge pair (ab,cd) with the pair\n% (ac,bd). The algoritm examines all possible edge pairs in the tour and\n% applies the best exchange. This procedure continues as long as the\n% tour length decreases. The resulting tour is called 2-optimal.\n\nn = numel(p);\nzmin = -1;\n\n% Iterate until the tour is 2-optimal\nwhile zmin < 0\n\n zmin = 0;\n i = 0;\n b = p(n);\n\n % Loop over all edge pairs (ab,cd)\n while i < n-2\n a = b;\n i = i+1;\n b = p(i);\n Dab = D(a,b);\n j = i+1;\n d = p(j);\n while j < n\n c = d;\n j = j+1;\n d = p(j);\n % Tour length diff z\n % Note: a == d will occur and give z = 0\n z = (D(a,c) - D(c,d)) + D(b,d) - Dab;\n % Keep best exchange\n if z < zmin\n zmin = z;\n imin = i;\n jmin = j;\n end\n end\n end\n\n % Apply exchange\n if zmin < 0\n p(imin:jmin-1) = p(jmin-1:-1:imin);\n end\n\nend\n\n% Tour length\nq = double(p);\nind = sub2ind([n,n],q,[q(2:n),q(1)]);\nL = sum(D(ind));\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35178-tspsearch/tspsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7607140132206416}} {"text": "function [embedding_layer_state, hidden_layer_state, output_layer_state] = ...\n fprop(input_batch, word_embedding_weights, embed_to_hid_weights,...\n hid_to_output_weights, hid_bias, output_bias)\n% This method forward propagates through a neural network.\n% Inputs:\n% input_batch: The input data as a matrix of size numwords X batchsize where,\n% numwords is the number of words, batchsize is the number of data points.\n% So, if input_batch(i, j) = k then the ith word in data point j is word\n% index k of the vocabulary.\n%\n% word_embedding_weights: Word embedding as a matrix of size\n% vocab_size X numhid1, where vocab_size is the size of the vocabulary\n% numhid1 is the dimensionality of the embedding space.\n%\n% embed_to_hid_weights: Weights between the word embedding layer and hidden\n% layer as a matrix of soze numhid1*numwords X numhid2, numhid2 is the\n% number of hidden units.\n%\n% hid_to_output_weights: Weights between the hidden layer and output softmax\n% unit as a matrix of size numhid2 X vocab_size\n%\n% hid_bias: Bias of the hidden layer as a matrix of size numhid2 X 1.\n%\n% output_bias: Bias of the output layer as a matrix of size vocab_size X 1.\n%\n% Outputs:\n% embedding_layer_state: State of units in the embedding layer as a matrix of\n% size numhid1*numwords X batchsize\n%\n% hidden_layer_state: State of units in the hidden layer as a matrix of size\n% numhid2 X batchsize\n%\n% output_layer_state: State of units in the output layer as a matrix of size\n% vocab_size X batchsize\n%\n\n[numwords, batchsize] = size(input_batch);\n[vocab_size, numhid1] = size(word_embedding_weights);\nnumhid2 = size(embed_to_hid_weights, 2);\n\n%% COMPUTE STATE OF WORD EMBEDDING LAYER.\n% Look up the inputs word indices in the word_embedding_weights matrix.\nembedding_layer_state = reshape(...\n word_embedding_weights(reshape(input_batch, 1, []),:)',...\n numhid1 * numwords, []);\n\n%% COMPUTE STATE OF HIDDEN LAYER.\n% Compute inputs to hidden units.\ninputs_to_hidden_units = embed_to_hid_weights' * embedding_layer_state + ...\n repmat(hid_bias, 1, batchsize);\n\n% Apply logistic activation function.\n% FILL IN CODE. Replace the line below by one of the options.\n% hidden_layer_state = zeros(numhid2, batchsize);\n% Options\n% (a) hidden_layer_state = 1 ./ (1 + exp(inputs_to_hidden_units));\n% (b) hidden_layer_state = 1 ./ (1 - exp(-inputs_to_hidden_units));\nhidden_layer_state = 1 ./ (1 + exp(-inputs_to_hidden_units));\n% (d) hidden_layer_state = -1 ./ (1 + exp(-inputs_to_hidden_units));\n\n%% COMPUTE STATE OF OUTPUT LAYER.\n% Compute inputs to softmax.\n% FILL IN CODE. Replace the line below by one of the options.\n% inputs_to_softmax = zeros(vocab_size, batchsize);\n% Options\ninputs_to_softmax = hid_to_output_weights' * hidden_layer_state + repmat(output_bias, 1, batchsize);\n% (b) inputs_to_softmax = hid_to_output_weights' * hidden_layer_state + repmat(output_bias, batchsize, 1);\n% (c) inputs_to_softmax = hidden_layer_state * hid_to_output_weights' + repmat(output_bias, 1, batchsize);\n% (d) inputs_to_softmax = hid_to_output_weights * hidden_layer_state + repmat(output_bias, batchsize, 1);\n\n% Subtract maximum.\n% Remember that adding or subtracting the same constant from each input to a\n% softmax unit does not affect the outputs. Here we are subtracting maximum to\n% make all inputs <= 0. This prevents overflows when computing their\n% exponents.\ninputs_to_softmax = inputs_to_softmax...\n - repmat(max(inputs_to_softmax), vocab_size, 1);\n\n% Compute exp.\noutput_layer_state = exp(inputs_to_softmax);\n\n% Normalize to get probability distribution.\noutput_layer_state = output_layer_state ./ repmat(...\n sum(output_layer_state, 1), vocab_size, 1);\n", "meta": {"author": "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/fprop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7607140105641348}} {"text": "\n%Number of decision makers k, i.e.\nk=4; \n%Number of criterias to be evaluated n i.e.\nn=4; \n%Information about is the given criteria cost or benefit criteria:\n%Benefit=1, Cost=2, should be given as a vector of length n. i.e.\ncriteria=[1 1 1 2];\n\n%Number of attributes to be ranked (suppliers in example case). i.e.\nm=6; \n\n%Criteria for selecting Fuzzy Positive Ideal Solution FPIS and Fuzzy Negative Ideal Solution FNIS.\n%Three possible option are now implemented. See [1.] for more information. i.e.\n\nideal=3; \n%Chosen similarity measure: Integer number within {1,2,3,4}\nsimi=4;\n\nlingvar\n\nWD1={VH H H H};\nWD2={H VH VH H};\nWD3={MH H H MH};\nWD4={M M MH MH};\nWD={WD1;WD2;WD3;WD4};\n\nFDM1={G G G F; MG G MG G; F F G VG; F P G G; MG MP MG MG; G MP F G};\nFDM2={MG G MG G; G MG G G; F F G VG; MG MP MG MG; F MP F MG; MG P F VG};\nFDM3={G MG MG G; F MG G F; MG P F G; MG MP MG G; F MP F G; MG P MG VG};\nFDM4={G MG G G; MG G G MG; G F MG G; F P G G; MG MP MG MG; MG MP F G};\nFDM={FDM1;FDM2;FDM3;FDM4};\n\n\n[CCS,Sstar,Sneg,Order]=Stopsis(WD,FDM,k,m,n,ideal,criteria,simi);\n\ndisp('Similarities w.r.t. attribute and FPIS:')\nSstar\ndisp('Similarities w.r.t. attribute and FNIS:')\nSneg\n\ndisp('Order of the attributes:')\nOrder\ndisp('Closeness values with similarity for choosing attributes:')\nCCS", "meta": {"author": "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/example2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7606592655148157}} {"text": "function a = a123 ( )\n\n%*****************************************************************************80\n%\n%% A123 returns the A123 matrix.\n%\n% Example:\n%\n% 1 2 3\n% 4 5 6\n% 7 8 9\n%\n% Properties:\n%\n% A is integral.\n%\n% A is not symmetric.\n%\n% A is singular.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real A(3,3), the matrix.\n%\n a = zeros ( 3, 3 );\n\n k = 0;\n for i = 1 : 3\n for j = 1 : 3\n k = k + 1;\n a(i,j) = k;\n end\n end\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/a123.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7606589710684319}} {"text": "%% The aliquot parts of a number\n%\n% This demo file teaches about the aliquot parts of a number,\n% and how to use the functions I've provided.\n%\n% Author: John D'Errico\n%\n% e-mail: woodchips@rochester.rr.com\n%\n% Release: 1.0\n%\n% Release date: 9/21/08\n\n%% The aliquot parts of a number are its proper divisors\n% For example, the number 12 has the list of prime factors\nfactor(12)\n\n%%\n% but its proper divisors are given by\naliquotparts(12)\n\n%%\n% See that N will not be listed as a proper divisor of itself, not\n% for any value of N. In fact, the number 1 has no proper divisors.\naliquotparts(1)\n\n%%\n% Of course, prime numbers can have only 1 as a proper divisor.\naliquotparts(17)\n\n%% The sum of the aliquot parts, or sum of proper divisors\naliquotsum([2 4 5 6 8 12 27 135 40320])\n\n%% aliquotsum is efficient and vectorized\n% In this test, the sum of the divisors for EVERY number from 1 to 100000\n% is computed in short order.\nN = (1:100000)';\ntic,pdsum = aliquotsum(N);toc\n%%\n% Show the numbers up to 100000 with the largest relative sums of their proper divisors.\n[pdsum,tags] = sort(pdsum./N,'descend');\ndisp(' N, sigma(N)./N')\ndisp([N(tags(1:10)),pdsum(1:10)])\n\n%% You can also count the number of divisors\n% This is just the sum of the zero'th powers of the divisors. Logically,\n% we expect all the prime numbers to have only one divisor.\nN = (1:20)';\n[N,aliquotsum(N,0)]\n\n%%\n% What number no larger than 100000 has the most proper divisors?\nN = (1:100000)';\nd = aliquotsum(N,0);\n[maxdivisors,Nmax] = max(d)\n%%\n% As you might expect, that number has multiple small factors\nfactor(Nmax)\n\n%% Or you can form the sum of the p'th powers\n% Here we will compute the sum of the squares of the aliquot parts.\nN = (1:20)';\n[N,aliquotsum(N,2)]\n\n%% Perfect numbers\n% Perfect numbers have their aliquot sums equal to the\n% number itself.\naliquotsum([6 28 496 8128])\n\n%% Abundant numbers\n% Just under 25% of all numbers are abundant\nN = 100000;\n100*sum(aliquotsum(1:N)>(1:N))/N\n\n%% Hyper-abundant numbers\n% Few (roughly 2%) of numbers are hyper-abundant.\n% I've defined hyper-abundancy as an aliquot sum of the number N\n% that is at least twice as large as N.\nN = (1:100000)';\n%%\n% As a percentage...\n100*sum(aliquotsum(N)>(2*N))./100000\n\n%%\n% Show the numbers up to 100000 with the largest relative sums of their proper divisors.\npdsum = aliquotsum(N);\n[pdsum,tags] = sort(pdsum./N,'descend');\ndisp(' N, sigma(N)./N')\ndisp([N(tags(1:10)),pdsum(1:10)])\n\n%% Collosally-abundant numbers?\n% How hyper-abundant can they get? Is there a maximum?\nN = 1000000;\npdsum = aliquotsum(1:N);\n[maxsum,whichN] = max(pdsum)\n%%\n% It does not appear that there is any maximum value\n% to this ratio. Certainly it exceeds 3. Mathworld suggests\n% \n% that the ratio can get fairly large. Add 1 to get the ratio they list.\nmaxsum/whichN\n\n%% Odd abundant numbers are less common than the abundant numbers in general\n% The smallest odd abundant number is 945. \nN = (1:2:10000)';\npdsum = aliquotsum(N);\nind = find(pdsum>N);\nN(ind)'\n\n%% The odd abundant numbers are also \"less\" abundant\n% The third column here is the extent of the overabundancy.\n% Since 1.0 there would indicate a perfect number, these odd abundants\n% are all clearly just barely so. I wonder, is there a limit to the\n% extent of abundancy for the odd numbers? Are any hyper-abundant,\n% as I've defined it above?\nN = (1:2:1000000)';\npdsum = aliquotsum(N);\nmaxOddAbundancy = max(pdsum./N)\n\n%% Why are the odd abundants so rare?\n% We can get some idea as to the reason why odd abundant numers \n% are so rare, by looking at the factors of a highly abundant even\n% number.\n%\n% Try 840 for example. Clearly it has multiple powers of 2 in its\n% factorization.\nfactor(840)\n%%\n% 840 is also quite abundant.\naliquotsum(840)\n%% \n% If we look at the factors of the most highly abundant numbers,\n% you will generally find many spare powers of 2. But how about\n% the odd abunbdants? There are no powers of 2 allowed in an odd number,\n% so pick some of the odd abundant numbers and look at their factors.\n% As expected, we find some extra powers of 3, along with some other\n% moderately small odd primes.\nfactor(945)\nfactor(9765)\n%%\n% Pick a rather large odd number that will have very many factors.\n% Unfortunately, this is close to as far as aliquotsum will go, due to\n% the limits of MATLAB's operating precision. I'll admit the ratio\n% is starting to approach 2.\nN = 3*3*3*5*5*7*7*11*13*17*19\naliquotsum(N)/N\n\n%% Deficient numbers\n% All primes are deficient, as are all pure powers of prime numbers.\n% As well, all the divisors of any perfect number are known to be deficient.\naliquotsum(primes(50))\n\n%% Maximally deficient numbers\n% Naturally, the prime numbers represent the most deficient numbers\n% possible, since each prime has only one divisor less than itself,\n% and that is the number 1. If we ignore the prime numbers, which\n% numbers are the next most deficient? Do you see a pattern?\nN = setdiff(1:50,primes(50))';\n[N,aliquotsum(N)]\n\n%% Amicable numbers\n% A pair of numbers is amicable if their aliquot sums are\n% equal to the other member of the pair.\naliquotsum([220 284])\n\n%% Sociable numbers form cliques, or amicable cycles\n% Perfect numbers are self-amicable, with a cycle length of 1.\n% Amicable pairs have a cycle length of 2.\n% This cycle has length 5 before it returns to the start.\naliquotsum([12496 14288 15472 14536 14264])\n\n%% Amicable cycles\n% Perfect numbers are self-amicable. The amicablecycles function:\n%\n% cycles = amicablecycles(N,L)\n% \n% will find all cycles that start with a number\n% as large as N. The length of the cycle is L.\namicablecycles(20000,1)\n%%\n% Amicable pairs have a cycle length of 2.\namicablecycles(20000,2)\n\n%%\n% There are no known sociable cliques of length 3 or 4\namicablecycles(20000,3)\namicablecycles(20000,4)\n\n%%\n% The smallest cycle of length 5 starts at 12496\namicablecycles(20000,5)\n\n%% Odd amicables\n% You can force amicablecycles to look only at certain starting points.\n% For example, to find the odd amicable cycles only\namicablecycles(1:2:200000,2)\n\n%% Some interesting things to try\n% What fun things can you find to do with these numbers?\n% Can you find any odd perfect numbers? Perhaps a quasi-perfect\n% number?\n%\n% Some simple problems for the student, and a few that may not be so\n% simple.\n%\n% 1. Which numbers have many distinct divisors?\n%\n% 2. What is the smallest number to have exactly 31 divisors?\n%\n% 3. Does the product of the first k primes necessarily have the largest number of distinct divisors?\n%\n% 4. Can you construct a number less than 2*3*5*7*11 that has more divisors than this number?\n%\n% 5. For which values of non-prime numbers N is the lower bound sqrt(N)+1 realized for the aliquot sum?\n%\n% 6. Can you prove that sqrt(N)+1 forms a lower bound for the aliquot sum for the non-prime numbers N?\n%\n% 7. Is there a simple relationship for the upper bound of the aliquot sum\n% as a function of N? Consider N*log(N) as a start.\n%\n% 8. There are many abundant numbers. As was shown above, roughly 25% of\n% all numbers are abundant. Can you generate the list of all abundant\n% numbers up to some value? (Start with the aliquotsum function.) What is the\n% smallest abundant number?\n%\n% 9. The odd abundant numbers were shown to be somewhat rare, and always\n% seemed to have multiple powers of 3 in their representations. Are there\n% any abundants that do not have either 2 or 3 as a factor? Can this\n% happen? Note that such an investigation might involve numbers that are\n% too large for the tools I've provided to work with properly.\nN = vpi(5)*5*5*5*5*5*7*7*7*11*13\naliquotsum(N)\n%%\n% 10. Can you represent numbers as the sum of two abundant numbers? Which\n% numbers are not so representable? Is there a smallest number such that\n% all those above it are the sum of two abundant numbers?\n%\n% 11. An interesting generalization of a perfect number is what I'll call the p-perfect\n% number. Thus, if a perfect number is an integer such that the sum of its\n% proper divisors adds up to the number itself, a p-perfect number N might\n% have the sum of the p'th powers of the divisors adding up to N^p. Do any\n% such numbers exist? Can you show this cannot happen? Or are there any\n% numbers with the squares of the divisors that adds up to the original\n% number?\n%\n% 12. How about p-amicability? Can you think of a way to generalize this\n% concept?\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21498-the-divisors-of-a-number-perfect-amicable-and-sociable-numbers/Aliquot_parts/demo_aliquot_parts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7606589550533865}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n\n% problem 2- graph of\n% u(t+1)*u(t-1)\n\n\n t1=-5:.1:1;\n t2=1:.1:10;\n x1=zeros(size(t1));\n x2=ones(size(t2));\n t=[t1 t2];\n x=[x1 x2];\n plot(t,x);\n ylim([-0.1 1.1]);\n \n figure\n t=-5:.1:10;\n x=heaviside(t+1).*heaviside(t-1) ;\n plot(t,x); \n ylim([-0.1 1.1]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c272.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7606452329296449}} {"text": "% Find x that minimizes ||Ax|| under different constraints\n%\n% The problem can be solved with different constraints:\n% Reference: Alg 5.6, HZ2, p. 595\n% Find x that minimizes ||Ax|| subject to ||x||=1 and x=G*xHat, where G\n% has rank r\n% Reference: Alg 5.7, HZ2, p. 596\n% Find x that minimizes ||Ax|| subject to ||Cx||=1\n%\n% USAGE\n% x = solveLeastSqAx(A)\n% [x,xHat] = solveLeastSqAx(A,G,method)\n%\n% INPUTS 1 - Find x that minimizes ||Ax|| subject to ||x||=1\n% A - constraint matrix, ||Ax|| to be minimized with ||x||=1\n%\n% INPUTS 2\n%\n% INPUTS 3 - Find x that minimizes ||Ax|| subject to ||x||=1 and x=G*xHat,\n% where G has rank r\n% A - constraint matrix\n% G - condition matrix\n% method - method=2\n%\n% INPUTS 4 - Find x that minimizes ||Ax|| subject to ||Cx||=1\n% A - constraint matrix\n% C - condition matrix\n% method - method=3\n%\n% OUTPUTS 1,2,4\n% x - solution\n%\n% OUTPUTS 3\n% x - solution\n% xHat - vector such that x = G*xHat\n%\n% EXAMPLE\n%\n% See also\n%\n% Vincent's Structure From Motion Toolbox Version 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\nfunction [ x xHat ] = solveLeastSqAx(A,G,method)\n\nif nargin==1; [U,D,V] = svd(A,0); x=V(:,end); return; end\nif nargin==2; error('method argument required'); end\n\nswitch method\n case 1\n % Find x that minimizes ||Ax|| subject to ||x||=1\n % Reference: HZ2, Algorithm 5.4, p593\n if issparse(A)\n [ disc disc V ]=svds(A);\n else\n [ disc disc V ]=svd(A);\n end\n x = V(:,end);\n case 2\n % Find x that minimizes ||Ax|| subject to ||x||=1 and x=G*xHat, where G\n % has rank r\n % Reference: HZ2, Algorithm 5.6, p595\n % (i)\n [U,D,V] = svd(G,0);\n % (ii)\n r = rank(G); Up = U(:,1:r);\n % (iii)\n xp = solveLeastSqAx(A*U2);\n % (iv)\n x = Up*xp;\n % (v)\n if nargout==2; Vp=V(:,1:r); xHat=Vp*diag(1./diag(D(1:r,1:r)))*x2; end\n case 3\n % Find x that minimizes ||Ax|| subject to ||Cx||=1\n % Reference: Alg 5.7, HZ2, p. 596\n % (i)\n [U,D,V]=svd(C); Ap=A*V;\n % (ii)\n r=rank(D); A1p=Ap(:,1:r); A2p=Ap(:,r:end);\n % (iii)\n D1=D(1:r,1:r);\n % (iv)\n D1inv=diag(1./diag(D1)); A2pPinv=pinv(A2p);\n App=(A2p*A2pPinv-eye(size(A2p,1)))*A1p*D1inv;\n % (v)\n xpp=solveLeastSqAx(App);\n % (vi)\n x1p=D1inv*xpp; x2p=-A2pPinv*A1p*x1p; xp=[x1p;x2p];\n % (vii)\n x=V*xp;\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/linearAlgebra/solveLeastSqAx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7606343057437012}} {"text": "function value = f_01_2d ( dim_num, x )\n\n%*****************************************************************************80\n%\n%% F_01_2D is the 2D test function #1.\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, real X(DIM_NUM), the point where the function\n% is to be evaluated.\n%\n% Output, real VALUE, the value of the function at X.\n%\n e = 2.718281828459045;\n value = x(2) * exp ( x(1) * x(2) ) / ( e - 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/lattice_rule/f_01_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7606049310699969}} {"text": "%% Machine Learning Online Class - Exercise 2: Logistic Regression\n%\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the logistic\n% regression exercise. You will need to complete the following functions \n% in this exericse:\n%\n% sigmoid.m\n% costFunction.m\n% predict.m\n% costFunctionReg.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%% Load Data\n% The first two columns contains the exam scores and the third column\n% contains the label.\n\ndata = load('ex2data1.txt');\nX = data(:, [1, 2]); y = data(:, 3);\n\n%% ==================== Part 1: Plotting ====================\n% We start the exercise by first plotting the data to understand the \n% the problem we are working with.\n\nfprintf(['Plotting data with + indicating (y = 1) examples and o ' ...\n 'indicating (y = 0) examples.\\n']);\n\nplotData(X, y);\n\n% Put some labels \nhold on;\n% Labels and Legend\nxlabel('Exam 1 score')\nylabel('Exam 2 score')\n\n% Specified in plot order\nlegend('Admitted', 'Not admitted')\nhold off;\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ============ Part 2: Compute Cost and Gradient ============\n% In this part of the exercise, you will implement the cost and gradient\n% for logistic regression. You neeed to complete the code in \n% costFunction.m\n\n% Setup the data matrix appropriately, and add ones for the intercept term\n[m, n] = size(X);\n\n% Add intercept term to x and X_test\nX = [ones(m, 1) X];\n\n% Initialize fitting parameters\ninitial_theta = zeros(n + 1, 1);\n\n% Compute and display initial cost and gradient\n[cost, grad] = costFunction(initial_theta, X, y);\n\nfprintf('Cost at initial theta (zeros): %f\\n', cost);\nfprintf('Expected cost (approx): 0.693\\n');\nfprintf('Gradient at initial theta (zeros): \\n');\nfprintf(' %f \\n', grad);\nfprintf('Expected gradients (approx):\\n -0.1000\\n -12.0092\\n -11.2628\\n');\n\n% Compute and display cost and gradient with non-zero theta\ntest_theta = [-24; 0.2; 0.2];\n[cost, grad] = costFunction(test_theta, X, y);\n\nfprintf('\\nCost at test theta: %f\\n', cost);\nfprintf('Expected cost (approx): 0.218\\n');\nfprintf('Gradient at test theta: \\n');\nfprintf(' %f \\n', grad);\nfprintf('Expected gradients (approx):\\n 0.043\\n 2.566\\n 2.647\\n');\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ============= Part 3: Optimizing using fminunc =============\n% In this exercise, you will use a built-in function (fminunc) to find the\n% optimal parameters theta.\n\n% Set options for fminunc\noptions = optimset('GradObj', 'on', 'MaxIter', 400);\n\n% Run fminunc to obtain the optimal theta\n% This function will return theta and the cost \n[theta, cost] = ...\n\tfminunc(@(t)(costFunction(t, X, y)), initial_theta, options);\n\n% Print theta to screen\nfprintf('Cost at theta found by fminunc: %f\\n', cost);\nfprintf('Expected cost (approx): 0.203\\n');\nfprintf('theta: \\n');\nfprintf(' %f \\n', theta);\nfprintf('Expected theta (approx):\\n');\nfprintf(' -25.161\\n 0.206\\n 0.201\\n');\n\n% Plot Boundary\nplotDecisionBoundary(theta, X, y);\n\n% Put some labels \nhold on;\n% Labels and Legend\nxlabel('Exam 1 score')\nylabel('Exam 2 score')\n\n% Specified in plot order\nlegend('Admitted', 'Not admitted')\nhold off;\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n%% ============== Part 4: Predict and Accuracies ==============\n% After learning the parameters, you'll like to use it to predict the outcomes\n% on unseen data. In this part, you will use the logistic regression model\n% to predict the probability that a student with score 45 on exam 1 and \n% score 85 on exam 2 will be admitted.\n%\n% Furthermore, you will compute the training and test set accuracies of \n% our model.\n%\n% Your task is to complete the code in predict.m\n\n% Predict probability for a student with score 45 on exam 1 \n% and score 85 on exam 2 \n\nprob = sigmoid([1 45 85] * theta);\nfprintf(['For a student with scores 45 and 85, we predict an admission ' ...\n 'probability of %f\\n'], prob);\nfprintf('Expected value: 0.775 +/- 0.002\\n\\n');\n\n% Compute accuracy on our training set\np = predict(theta, X);\n\nfprintf('Train Accuracy: %f\\n', mean(double(p == y)) * 100);\nfprintf('Expected accuracy (approx): 89.0\\n');\nfprintf('\\n');\n\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-ex2/ex2/ex2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8947894555814343, "lm_q1q2_score": 0.7605452591287747}} {"text": "function y = atanminuspihalf(x)\n%ATANMINUSPIHALF Inverse tangent minus pi/2.\n%\n% ATANMINUSPIHALF(X) is ATAN(X)-PI/2 calculated in a way that is numerically\n% better when X is large and positive.\n%\n% See also TANPLUSPIHALF.\n\n% Author: Peter J. Acklam\n% Time-stamp: 2003-10-13 14:55:25 +0200\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n % check number of input arguments\n error(nargchk(1, 1, nargin));\n\n y = zeros(size(x));\n\n k = x <= 0;\n y(k) = atan(x(k)) - (pi / 2);\n\n k = x > 0;\n y(k) = atan(-1 ./ x(k));\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/atanminuspihalf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7605452469836547}} {"text": "function c=ref_dft_1(f)\n%REF_DFT_1 Reference DFT by doubling \n% Usage: c=ref_dft_1(f);\n%\n% REF_DFT_1(f) computes a DFT of f by upsampling f and inserting zeros\n% at the odd positions.\n%\n% This is not an efficient method, it is just meant to illustrate a \n% symmetry of the DFT.\n\nL=size(f,1);\nW=size(f,2);\n\nflong=zeros(2*L,W,assert_classname(f));\nflong(1:2:end-1)=f;\n\nfflong=fft(flong)/sqrt(L);\n\nc=fflong(1:L,:);\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_dft_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7604728014178548}} {"text": "function kappa = polynomialCurveCurvature(t, varargin)\n%POLYNOMIALCURVECURVATURE Compute the local curvature of a polynomial curve\n%\n% KAPPA = polynomialCurveCurvature(T, XCOEF, YCOEF)\n% XCOEF and YCOEF are row vectors of coefficients, in the form:\n% [a0 a1 a2 ... an]\n% KAPPA is the local curvature of the polynomial curve, computed for\n% position T. If T is a vector, KAPPA has the same length as T.\n%\n% KAPPA = polynomialCurveCurvature(T, COEFS)\n% COEFS is either a 2xN matrix (one row for the coefficients of each\n% coordinate), or a cell array.\n%\n% Example\n% polynomialCurveCurvature\n%\n% See also\n% polynomialCurves2d, polynomialCurveLength, polynomialCurveDerivative\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2007-02-23\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n%% Extract input parameters\n\n% polynomial coefficients for each coordinate\nvar = varargin{1};\nif iscell(var)\n xCoef = var{1};\n yCoef = var{2};\nelseif size(var, 1)==1\n xCoef = varargin{1};\n yCoef = varargin{2};\nelse\n xCoef = var(1,:);\n yCoef = var(2,:);\nend\n \n\n%% compute derivative\n\n% compute first derivatives of the polynomials\ndx = polynomialDerivate(xCoef);\ndy = polynomialDerivate(yCoef);\n\n% compute second derivatives\nsx = polynomialDerivate(dx);\nsy = polynomialDerivate(dy);\n\n% convert to polyval convention\ndx = dx(end:-1:1);\ndy = dy(end:-1:1);\nsx = sx(end:-1:1);\nsy = sy(end:-1:1);\n\n% compute local first and second derivatives\nxp = polyval(dx, t);\nyp = polyval(dy, t);\nxs = polyval(sx, t);\nys = polyval(sy, t);\n\n% compute local curvature of polynomial curve\nkappa = (xp.*ys - xs.*yp) ./ power(xp.*xp + yp.*yp, 3/2);\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/polynomialCurves2d/polynomialCurveCurvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7604162421686345}} {"text": "function r = assortativity_bin(CIJ,flag)\n% ASSORTATIVITY_BIN Assortativity coefficient\n%\n% r = assortativity(CIJ,flag);\n%\n% The assortativity coefficient is a correlation coefficient between the\n% degrees of all nodes on two opposite ends of a link. A positive\n% assortativity coefficient indicates that nodes tend to link to other\n% nodes with the same or similar degree.\n%\n% Inputs: CIJ, binary directed/undirected connection matrix\n% flag, 0, undirected graph: degree/degree correlation\n% 1, directed graph: out-degree/in-degree correlation\n% 2, directed graph: in-degree/out-degree correlation\n% 3, directed graph: out-degree/out-degree correlation\n% 4, directed graph: in-degree/in-degree correlation\n%\n% Outputs: r, assortativity coefficient\n%\n% Notes: The function accepts weighted networks, but all connection\n% weights are ignored. The main diagonal should be empty. For flag 1\n% the function computes the directed assortativity described in Rubinov\n% and Sporns (2010) NeuroImage.\n%\n% Reference: Newman (2002) Phys Rev Lett 89:208701\n% Foster et al. (2010) PNAS 107:10815�10820\n%\n% Olaf Sporns, Indiana University, 2007/2008\n% Vassilis Tsiaras, University of Crete, 2009\n% Murray Shanahan, Imperial College London, 2012\n% Mika Rubinov, University of Cambridge, 2012\n\nif (flag==0) % undirected version\n deg = degrees_und(CIJ);\n [i,j] = find(triu(CIJ,1)>0);\n K = length(i);\n degi = deg(i);\n degj = deg(j);\n\nelse % directed versions\n [id,od] = degrees_dir(CIJ);\n [i,j] = find(CIJ>0);\n K = length(i);\n\n switch flag\n case 1\n degi = od(i);\n degj = id(j);\n case 2\n degi = id(i);\n degj = od(j);\n case 3\n degi = od(i);\n degj = od(j);\n case 4\n degi = id(i);\n degj = id(j);\n end\nend\n\n% compute assortativity\nr = ( sum(degi.*degj)/K - (sum(0.5*(degi+degj))/K)^2 ) / ...\n ( sum(0.5*(degi.^2+degj.^2))/K - (sum(0.5*(degi+degj))/K)^2 );\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/assortativity_bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7604162338016585}} {"text": "function pp = pchipd(x,y,d,xx)\n%PCHIPD Piecewise Cubic Hermite Interpolating Polynomial with Derivatives.\n% PP = PCHIPD(X,Y,D) provides the piecewise cubic polynomial which\n% interpolates values Y and derivatives D at the sites X. This is meant\n% to augment the built-in Matlab function PCHIP, which does not allow the\n% user to specify derivatives.\n% \n% X must be a vector.\n%\n% If Y and D are vectors, then Y(i) and D(i) are the value and derivative\n% to be matched at X(i).\n%\n% If Y and D are matrices, then size(Y,2) == size(D,2) == length(X).\n% Also, size(Y,1) == size(D,1). Use this for interpolating vector valued\n% functions.\n%\n% YY = PCHIPD(X,Y,D,XX) is the same as YY = PPVAL(PCHIPD(X,Y,D),XX), thus\n% providing, in YY, the values of the interpolant at XX.\n%\n% Example comparing SPLINE, PCHIP, and PCHIPD\n% a = -10;\n% b = 10;\n% x = linspace(a,b,7); \n% f = @(x) 1./(1+exp(-x)); % logistic function\n% df = @(x) f(x).*(1-f(x)); % derivative of the logistic function\n% t = linspace(a,b,50);\n% r = f(t);\n% p = pchip(x,f(x),t);\n% s = spline(x,f(x),t);\n% q = pchipd(x,f(x),df(x),t);\n% plot(t,r,'k',x,f(x),'o',t,p,'-',t,s,'-.',t,q,'--')\n% legend('true','data','pchip','spline','pchipd',4)\n%\n% See also INTERP1, SPLINE, PCHIP, PPVAL, MKPP, UNMKPP.\n%\n\n%\n% 2010-10-04 (nwh) first version\n%\n\n% check inputs\n% x must be a vector\nif ~isvector(x)\n error('pchipd:input_error','x must be a vector of length > 2.')\nend\n\n% get size and orient\nn = length(x);\nx = x(:);\n\n% make sure x is long enough, we can't construct an interpolating\n% polynomial with just one point\nif n < 2\n error('pchipd:input_error','x must be a vector of length > 2.')\nend\n\n% check y and d\nif isvector(y) && isvector(d) && length(y) == n && length(d) == n\n % orient\n y = y(:);\n d = d(:);\n m = 1;\nelseif size(y,2) == n && size(d,2) == n && size(y,1) == size(d,1)\n m = size(y,1);\n y = y';\n d = d';\nelse\n error('pchipd:input_error','y and d must be vectors or matrices of same size with length(x) columns.')\nend\n\n% sort breaks & data if needed\nif ~issorted(x)\n [x x_ix] = sort(x);\n if m == 1\n y = y(x_ix);\n d = d(x_ix);\n else\n y = y(x_ix,:);\n d = d(x_ix,:);\n end\nend\n\n% compute coefficients\ncoef = zeros(m,n-1,4);\ndx = diff(x);\nfor i = 1:m\n dy = diff(y(:,i));\n coef(i,:,4) = y(1:end-1,i)';\n coef(i,:,3) = d(1:end-1,i)';\n coef(i,:,2) = 3*dy./(dx.^2) - (2*d(1:end-1,i)+d(2:end,i))./dx;\n coef(i,:,1) = -2*dy./(dx.^3) + (d(1:end-1,i)+d(2:end,i))./(dx.^2);\nend\n\n% create the piecewise polynomial structure\npp = mkpp(x,coef,m);\n\n% if user requests evaluations\nif nargin > 3\n pp = ppval(pp,xx);\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/36836-vasplab/vasplab/pchipd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7604162324086474}} {"text": "function [FV2]=refinepatch(FV)\n% This function \"refinepatch\" refines a triangular mesh with \n% a spline interpolated 4-split method.\n%\n% [FV2] = refinepatch(FV,options)\n%\n% inputs,\n% FV : Structure containing a Patch, with\n% FV.vertices the mesh vertices\n% FV.face the mesh faces (triangles), rows with each 3 vertex indices\n% outputs,\n% FV2 : Structure Containing the refined patch\n%\n%\n% Reference:\n% The spline interpolation of the face edges is done by the \n% Opposite Edge Method, described in: \"Construction of Smooth Curves \n% and Surfaces from Polyhedral Models\" by Leon A. Shirman \n%\n% How it works:\n% The tangents (normals) and velocity on the edge points of all edges \n% are calculated. Which are later used for b-spline interpolation when \n% splitting the edges.\n%\n% A tangent on an 3D line or edge is under defined and can rotate along \n% the line, thus an (virtual) opposite vertex is used to fix the tangent and\n% make it more like a surface normal.\n%\n% B-spline interpolate a half way vertices between all existing vertices\n% using the velocity and tangent from the edgepoints. After splitting a\n% new facelist is constructed\n%\n% Speed:\n% Compile the c-functions for more speed with:\n% mex vertex_neighbours_double.c -v;\n% mex edge_tangents_double.c -v;\n%\n% Example:\n%\n% X=[-0.5000; 0.5000; 0.0000; 0.0000];\n% Y=[-0.2887; -0.2887; 0.5774; 0.0000];\n% Z=[ 0.0000; 0.0000; 0.0000; 0.8165];\n% FV.vertices=[X Y Z];\n%\n% FV.faces=[2 3 4; 4 3 1; 1 2 4; 3 2 1];\n%\n% figure, set(gcf, 'Renderer', 'opengl'); axis equal;\n% for i=1:4\n% patch(FV,'facecolor',[1 0 0]);\n% pause(2);\n% [FV]=refinepatch(FV);\n% end\n%\n% Function is written by D.Kroon University of Twente (February 2010)\n\n% Get the neighbour vertices of each vertice from the face list.\nNe=vertex_neighbours(FV);\n\n% Calculate the tangents (normals) and velocity of all edges. Which is\n% later used for b-spline interpolation and split of the edges\n%\n% A tangent on an 3D line or edge is under defined and can rotate along \n% the line, thus an (virtual) opposite vertex is used to fix the tangent and\n% make it more like a surface normal.\nV=FV.vertices; F=FV.faces;\n[ET_table,EV_table,ETV_index]=edge_tangents(V,Ne);\n\n% B-spline interpolate a half way vertices between all existing vertices\n% using the velocity and tangent from above\n[V,HT_index, HT_values]=make_halfway_vertices(EV_table,ET_table,ETV_index,V,Ne);\n\n% Make new facelist\nFnew=makenewfacelist(F,HT_index,HT_values);\n\nFV2.vertices=V;\nFV2.faces=Fnew;\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/external/meshTools/refinepatch_version2b/refinepatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7604135662928277}} {"text": "function price = Price_Spread_Option_BjerksundStensland_2D(K, S0_1, S0_2, T, r, rho, sigma_1, sigma_2, q_1, q_2)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: calcuates Price of 2D Spread option, (S_1(T) - S_2(T) - K)+, using Bjerksund & Stensland approximation\n% Note: when K = 0, this agrees with Magrabes exact formula\n% Author: Justin Lars Kirkby\n%\n% Reference: Bjerksund, P. and Stensland, G. (2006): \"Closed form spread option valuation\"\n%\n% -----------------\n% Params\n% -----------------\n% S0_1 = initial asset price of first asset, e.g. S0_1 = 100\n% S0_2 = initial asset price of second asset, e.g. S0_2 = 100\n% T = time to maturity in years (e.g. T=1)\n% r = interest rate\n% rho = instantaneous correlation between S_1 and S_2\n% sigma_1 = volatility of first asset (annualized), e.g. sigma = 0.2\n% sigma_2 = volatility of second asset (annualized), e.g. sigma = 0.2\n% q_1 = dividend yield of first asset, e.g. q_1 = 0.02\n% q_2 = dividend yield of second asset, e.g. q_2 = 0.02\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nF1 = S0_1*exp((r-q_1)*T);\nF2 = S0_2*exp((r-q_2)*T);\n\na = F2 + K;\nb = F2 / a;\nrhosigs = rho*sigma_1*sigma_2;\nsig = sqrt(sigma_1^2 - 2*rhosigs*b + b^2*sigma_2^2);\nsigst = sig*sqrt(T);\n\n\nd1 = (log(F1/a) + (0.5*sigma_1^2 - b*rhosigs + 0.5*b^2*sigma_2^2)*T) / sigst;\nd2 = (log(F1/a) + (-0.5*sigma_1^2 + rhosigs + (0.5*b^2 - b)*sigma_2^2)*T) / sigst;\nd3 = (log(F1/a) + (-0.5*sigma_1^2 + 0.5*b^2*sigma_2^2)*T) / sigst;\n\nprice = exp(-r*T)*(F1*normcdf(d1) - F2*normcdf(d2) - K*normcdf(d3));\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/Analytical/BlackScholes/Price_Spread_Option_BjerksundStensland_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7603926716085101}} {"text": "function dist_signed = triangle_point_dist_signed_2d ( t, p )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_POINT_DIST_SIGNED_2D: signed distance ( triangle, point ) in 2D.\n%\n% Discussion:\n%\n% If the signed distance is:\n% 0, the point is on the boundary of the triangle;\n% negative, the point is in the triangle;\n% positive, the point is outside the triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the triangle vertices.\n% These should be given in counter clockwise order.\n%\n% Input, real P(2,1), the point which is to be checked.\n%\n% Output, real DIST_SIGNED, the signed distance from the\n% point to the triangle.\n%\n dim_num = 2;\n%\n% Compute the signed line distances to the point.\n%\n dis12 = line_exp_point_dist_signed_2d ( t(1:2,1), t(1:2,2), p );\n\n dis23 = line_exp_point_dist_signed_2d ( t(1:2,2), t(1:2,3), p );\n\n dis31 = line_exp_point_dist_signed_2d ( t(1:2,3), t(1:2,1), p );\n%\n% If the point is inside the triangle, all the line distances are negative.\n% The largest (negative) line distance has the smallest magnitude,\n% and is the signed triangle distance.\n%\n if ( dis12 <= 0.0 & dis23 <= 0.0 & dis31 <= 0.0 )\n\n dist_signed = max ( dis12, max ( dis23, dis31 ) );\n%\n% If the point is outside the triangle, then we have to compute\n% the (positive) line segment distances and take the minimum.\n%\n else\n\n dis12 = segment_point_dist_2d ( t(1:2,1), t(1:2,2), p );\n dis23 = segment_point_dist_2d ( t(1:2,2), t(1:2,3), p );\n dis31 = segment_point_dist_2d ( t(1:2,3), t(1:2,1), p );\n\n dist_signed = min ( dis12, min ( dis23, dis31 ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/triangle_point_dist_signed_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7603877658825176}} {"text": "function [y a]=lpredict(x, np, npred, pos)\n% LPREDICT estimates the values of a data set before/after the observed set.\n%\n% LPREDICT uses linear prediction to extrapolate data, typically a\n% timeseries. Note that this is not the same as linear extrapolation. \n% A window of autocorrelation coefficients is moved beyond the data\n% limits to extrapolate the data. For a discussion, see Press et. al. [1].\n%\n% The required coefficients are derived from a call to LPC in MATLAB's\n% Signal Processing Toolbox\n%\n% Example:\n% y=LPREDICT(x, np, npred, pos)\n% [y, a]=LPREDICT(x, np, npred, pos)\n% x: the input data series as a column vector or a matrix \n% with series organized in columns\n% np: the number of predictor coefficients to use (>=2)\n% npred: the number of data values to return in the output\n% pos: a string 'pre' or 'post' (default: post)\n% This determines whether extrapolation occurs before or\n% after the observed series x.\n%\n% y: the output, appropriately sequenced for concatenation with\n% input x\n% a: the coefficients returned by LPC (organized in rows).\n% These can be used to check the quality/stability of the\n% fit to the observed data as described in the\n% documenation to the LPC function.\n%\n% The output y is given by:\n% y(k) = -a(2)*y(k-1) - a(3)*y(k-2) - ... - a(np)*y(k-np)\n% where y(n) => x(end-n) for n<=0\n% \n% Note that sum(-a(2:end))is always less than unity. The output will\n% therefore approach zero as npred increases. This may be a problem if x\n% has a large DC offset. Subtract the the column mean(s) of x from x on\n% input and add them to the output column(s) to restore DC. For a more\n% accurate DC correction, see [1].\n%\n% To pre-pend data, the input sequence is reversed and the output is\n% similarly reversed before being returned. The output may always be\n% vertically concatenated with the input to extend the timeseries e.g:\n% k=(1:100)';\n% x=exp(-k/100).*sin(k/5);\n% x=[lpredict(x, 5, 100, 'pre'); x; lpredict(x, 5, 100, 'post')];\n% \n% \n% See also LPC\n%\n% References:\n% [1] Press et al. (1992) Numerical Recipes in C. (Ed. 2, Section 13.6).\n%\n% Toolboxes Required: Signal Processing\n%\n% Revisions: 10.07 renamed to avoid filename clash with System ID\n% Toolbox\n% DC correction help text corrected.\n%\n% -------------------------------------------------------------------------\n% Author: Malcolm Lidierth 10/07\n% Copyright Š The Author & King's College London 2007\n% -------------------------------------------------------------------------\n\n\n% ---------------Argument checks---------------\nif nargin<3\n error('Not enough input arguments');\nend\n\nif np<2\n error('np must be >=2');\nend\n\nif nargin<4\n pos='post';\nend\n%---------------------------------------------\n\n%------------------MATRIX--------------------\n% Deal with matrix input.\n% Apply function to each column via recursive calls\ncols=size(x,2);\nif cols>1\n y=zeros(npred, cols);\n a=zeros(cols, np+1);\n for k=1:size(x,2)\n [y(:,k) a(k,:)]=lpredict(x(:,k), np, npred, pos);\n end\n return\nend\n%---------------------------------------------\n\n\n% ---------------MAIN FUNCTION---------------\n% Order input sequence\nif nargin==4 && strcmpi(pos,'pre')\n x=x(end:-1:1);\nend\n\n% Get the forward linear predictor coefficients via the LPC\n% function\ntry\n a=lpc(x,np);\ncatch\n % LPC missing?\n m=lasterror();\n if strcmp(m.identifier, 'MATLAB:UndefinedFunction')\n error('Requires the LPC function from the Signal Processing Toolbox');\n else\n rethrow(lasterror);\n end\nend\n\n% Negate coefficients, and get rid of a(1)\ncc=-a(2:end);\n\n% Pre-allocate output\ny=zeros(npred,1);\n% Seed y with the first value\ny(1)=cc*x(end:-1:end-np+1);\n% Next np-1 values\nfor k=2:min(np,npred)\n y(k)=cc*[y(k-1:-1:1); x(end:-1:end-np+k)];\nend\n% Now do the rest\nfor k=np+1:npred\n y(k)=cc*y(k-1:-1:k-np);\nend\n\n% Order the output sequence if required\nif nargin==4 && strcmpi(pos,'pre')\n y=y(end:-1:1);\nend\n\nreturn\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16798-lpredict/lpredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7603389770525489}} {"text": "function B = adjugate(A)\n\n% This finds the adjugate (adjoint) of square matrix A,\n% and is valid even if A is singular or complex-valued.\n% With u, s, and v obtained from [u,s,v] = svd(A), it\n% makes use of the identity adj(A) = det(u*v')*v*adj(s)*u',\n% which holds even if A and s are singular. The expression,\n% diag(prod(reshape(s0(ix),n-1,n),1)), accomplishes the\n% evaluation of adj(s), each of whose diagonal elements\n% is the product of all but one of the diagonal elements\n% of s. This requires that A be n x n where n >= 2.\n% Roger Stafford - 10/18/06\n\n[m,n] = size(A);\nif (m ~= n) | (n < 2)\n error('Matrix A should be size n x n with n >= 2.')\nend\n[u,s,v] = svd(A);\ns0 = diag(s);\nix = toeplitz(ones(n-1,1),[1 zeros(1,n-1)]) ...\n + repmat((1:n-1)',1,n);\nB = det(u*v')*v*diag(prod(reshape(s0(ix),n-1,n),1))*u';\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/12692-adjugate-adjoint-of-a-square-matrix/adjugate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7603320682735119}} {"text": "% 3D rotatin about Y\nfunction rot_y = rotMatY_3D(ty) \n\n\trot_y = [cos(ty)\t 0.0\t\tsin(ty);\n\t 0.0\t\t \t 1.0\t\t0.0;\n\t\t -sin(ty)\t 0.0\t\tcos(ty) ];\n\t\t \nend\t\n", "meta": {"author": "JunaidCS032", "repo": "MOTBeyondPixels", "sha": "8bf3c417fbcbf3956b0e4381c6bb53b6c396fd94", "save_path": "github-repos/MATLAB/JunaidCS032-MOTBeyondPixels", "path": "github-repos/MATLAB/JunaidCS032-MOTBeyondPixels/MOTBeyondPixels-8bf3c417fbcbf3956b0e4381c6bb53b6c396fd94/src/rotMatY_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7603320627630393}} {"text": "function [z, r] = fisherz(r)\n% Fisher's r to z' transform, and the inverse\n%\n% :Outputs:\n%\n% **z:**\n% z = z', treating input r as correlation\n%\n% **r:**\n% treating input r as a z' score\n\n z = .5 .* log((1+r) ./ (1-r)); % Fisher's r-to-z transform\n\n if nargout > 0\n r = (exp(2.*r) - 1) ./ (exp(2.*r) + 1); % inverse\n 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/Statistics_tools/fisherz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.760312610168607}} {"text": "npts=1000;\nntaps = 5;\nb =ones(1, ntaps) / ntaps; % create filter coefficients for 5- point moving average\n\nx=(rand(npts,1)*2)-1; % raw data from -1 to +1\nfiltered_data=filter(b,1,x); % filter using 'b' coefficients\n\nsubplot(2,1,1); % 1st subplot\nplot(x); % plot raw data\ntitle('Raw Data');\nsubplot(2,1,2); % 2nd subplot\nplot(filtered_data); %plot filtered data\ntitle('Filtered Data');\nxlabel('Time');\n\n\n% Perform FFT on original and filtered signal\nfftpts=npts; % number points in FFT\nhpts=fftpts/2; % half number of FFT points\nx_fft=abs(fft(x))/hpts; %scaled FFT of original signal\nfiltered_fft=abs(fft(filtered_data))/hpts; %scaled FFT of filtered signal\n\nsubplot(2,1,1) %1st subplot\nplot(x_fft(1:hpts)); %plot first half of data points\ntitle('Raw Data');\nsubplot(2,1,2) %2nd subplot\nplot(filtered_fft(1:hpts));%plot first half data points\ntitle('Filtered Data');\nxlabel('Frequency');\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/MATLABsimplified/my_fir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7603126044633636}} {"text": "function Q = costMat(tau, r)\n%costMat constructs a cost matrix, Q for a single segment\n% r: The order of the derivative subjected to optimization\n% ex) r = 4: minimum snap, r = 2: minimum acceleration\n\n% nth order poly\nn = 2*r+1;\n\nQ = zeros(n+1);\nQQ = zeros(n+1,n+1,length(r));\n% eg optimizing 4th derivative\n% r = 4;\n% row\nfor rr = 1:length(r)\n for i=0:size(Q,1)-1\n % column\n for j=0:size(Q,2)-1\n if i >= r(rr) && j >= r(rr)\n m = 0:r(rr)-1;\n QQ(i+1,j+1,rr) = 2*prod((i-m).*(j-m))*tau^(i+j-2*r(rr)+1)/(i+j-2*r(rr)+1);\n end\n end\n end\nend\n\nfor i = 1:length(r)\n Q = Q + QQ(:,:,i);\nend", "meta": {"author": "yorgoon", "repo": "minimum-snap-geometric-control", "sha": "efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac", "save_path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control", "path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control/minimum-snap-geometric-control-efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac/poly_optimization/costMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7602816369539401}} {"text": "function cnk = combin ( n, k )\n\n%*****************************************************************************80\n%\n%% COMBIN computes the combinatorial coefficient C(N,K).\n%\n% Discussion:\n%\n% Real arithmetic is used, and C(N,K) is computed directly, via\n% Gamma functions, rather than recursively.\n%\n% C(N,K) is the number of distinct combinations of K objects\n% chosen from a set of N distinct objects. A combination is\n% like a set, in that order does not matter.\n%\n% C(N,K) = N% / ( (N-K)% * K% )\n%\n% Example:\n%\n% The number of combinations of 2 things chosen from 5 is 10.\n%\n% C(5,2) = ( 5 * 4 * 3 * 2 * 1 ) / ( ( 3 * 2 * 1 ) * ( 2 * 1 ) ) = 10.\n%\n% The actual combinations may be represented as:\n%\n% (1,2), (1,3), (1,4), (1,5), (2,3),\n% (2,4), (2,5), (3,4), (3,5), (4,5).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the value of N.\n%\n% Input, integer K, the value of K.\n%\n% Output, real CNK, the value of C(N,K)\n%\n if ( n < 0 )\n\n cnk = 0.0;\n\n elseif ( k == 0 )\n\n cnk = 1.0;\n\n elseif ( k == 1 )\n\n cnk = n;\n\n elseif ( 1 < k && k < n - 1 )\n\n facn = gammaln ( n + 1 );\n fack = gammaln ( k + 1 );\n facnmk = gammaln ( n - k + 1 );\n\n cnk = round ( exp ( facn - fack - facnmk ) );\n\n elseif ( k == n - 1 )\n\n cnk = n;\n\n elseif ( k == n )\n\n cnk = 1.0;\n\n else\n\n cnk = 0.0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/combin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.760279336242308}} {"text": "function [ delay, N_i ] = delayest_iterative(u2,u1,N_i_max,d_tol);\n%[ delay, N_i ] = delayest_iterative(u2,u1,N_i_max,d_tol);\n%Estimates delay using successive parabolic interpolation of the cross \n%correlation function (interpolated using Nyquist sampling theorem).\n%N_i_max is the maximum number of iterations\n%d_tol is the tolerance to stop at (samples)\n\n% Copyright Travis Wiens 2009 travis.mlfx@nutaksas.com\n\nif nargin<3\n\tN_i_max=20;%max iterations\nend\nif nargin<4\n\td_tol=1e-5;%stopping tolerance\nend\n\nN_p=numel(u2);%number of points\n\nU1=fft(u1);\nU2=fft(u2);\nXC=U2.*conj(U1);%circular cross correlation\nxc=ifft(XC);\n[tmp idx]=max(xc);%find peak\n\nR=zeros(1,3);%three points to interpolate through\nR(2)=xc(idx);\n\n%neighbors\nif idx==1\n R(1)=xc(end);\n R(3)=xc(2);\nelseif idx==numel(xc)\n R(1)=xc(end-1);\n R(3)=xc(1);\nelse\n R(1)=xc(idx-1);\n R(3)=xc(idx+1);\nend\n\nd_R=[-1 0 1]+idx-1;%delay corresponding to R\n\n\nfor N_i=1:N_i_max\n [d_R_max]=crit_interp_p(R,d_R);%interpolate peak from R using parabola\n R_max=fourier_series(XC,d_R_max);%calculate new xc from Fourier coefficients\n if d_R_max1) | any(S(:)<-1),\n error('Values of similarity must be in [-1,1]');\nend\n\nD=1-S;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/icasso/sim2dis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7602793229273086}} {"text": "function [xi,w]=quadraturePoints1D(n,algorithm,c1)\n%%QUADRATUREPOINTS1D Obtain quadrature points and weights to efficiently\n% numerically evaluate 1D integrals involving various weighting\n% functions. The quadrature points and weights are based off\n% properties of orthogonal polynomials. The evaluation of a\n% continuous integral using cubature points is\n% integral_lowL^upL w(x)*f(x) dx=sum_{i=1}^n w_i*f(xi(i))\n% where the equality holds up for all polynomials up to a\n% particular degree. For high-order polynomials and other\n% functions, quadrature integration is just an approximation.\n%\n%INPUTS: n A positive integer such that 2n-1 is the highest degree to\n% which the quadrature points are accurate. n points are returned\n% by the function.\n% algorithm This specifies the type of weighting function and the range of\n% the integral. These points can generally be transformed for\n% integrals over other regions/ with other parameters. Possible\n% values are\n% 0 (The default if omitted or an empty matrix is passed) The\n% weighting function is w(x)=1/(sqrt(2*pi))*exp(-x^2/2), the\n% integration interval is (-Inf,Inf). The algorithm of [2] is\n% used with parameters from Table 22.7 in Ch. 22 of [1].\n% 1 w(x)=exp(-x^2) on the interval (-Inf,Inf). The algorithm of\n% [2] is used with parameters from Table 22.7 in Ch. 22 of [1].\n% 2 w(x)=1 on (-1,1). The function GaussLegendrePoints1D is used.\n% Note that the transformation \n% xiNew=xi*(b-a)/2+(b+a)/2;\n% wNew=w*(b-a)/2;\n% can be used to transform the points and weights to the\n% weighting function w(y)=1 on the range (a,b).\n% 3 w(x)=(1-x^2)^(c1-1/2) on (-1,1) with c1>-1/2. The algorithm of\n% [2] is used with the values from Table 22.7 of [1]. Formula 10\n% is used for the c1=0 case. This becomes numerically unstable\n% for c1 close to but not equal to zero.\n% 4 w(x)=exp(-x) on (0,Inf). The algorithm of [2] is used with the\n% values from Table 22.7 of [1].\n% 5 w(x)=x^c1*exp(-x) on (0,Inf). The algorithm of [2] is used\n% with the values from Table 22.7 of [1] for c1>-1.\n% 6 w(x)=(1+x)^c1 on (-1,1) for c1>-1. This is a special case of\n% the Jacobi polynomials. The algorithm of [2] is used with\n% values from Table 22.7 of [1].\n% 7 w(x)=x^c1 on (0,1), c1>-1. The algorithm of [2] is used. The\n% three-term recursion was derived by explicitly evaluating\n% the integrals with the desired orthogonality constraints\n% until a pattern could be identified for an arbitrary order.\n% 8 w(x)=|x|^c1 on (-1,1), c1>=0 and c1 is an integer. The\n% algorithm of [2] is used. The three-term recursion was derived\n% by explicitly evaluating the integrals with the desired\n% orthogonality constraints until a pattern could be identified\n% for an arbitrary order. Separate patterns for even and odd\n% integers were found.\n% 9 w(x)=|x|^c1*exp(-x^2) on (-Inf,Inf), c1>=0 and c1 is an\n% integer. The algorithm of [2] is used. The three-term\n% recursion was derived by explicitly evaluating the integrals\n% with the desired orthogonality constraints until a pattern\n% could be identified for an arbitrary order. Separate patterns\n% for even and odd integers were found.\n% 10 w(x)=1/sqrt(1-x^2) on (-1,1). The formula in 25.4.38 in [1] is\n% used. Note that the transformation\n% xiNew=(b+a)/2+xi*(b-a)/2; can be used to change the\n% quadrature points to the weighting function\n% w(y)=1/sqrt((y-a)*(b-y)) on (a,b).\n% 11 w(x)=sqrt(1-x^2) on (-1,1). The formula in 25.4.40 in [1] is\n% used. Note that the transformation xiNew=(b+a)/2+xi*(b-a)/2\n% can be used to change the quadrature points to the weighting\n% function w(y)=sqrt((y-a)*(b-y)) on (a,b).\n% 12 w(x)=sqrt(x/(1-x)) on (0,1). The formula in 25.4.42 in [1] is\n% used. Note that the transformation xiNew=a+(b-a)*xi can be\n% used to change the quadrature points to the weighting\n% function w(x)=sqrt((x-a)/(b-x)) on (a,b).\n% c1 This is a parameter that is only used with certain algorithms\n% described above.\n%\n%OUTPUTS: xi A 1 X n vector containing the quadrature points.\n% w An nX1 vector of the weights associated with the quadrature\n% points. Depending on the algorithm, these may or may not sum\n% to one.\n%\n%In the algorithms implemented in this function, with the exception of 11\n%and 12, this function obtains points by passing parameters for a three-\n%point recursion to the orthoPolyZerosFromRecur function.\n%\n%Note that the function linCubPoints2MultiDim can be given a handle to this\n%function to produce multi-dimensional cubature formula.\n%\n%REFERENCES:\n%[1] Abramowitz, M. and Stegun, I. A. (Eds.). \"Orthogonal Polynomials.\"\n% in Ch. 22, 25 in Handbook of Mathematical Functions with Formulas,\n% Graphs, and Mathematical Tables, 9th printing. New York: Dover, 1972.\n%[2] G. H. Golub and J. H. Welsh, \"Calculation of Gauss quadrature rules,\"\n% Mathematics of Computation, vol. 23, pp. 221-230, 1969.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(algorithm))\n algorithm=0;\nend\n\nswitch(algorithm)\n case 0%Weighting function w(x)=1/(sqrt(2*pi))*exp(-x^2/2)\n %on (-Inf,Inf)\n mu0=1;\n a=@(i)1;\n b=@(i)0;\n c=@(i)i-1;\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 1%Weighting function w(x)=exp(-x^2) on (-Inf,Inf)\n mu0=sqrt(pi);\n a=@(i)2;\n b=@(i)0;\n c=@(i)2*(i-1);\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 2%Weighting function w(x)=1 on (-1,1)\n [xi,w]=GaussLegendrePoints1D(n);\n case 3%Weighting function w(x)=(1-x^2)^(c1-1/2) on (-1,1) with c1>-1/2\n %and c1~=0. Given c1=0, Formula 10 is used.\n if(c1==0)\n [xi,w]=quadraturePoints1D(n,10);\n return;\n end\n \n mu0=(sqrt(pi)*gamma((1/2)+c1))/gamma(1+c1);\n a=@(i)2*(i+c1-1)/i;\n b=@(i)0;\n c=@(i)(i+2*c1-2)/i;\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 4%Weighting function w(x)=exp(-x) on (0,Inf)\n mu0=1;\n a=@(i)-1/i;\n b=@(i)(2*(i-1)+1)/i;\n c=@(i)(i-1)/i;\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 5%Weighting function w(x)=x^c1*exp(-x) on (0,Inf) for c1>-1.\n mu0=gamma(1+c1);\n a=@(i)(-1/i);\n b=@(i)(2*i-1+c1)/i;\n c=@(i)(i-1+c1)/i;\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 6%Weighting function w(x)=(1+x)^c1 on (-1,1) for c1>-1.\n %This uses a special case of the Jacobi polynomials.\n mu0=2^(c1+1)/(c1+1);\n a=@(i)(2*i+c1-1)*(2*i+c1)*(2*i+c1-2)/(2*i*(i+c1)*(2*i+c1-2));\n b=@(i)(2*i+c1-1)*(-c1^2)/(2*i*(i+c1)*(2*i+c1-2));\n c=@(i)2*(i-1)*(i+c1-1)*(2*i+c1)/(2*i*(i+c1)*(2*i+c1-2));\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 7%Weighting function w(x)=x^c1 on (0,1) for c1>-1\n mu0=1/(1+c1);\n a=@(k)1;\n b=@(k)(-(c1^2+(2*(k-1)+1)*c1+2*k*(k-1))/((2*(k-1)+c1)*(2*k+c1)));\n c=@(k)((k-1)^2*(c1+k-1)^2/((2*k-3+c1)*(2*k-2+c1)^2*(2*k-1+c1)));\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 8%Weighting function w(x)=|x|^c1 on (-1,1), c1>=0 and c1 is an\n %integer.\n if(mod(c1,2)==0)%Even integer\n c1=c1/2;\n mu0=2/(1+2*c1);\n a=@(k)1;\n b=@(k)0;\n c=@(k)((k-1+2*c1*mod(k+1,2))^2/((2*k-3+2*c1)*(2*k-1+2*c1)));\n else%Odd integer\n c1=(c1-1)/2;\n mu0=1/(1+c1);\n a=@(k)1;\n b=@(k)0;\n c=@(k)(((k-mod(k,2))/2+mod(k+1,2)*c1)^2/((k-1+c1)*(k+c1)));\n end\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 9%Weighting function w(x)=|x|^c1*exp(-x^2) on (-Inf,Inf), c1>=0\n %and c1 is an integer.\n if(mod(c1,2)==0)%Even integer\n c1=c1/2;\n mu0=gamma(c1+1/2);\n a=@(k)1;\n b=@(k)0;\n c=@(k)((k-1)/2+c1*mod(k+1,2));\n else%Odd integer\n c1=(c1-1)/2;\n mu0=factorial(c1);\n a=@(k)1;\n b=@(k)0;\n c=@(k)((k-mod(k,2))/2+c1*mod(k+1,2));\n end\n [xi,w]=orthoPolyZerosFromRecur(n,a,b,c,mu0);\n case 10%Weighting function w(x)=1/sqrt(1-x^2) on (-1,1) from 25.4.38 in\n %[1].\n xi=cos((2*(1:n)-1)*pi/(2*n));\n w=repmat(pi/n,[n,1]);\n case 11%Weighting function w(x)=sqrt(1-x^2) on (-1,1) from 25.4.40 in\n %[1].\n xi=cos((1:n)*pi/(n+1));\n w=(pi/(n+1))*sin((1:n)'*pi/(n+1)).^2;\n case 12%Weighting function w(x)=sqrt(x/(1-x)) on (0,1) from 25.4.42 in\n %[1].\n xi=cos((pi/2)*((2*(1:n)-1)/(2*n+1))).^2;\n w=(2*pi/(2*n+1))*xi';\n otherwise\n error('Unknown algorithm specified');\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/quadraturePoints1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7602793229273086}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n%Parseval's Theorem \n\n%x(t)=exp(-t^2)\n\nsyms t w\nx=exp(-t^2);\nEt=int((abs(x))^2,t,-inf,inf) ; \neval(Et)\nX=fourier(x,w);\nEw=(1/(2*pi))*int((abs(X))^2,w,-inf,inf);\neval(Ew)\n\n\n%x(t)=exp(-t)u(t)\nx=exp(-t) *heaviside(t);\nEt=int((abs(x))^2,t,-inf,inf)\nX=fourier(x,w);\nInteg= int((abs(X))^2,w,-inf,inf);\nEw=(1/(2*pi))*Integ;\neval(Ew)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/6/c67.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7602793194282582}} {"text": "function [ w, xyz ] = tetrahedron_unit_o01 ( )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_UNIT_O01 returns a 1 point quadrature rule for the unit tetrahedron.\n%\n% Discussion:\n%\n% The integration region is:\n%\n% 0 <= X\n% 0 <= Y\n% 0 <= Z\n% X + Y + Z <= 1.\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% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Output, real W(1), the weights.\n%\n% Output, real XYZ(3,1), the abscissas.\n%\n w(1:1,1) = [ ...\n 1.0 ];\n\n xyz(1:3,1:1) = [ ...\n 0.25000000000000000000, 0.25000000000000000000, 0.25000000000000000000 ]';\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tetrahedron_felippa_rule/tetrahedron_unit_o01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7602793192858152}} {"text": "% gabor2d() - generate a two-dimensional gabor matrice.\n%\n% Usage:\n% >> [ matrix ] = gabor2d(rows, columns);\n% >> [ matrix ] = gabor2d( rows, columns, freq, ...\n% angle, sigmaR, sigmaC, meanR, meanC, dephase, cut)\n% Example :\n%\t>> imagesc(gabor2d( 50, 50))\n%\n% Inputs:\n% rows - number of rows \n% columns - number of columns \n% freq - frequency of the sinusoidal function in degrees (default: 360/rows)\n% angle - angle of rotation of the resulting 2-D array in\n% degrees of angle {default: 0}.\n% sigmaR - standard deviation for rows {default: rows/5}\n% sigmaC - standard deviation for columns {default: columns/5}\n% meanR - mean for rows {default: center of the row}\n% meanC - mean for columns {default: center of the column}\n% dephase - phase offset in degrees {default: 0}. A complex Gabor wavelet \n% can be build using gabor2dd(...., 0) + i*gabor2d(...., 90), \n% 0 and 90 being the phase offset of the real and imaginary parts\n% cut\t - percentage (0->1) of maximum value below which to remove values \n% from the matrix {default: 0}\n% Ouput:\n% matrix - output gabor matrix\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction mat = gabor2d( sizeX, sizeY, freq, angle, sigmaX, sigmaY, meanX, ...\nmeanY, dephase, cut);\n\nif nargin < 2\n\thelp gabor2d\n\treturn; \nend;\nif nargin < 3\n\tfreq = 360/sizeX;\nend;\nif nargin < 4\n\tangle = 0;\nend;\nif nargin < 5\n\tsigmaX = sizeX/5;\nend;\nif nargin < 6\n\tsigmaY = sizeY/5;\nend;\nif nargin < 7\n\tmeanX = (sizeX+1)/2;\nend;\nif nargin < 8\n\tmeanY = (sizeY+1)/2;\nend;\nif nargin < 9\n\tdephase = 0;\nend;\nif nargin < 10\n\tcut = 0;\nend;\nfreq = freq/180*pi;\n\nX = linspace(1, sizeX, sizeX)'* ones(1,sizeY);\nY = ones(1,sizeX)' \t\t * linspace(1, sizeY, sizeY);\n%[-sizeX/2:sizeX/2]'*ones(1,sizeX+1);\n%Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2];\n\nrotatedmat = ((X-meanX)+i*(Y-meanY)) * exp(i*angle/180*pi);\nmat = sin(real(rotatedmat)*freq + dephase/180*pi).*exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)...\n\t\t\t\t+((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... \n \t\t\t/((sigmaX*sigmaY)^(0.5)*pi); \n\nif cut > 0\n\tmaximun = max(max(mat))*cut;\n\tI = find(mat < maximun);\n\tmat(I) = 0;\nend;\n\nreturn;\n\n% other solution\n% --------------\n\nfor X = 1:sizeX\n for Y = 1:sizeY\n mat(X,Y) = sin(real((X-meanX+j*(Y-meanY))*exp(i*angle/180*pi))*freq + dephase/180*pi) ...\n .*exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)...\n +((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... \n \t\t\t/((sigmaX*sigmaY)^(0.5)*pi); \n end;\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/gabor2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.760279319143372}} {"text": "%% Example of de-meaning\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n%% Generate random dataset\nds=cosmo_synthetic_dataset('nchunks',4,'ntargets',3);\n\n% add some constant to all data\nds.samples=ds.samples+2;\n\n% show dataset\nsubplot(2,2,1);\nimagesc(ds.samples,[-4 4])\ntitle('before demeaning');\nsubplot(2,2,2);\nhist(ds.samples(:),10)\nxlim([-6 6]);\n\n%% Split the dataset by chunks\n% >@@>\nsplits=cosmo_split(ds,{'chunks'},1);\n% <@@<\nnsplits=numel(splits);\n\n% allocate space for output\noutputs=cell(nsplits,1);\n\n% treat each element in splits seperately, and subtract the mean for each\n% feature seperately\nfor k=1:nsplits\n d=splits{k};\n % >@@>\n\n % mean over samples, for each feature\n mu=mean(d.samples,1);\n\n % subtract the mean.\n % equivalent, but less efficient, is:\n % nsamples=size(d.samples,1);\n % d.samples=d.samples-repmat(mu,nsamples,1);\n %\n d.samples=bsxfun(@minus,d.samples,mu);\n % <@@<\n\n % store output\n outputs{k}=d;\nend\n\nds_demeaned=cosmo_stack(outputs);\n\n% show dataset\nsubplot(2,2,3);\nimagesc(ds_demeaned.samples,[-4 4])\ntitle('after demeaning');\nsubplot(2,2,4);\nhist(ds_demeaned.samples(:),10);\nxlim([-6 6]);\n\n%% Alternative approach to demeaning\n\n% note: the samples in the output are in a different order than the input,\n% but otherwise the same\ndemeaner=@(x)bsxfun(@minus,x,mean(x,1)); % function handle as helper\nds_demeaned_alt=cosmo_fx(ds,demeaner,'chunks');\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/examples/run_demean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.760245325585821}} {"text": "function [ o, x, w ] = cn_geg_02_xiu ( n, alpha )\n\n%*****************************************************************************80\n%\n%% CN_GEG_02_XIU implements the Xiu rule for region CN_GEG.\n%\n% Discussion:\n%\n% The rule has order\n%\n% O = N + 1.\n%\n% The rule has precision P = 2.\n%\n% CN_GEG is the cube [-1,+1]^N with the Gegenbauer weight function\n%\n% w(alpha;x) = product ( 1 <= i <= n ) (1-x(i)^2)^alpha.\n%\n% with -1.0 < alpha.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dongbin Xiu,\n% Numerical integration formulas of degree two,\n% Applied Numerical Mathematics,\n% Volume 58, 2008, pages 1515-1520.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, real ALPHA, the parameter.\n% -1.0 < ALPHA.\n%\n% Input, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CN_GEG_02_XIU - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'CN_GEG_02_XIU - Fatal error!' );\n end\n\n o = n + 1;\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n for j = 1 : o\n\n i = 0;\n for r = 1 : floor ( n / 2 )\n arg = 2 * r * ( j - 1 ) * pi / ( n + 1 );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * cos ( arg );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * sin ( arg );\n end\n\n if ( i < n )\n i = i + 1;\n x(i,j) = r8_mop ( j - 1 );\n end\n\n end\n\n gamma0 = 1.0;\n delta0 = 0.0;\n c1 = 1.0 / ( 2.0 * alpha + 3.0 );\n\n x(1:n,1:o) = ( sqrt ( gamma0 * c1 ) * x(1:n,1:o) - delta0 ) / gamma0;\n\n expon = 0;\n volume_1d = c1_geg_monomial_integral ( alpha, expon );\n volume = volume_1d ^ n;\n\n w(1:o) = volume / o;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/cn_geg_02_xiu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7602453171210001}} {"text": "function A = metric_04 ( p )\n\n%*****************************************************************************80\n%\n%% METRIC_04 evaluates metric #4 at any point.\n%\n% Discussion:\n%\n% This routine evaluates the matrix that determines the metric\n% at a point.\n%\n% This particular matrix reduces distances when evaluated far from the origin.\n%\n% It is diagonal, and it is spatially varying.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P(2), the point at which the metric matrix is to\n% be evaluated.\n%\n% Output, real A[2,2], the metric matrix.\n%\n A = [ 1.0, 0.0; 0.0, 1.0 ] * ...\n ( 0.20 + ( sin ( 2 * pi * p(1) ) )^2 * ( sin ( 2 * pi * p(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/cvt_metric/metric_04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7602213552469583}} {"text": "% This matlab codes implement the adaptive residual subsampling \n% method for radial basis function 1-D initial-boundary value problem. \n%\n% Implementation : Method of lines\n% Time-stepping: 4th order Runge-Kutta method\n% Space adaptivity: Adaptive residual subsampling for RBFs\n%\n% For reference, see:\n% Adaptive residual subsampling methods for radial basis function\n% interpolation and collocation problems. submitted to Computers Math. Appl\n%\n% Tobin A. Driscoll and Alfa R.H. Heryudono 05/14/2006\n% MATLAB 7 is recommended.\n%\n% Test problem:\n% Burger's Equation\n% epsilon.u_xx - u.u_x = u_t, 0 < x < 1\n% u(0,t)=u(1,t)=0.\n\nTfin = 1;\ndt = Tfin/100;\n\nepsilon = 1e-3; theta = 1e-4;\ntheta = [theta theta/1000];\ninitcond = @(x) sin(2*pi*x) + 0.5*sin(pi*x);\n[x,c,u0] = coarserefine(initcond,[0 1],theta,13,0.75);\n\nTdone = 0;\nhan = plot(x,u0,'-ko',x,-1*x.^0,'ko','MarkerFaceColor','k','MarkerSize',2);\ntp = title('','erasemode','xor'); hold on;\nxlabel('x');ylabel('u(x,t)');\naxis([0 1 -1 1.5])\n\nwhile Tdone < Tfin\nN = length(x);\n\n[A,D1,D2] = deal(zeros(N));\nfor j=1:N\n [A(:,j),D1(:,j),D2(:,j)] = mq(x,x(j),c(j));\nend\n\nlambda = A\\eye(N);\nD1 = D1*lambda; D1([1 N],:)=[]; D1(:,[1 N])=[];\nD2 = D2*lambda; D2([1 N],:)=[]; D2(:,[1 N])=[];\n\n% Solve system of ODEs\noptions = odeset('RelTol',1e-5,'AbsTol',1e-8,'Jacobian',@Jburgers,'OutputFcn', ...\n @(t,y,flag,varargin) burgersplot(t,y,flag,varargin,x,han));\n\nset(tp,'string',sprintf('T = %.3f, N = %3i.',Tdone,N));\n[T,U] = ode15s(@burgers,[Tdone Tdone+dt],u0(2:N-1),options,epsilon,D1,D2);\n\ndisp('-----------------------');\n[x,c,u0] = coarserefine(@(xp)predictor(xp,x,[0;U(end,:)';0]),[0 1],theta,13,0.75);\nTdone = Tdone + dt;\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/11101-adaptive-residual-subsampling-for-radial-basis-functions/adaptburgers_mol/adaptburgers_mol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7601662327494262}} {"text": "function x = log_1(x,rnd)\n%LOG_ Rigorous calculation of log(1+x) for 0<=x<=1 according to rnd\n%\n% y = log_1(x)\n%\n%Internal function\n%\n\n% written 12/30/98 S.M. Rump\n% modified 08/31/98 S.M. Rump improved accuracy\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 INTLAB_STDFCTS_LOG = getappdata(0,'INTLAB_STDFCTS_LOG');\n\n setround(0)\n xs = pow2( floor(x*2^13) , -13 ); % first 13 bits\n log1xs = log(1+xs); % 1+xs exactly representable in 14 bits\n\n setround(rnd)\n d = ( x - xs ) ./ (1+xs); % 0 <= d < 2^-13\n\n % log(1+x) = log( (1+xs) * (1+d) ) , 0 <= err <= d^5/5 < 4.45e-17*d\n if rnd==-1\n log1d = ((( (-d)/4 + 1/3 ).*d - 0.5 ).*d).*d + d;\n x = log1xs + ( log1d + (-INTLAB_STDFCTS_LOG.EPS)*abs(log1xs) );\n else\n log1d = (((( d/5 - .25 ).*d + 1/3 ).*d - 0.5 ).*d).*d + d;\n x = log1xs + ( log1d + INTLAB_STDFCTS_LOG.EPS*abs(log1xs) );\n end\n\n setround(0)\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/log_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7601662317818513}} {"text": "%GENDATD Generation of 'difficult' normally distributed classes\n% \n% A = GENDATD(N,K,D1,D2,LABTYPE)\n%\n% INPUT\n% N Number of objects in each of the classes (default: [50 50])\n% K Dimensionality of the dataset (default: 2)\n% D1 Difference in mean in feature 1 (default: 3)\n% D2 Difference in mean in feature 2 (default: 3)\n% LABTYPE 'crisp' or 'soft' labels (default: 'crisp').\n%\n% OUTPUT\n% A Generated dataset\n%\n% DESCRIPTION\n% Generation of a K-dimensional 2-class dataset A of N objects.\n% Class variances are very different for the first two dimensions.\n% Separation is thereby, for small sample sizes, 'difficult'. \n% \n% D1 is the difference between the means for the first feature, D2\n% is the difference between the means for the second feature. In all\n% other directions the means are equal. The two covariance matrices\n% are equal with a variance of 1 in all directions except for the\n% second feature, which has a variance of 40. The first two feature\n% are rotated over 45 degrees to construct a strong correlation.\n% Class priors are P(1) = P(2) = 0.5.\n%\n% If N is a vector of sizes, exactly N(I) objects are generated\n% for class I, I = 1,2.\n%\n% LABTYPE defines the desired label type: 'crisp' or 'soft'. In the \n% latter case true posterior probabilities are set for the labels.\n%\n% SEE ALSO (PRTools Guide)\n% DATASETS, PRDATASETS\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: gendatd.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction A = gendatd(N,k,d1,d2,labtype)\n\n\t\t\n\tif nargin < 5, labtype = 'crisp'; end\n\tif nargin < 4, d2 = 3; end\n\tif nargin < 3, d1 = 3; end\n\tif nargin < 2, k = 2; end\n\tif nargin < 1, N = [50 50]; end\n\n\tif k < 2,\n\t\terror('Number of features should be larger than 1'),\n\tend\n\tV = ones(1,k); V(2) = 40; V = sqrt(V);\n\tp = [0.5 0.5];\n\tN = genclass(N,p);\t\n\tma = zeros(1,k);\n\tmb = zeros(1,k); mb(1:2) = [d1, d2];\n\tA = [randn(N(1),k).*V(ones(1,N(1)),:) + ma(ones(1,N(1)),:); ...\n\t randn(N(2),k).*V(ones(1,N(2)),:) + mb(ones(1,N(2)),:)];\n\tA(:,1:2) = A(:,1:2)*[1 -1; 1 1]./sqrt(2);\n\tlab = genlab(N);\n\tA = prdataset(A,lab,'name','Difficult Dataset','prior',p);\n\n\tswitch labtype\n\t case 'crisp'\n\t ;\n\t case 'soft'\n\t U = prdataset([ma(1:2);mb(1:2)],getlablist(A));\n\t G = diag(V(1:2));\n\t W = nbayesc(U,G);\n\t targets = A(:,1:2)*W*classc;\n\t A = setlabtype(A,'soft',targets);\n\t otherwise\n\t error(['Label type ' labtype ' not supported'])\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/gendatd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7599922712626238}} {"text": "function Rx=x_rot(phi)\n%X_ROT Matrix creating a rotation around the x axis by an angle phi.\n% phi: angle in radians.\n\nRx = [1 0 0; 0 cos(phi) -sin(phi);0 sin(phi) cos(phi)];\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/Common/blochsim/x_rot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7599828285462678}} {"text": "function poly_cof = r8poly_shift ( scale, shift, n, poly_cof )\n\n%*****************************************************************************80\n%\n%% R8POLY_SHIFT adjusts the coefficients of a polynomial for a new argument.\n%\n% Discussion:\n%\n% Assuming P(X) is a polynomial in the argument X, of the form:\n%\n% P(X) =\n% C(N) * X**(N-1)\n% + ...\n% + C(2) * X\n% + C(1),\n%\n% and that Z is related to X by the formula:\n%\n% Z = SCALE * X + SHIFT\n%\n% then this routine computes coefficients C for the polynomial Q(Z):\n%\n% Q(Z) =\n% C(N) * Z**(N-1)\n% + ...\n% + C(2) * Z\n% + C(1)\n%\n% so that:\n%\n% Q(Z(X)) = P(X)\n%\n% Example:\n%\n% P(X) = 2 * X**2 - X + 6\n%\n% Z = 2.0 * X + 3.0\n%\n% Q(Z) = 0.5 * Z**2 - 3.5 * Z + 12\n%\n% Q(Z(X)) = 0.5 * ( 4.0 * X**2 + 12.0 * X + 9 )\n% - 3.5 * ( 2.0 * X + 3 )\n% + 12\n%\n% = 2.0 * X**2 - 1.0 * X + 6\n%\n% = P(X)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real SHIFT, SCALE, the shift and scale applied to X,\n% so that Z = SCALE * X + SHIFT.\n%\n% Input, integer N, the order of the polynomial.\n%\n% Input, real POLY_COF(N), the coefficient array in terms of the X variable.\n%\n% Output, real POLY_COF(N), the coefficient array in terms of the Z variable.\n%\n for i = 1 : n\n poly_cof(i+1:n) = poly_cof(i+1:n) / scale;\n end\n\n for i = 1 : n\n for j = n-1 : -1 : i\n poly_cof(j) = poly_cof(j) - shift * poly_cof(j+1);\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/divdif/r8poly_shift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8596637577007393, "lm_q1q2_score": 0.759976538780063}} {"text": "%% SQUARESTOKE Stokes equations on the unit square\n%\n% SQUARESTOKE computes P2-P1 approximations of the Stokes equations in\n% the unit square on a sequence of meshes obtained by uniform refinement.\n% It plots the approximation error (pressue in L2 norm and velocity in H1\n% norm) vs the number of dof. Other types of FEM approximation can be\n% computed similarly.\n% \n% See also StokesP2P1, collidingflow, squarePoisson \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; \nclear variables;\n%% Set up\nmaxIt = 4;\nN = zeros(maxIt,1); \nh = zeros(maxIt,1);\nerru = zeros(maxIt,1); \nerrp = zeros(maxIt,1);\n\n%% Generate initial mesh\n[node,elem] = squaremesh([0 1 0 1], 0.25);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% PDE and options\npde = Stokesdata2;\n% pde = Stokesdata3;\n\n%% Finite Element Method \nfor k = 1:maxIt\n % refine mesh\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n % solve the equation\n [soln,eqn] = StokesP2P1(node,elem,bdFlag,pde);\n% [soln,eqn] = StokesP2P0(node,elem,bdFlag,pde);\n% [soln,eqn] = StokesisoP2P1(node,elem,bdFlag,pde);\n% [soln,eqn] = StokesisoP2P0(node,elem,bdFlag,pde);\n% [soln,eqn] = StokesCRP0(node,elem,bdFlag,pde);\n% [soln,eqn] = StokesP1bP1(node,elem,bdFlag,pde);\n uh = soln.u;\n ph = soln.p;\n N(k) = length(uh)+length(ph);\n h(k) = 1./(sqrt(size(node,1))-1);\n if N(k) < 2e3 % show solution for small size\n figure(1); showresult(node,elem,ph); \n end\n % compute error\n uI = pde.exactu([node; (node(eqn.edge(:,1),:)+node(eqn.edge(:,2),:))/2]);\n erru(k) = sqrt((uh-uI(:))'*eqn.A*(uh-uI(:)));\n errp(k) = getL2error(node,elem,pde.exactp,ph);\nend\n\n%% Plot convergence rates\nfigure(2);\nshowrateh2(h,erru,1,'-*','|u_I-u_h|_1',...\n h,errp,1,'m-+','|| p-p_h||');\n\nfprintf('\\n');\ndisp('Table: Error')\ncolname = {'#Dof','h','|u_I-u_h|_1','||p-p_h||'};\ndisptable(colname,N,[],h,'%0.3e',erru,'%0.5e',errp,'%0.5e');\n% figure;\n% set(gcf,'Units','normal'); \n% set(gcf,'Position',[0.25,0.25,0.55,0.4]);\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Stokes/squareStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7599765345644188}} {"text": "function RND = mnbinrnd(W, K, M, N)\n%MNBINRND Maszle's negative binomial random numbers\n%\n% RND = MNBINRND(W, K, M, N) \n%\n% returns an M x N matrix of random numbers chosen from a negative\n% binomial distribution with mean W and aggregation K.\n%\n% This is an alternate form of the negative binomial commonly\n% employed in biology to describe aggregated count data. \n% W and K are related to the traditional parametrization by the\n% relationships: \n%\n% P = K/(K + W), and K = R,\n%\n% with the distinction that K is any positive real number, not just\n% positive integers. K < 1 yields a highly skewed distribution.\n%\n% The size of RND is the common size of W and K if both are matrices.\n% If either parameter is a scalar, the size of RND is the size of\n% the other parameter. \n%\n% Alternatively, RND = NBINRND(W, K, M, N) returns an M x N matrix. \n%\n% Requires stats toolbox.\n%\n% See also MNBINPDF\n\n\n%----------------------------------------------------------------------\n% Copyright (c) 1999. Don R. Maszle. All rights reserved.\n%\n% -- Revisions -----\n% Date: 4 March 1999\n% Author: Don R. Maszle\n% E-mail: maze@sparky.berkeley.edu\n% -- SCCS ---------\n%----------------------------------------------------------------------\n\n\n%-- Perform standard argument checks for random generators\n\n\nif (nargin < 2)\n error('Requires at least two parameters.'); \nend\n\n\nif (nargin == 2)\n [iError nRows nCols] = rndcheck(2,2,K,W);\n if (max(size(K)) == 1)\n K = K(ones(nRows,1),ones(nCols,1));\n end\n if (max(size(W)) == 1)\n W = W(ones(nRows,1),ones(nCols,1));\n end\nend\n\n\nif (nargin == 3)\n [iError nRows nCols] = rndcheck(3,2,K,W,M);\n K = K(ones(M(1),1),ones(M(2),1));\n W = W(ones(M(1),1),ones(M(2),1));\n\n\nend\n\n\nif (nargin == 4)\n [iError nRows nCols] = rndcheck(4,2,K,W,M,N);\n K = K(ones(M,1), ones(N,1));\n W = W(ones(M,1), ones(N,1));\nend\n\n\nif (iError > 0)\n error('Size information is inconsistent.');\nend\n\n\n\n% From \"Non-uniform random variate generation\", Luc Devroye, New York,\n% Springer-Verlag, 1986. (Thanks to Charles N. Haas, Drexel U. for\n% pointing me to this source.)\n%\n% As Devroye derives, the negative binomial can be expressed as a\n% Poisson of a Gamma with parameters K and (1-P)/P, where P = K/(K + W).\n\n\nRND = poissrnd(gamrnd(K, W./K, M, 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/201-mnbinrnd/mnbinrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7599526900389275}} {"text": "function [ a, seed ] = r8pp_random ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8PP_RANDOM randomizes a R8PP matrix.\n%\n% Discussion:\n%\n% The R8PP storage format is appropriate for a symmetric positive\n% definite matrix. Only the upper triangle of the matrix is stored,\n% by successive partial columns, in an array of length (N*(N+1))/2,\n% which contains (A11,A12,A22,A13,A23,A33,A14,...,ANN) \n%\n% The matrix is computed by setting a \"random\" upper triangular\n% Cholesky factor R, and then computing A = R'*R.\n% The randomness is limited by the fact that all the entries of\n% R will be between 0 and 1. A truly random R is only required\n% to have positive entries on the diagonal.\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 order of the matrix.\n% N must be positive.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real A((N*(N+1))/2), the R8PP matrix.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n a(1:(n*(n+1))/2) = 0.0;\n\n for i = n : -1 : 1\n%\n% Set row I of R.\n%\n for j = i : n\n ij = i + ( j * ( j - 1 ) ) / 2;\n [ a(ij), seed ] = r8_uniform_01 ( seed );\n end\n%\n% Consider element J of row I, last to first.\n%\n for j = n : -1 : i\n%\n% Add multiples of row I to lower elements of column J.\n%\n ij = i + ( j * ( j - 1 ) ) / 2;\n\n for k = i+1 : j\n kj = k + ( j * ( j - 1 ) ) / 2;\n ik = i + ( k * ( k - 1 ) ) / 2;\n a(kj) = a(kj) + a(ik) * a(ij);\n end\n%\n% Reset element J.\n%\n ii = i + ( i * ( i - 1 ) ) / 2;\n a(ij) = a(ii) * a(ij);\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/linplus/r8pp_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7599526726738605}} {"text": "% 计算差商\nfunction [p, q] = d_d(x,y)\n%\n% 参数说明:\n% 输入参数: x 为节点,y 为函数值(注意:向量 x 与向量 y 的长度必须一致)\n% 输出参数:\n% p 包含所有差商,即差商表中的所有值\n% q 为差商表中对角线的值\n\nm = length(x);\nx = x(:);\np = zeros(m, m+1);\np(:,1) = x; \np(:,2) = y(:);\nfor k = 3 : m+1\n p(k-1:m, k) = diff(p(k-2:m, k-1)) ./ ( x(k-1:m) - x(1:m+2-k) );\nend\nq = diag(p(1:m,2:m+1));\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/d_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7598867574973018}} {"text": "function [sqrtx,sqrtinvx,di] = randiwishart(sigma,df,di)\n%RANDIWISHART Generate inverse Wishart random matrix\n% W=RANDIWISHART(SIGMA,DF) generates a random matrix W from the inverse\n% Wishart distribution with parameters SIGMA and DF. The inverse of W\n% has the Wishart distribution with covariance matrix inv(SIGMA) and DF\n% degrees of freedom.\n%\n% W=RANDIWISHART(SIGMA,DF,DI) expects DI to be the Cholesky factor of\n% the inverse of SIGMA.\n%\n% [W,DI]=RANDIWISHART(SIGMA,DF) returns DI so it can be used again in\n% future calls to RANDIWISHART.\n\nn = size(sigma,1);\nif (df=X\n% HUBER_POS(X) = X^2 if 0<=X<=1\n% 2*X-1 if X>=1\n%\n% HUBER_POS(X,M) is the monotonic Huber-style penalty function of\n% halfwidth M, M.^2.*HUBER_POS(X./M). M must be real and positive.\n%\n% HUBER_POS(X,M,T) computes the monotonic Huber-style penalty function \n% with halfwidth M and concomitant scale T:\n%\n% HUBER_POS(X,M,T) = T.*HUBER_POS(X./T,M) if T > 0\n% +Inf if T <= 0\n%\n% See the help file for HUBER for information about this usage.\n%\n% For matrices and N-D arrays, the penalty function is applied to each\n% element of X independently. M and T must be compatible with X in the same\n% sense as .*: one must be a scalar, or they must have identical size.\n%\n% Disciplined convex programming information:\n% HUBER_POS is jointly convex in X and T. It is nondecreasing in X and\n% nonincreasing in T. Therefore, when used in CVX specifications, X\n% must be convex and T must be concave (or affine). Both must be real.\n\n%\n% Check arguments\n%\n\nerror( nargchk( 1, 3, nargin ) );\nif ~isreal( x ),\n error( 'First argument must be real.' );\nend\nif nargin < 2,\n M = 1;\nelseif ~isreal( M ) || any( M( : ) <= 0 ),\n error( 'Second argument must be real and positive.' );\nend\nif nargin < 3,\n t = 1;\nelseif ~isreal( t ),\n error( 'Third argument must be real.' );\nend\nsz = cvx_size_check( x, M, t );\nif isempty( sz ),\n error( 'Sizes are incompatible.' );\nend\n\n%\n% Compute result\n%\n\ny = max( x, 0 );\nz = min( y, M );\ny = t .* z .* ( 2 * y - z );\nq = t <= 0;\nif nnz( q ),\n if length( t ) == 1,\n y = Inf * ones( sy );\n else\n y( q ) = Inf;\n end\nend\n\n% Copyright 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/huber_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7597809124115025}} {"text": "function volume = estimateTissueVolume(curvature, thickness, surfaceArea)\n%\n% volume = estimateTissueVolume(curvature, thickness, surfaceArea)\n%\n% * curvature is an array of curvature estimates for each mesh triangle\n% * thickness is the estimated tissue thickness\n% * surfaceArea is the actual surface area of each triangle (on the plane)\n%\n% To estimate the volume, if the curvature is zero we can just multiply the\n% single surface area of the triangle by the thickness of the tissue. But,\n% if the local curvature is not zero, then the surface area at the white\n% matter boundary differs from the surface area thickness millimeters away.\n% So, we can 't just multiply a single area by the thickness. Instead, we\n% have to measure the volume by taking the difference between two spheres\n% that define the inner and outer radius of the local curvature at the two\n% boundaries of the gray matter.\n%\n% This routine measures the volume between these two surfaces rather than\n% assuming there is a single surface area and multiplying by the thickness.\n%\n% Estimates the volume of tissue of a given thickness on a surface with the\n% specified mean curvature. The algorithm simply estimates the tissue\n% volume on a sphere of radius 1/curvature and radius + thickness. It\n% takes the local volume estimate as the surfaceArea/sphereSurfaceArea \n% proportion of the total volume between these spheres.\n%\n% HISTORY: RFD (bob@white.stanford.edu) wrote it.\n%\n\nif(~exist('curvature','var') | isempty(curvature))\n help(mfilename);\n return;\nend\n\ncurvature(curvature==0) = 0.0000001;\nr = 1./curvature;\n\nsphereSurfaceArea = 4*pi*r.^2;\ninnerV = (4*pi/3).*(r.^3);\nouterV = (4*pi/3).*(r + thickness).^3;\ntotalTissueVolume = outerV - innerV;\n\nvolume = totalTissueVolume.*(surfaceArea./sphereSurfaceArea);\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/SurfaceMeasurements/estimateTissueVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7597259227494835}} {"text": "function determ = bab_determinant ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% BAB_DETERMINANT computes the determinant of the BAB matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real ALPHA, BETA, parameters that define the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n determ_nm1 = alpha;\n\n if ( n == 1 )\n determ = determ_nm1;\n return\n end\n\n determ_nm2 = determ_nm1;\n determ_nm1 = alpha * alpha - beta * beta;\n\n if ( n == 2 )\n determ = determ_nm1;\n return\n end\n\n for i = n - 2 : -1 : 1\n\n determ = alpha * determ_nm1 - beta * beta * determ_nm2;\n\n determ_nm2 = determ_nm1;\n determ_nm1 = determ;\n \n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/bab_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7596664345851333}} {"text": "function [ l, u ] = l1pp_lu ( n, h )\n\n%*****************************************************************************80\n%\n%% L1PP_LU computes the LU factors of the 1D PP Laplacian.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n% N must be at least 3.\n%\n% Input, real H, the spacing between points.\n%\n% Output, real L(N,N), U(N,n), the LU factors.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'L1PP_LU - Fatal error!\\n' );\n fprintf ( 1, ' N < 3.\\n' );\n error ( 'L1PP_LU - Fatal error!' );\n end\n\n l = zeros ( n, n );\n\n for i = 1 : n\n l(i,i) = 1.0;\n end\n\n for i = 2 : n - 1\n l(i,i-1) = - ( i - 1 ) / i;\n l(n,i-1) = - 1 / i;\n end\n l(n,n-1) = - 1.0;\n\n u = zeros ( n, n );\n\n for i = 1 : n - 2\n u(i,i) = ( i + 1 ) / i;\n u(i,i+1) = - 1.0;\n u(i,n) = - 1 / i;\n end\n\n i = n - 1;\n u(i,i) = ( i + 1 ) / i;\n u(i,i+1) = - ( i + 1 ) / i;\n\n i = n;\n u(i,i) = 0.0;\n\n u(1:n,1:n) = u(1:n,1:n) / h / h;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laplacian/l1pp_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7596664297549756}} {"text": "function value = monomial_value ( dim_num, point_num, x, expon )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_VALUE evaluates a monomial.\n%\n% Discussion:\n%\n% This routine evaluates a monomial of the form\n%\n% product ( 1 <= dim <= dim_num ) x(dim)^expon(dim)\n%\n% where the exponents are nonnegative integers. Note that\n% if the combination 0^0 is encountered, it should be treated\n% as 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer POINT_NUM, the number of points at which the\n% monomial is to be evaluated.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the point coordinates.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Output, real VALUE(POINT_NUM), the value of the monomial.\n%\n value(1,1:point_num) = 1.0;\n \n for dim = 1 : dim_num\n if ( 0 ~= expon(dim) )\n value(1,1:point_num) = value(1,1:point_num) .* ( x(dim,1:point_num).^expon(dim) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_cc/monomial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7596664297549754}} {"text": "function trbvp\n%TRBVP Exercise for Example 3 of the BVP tutorial.\n% This problem is studied in section 5.4 of B.A. Finlayson, The Method of\n% Weighted Residuals and Variational Principles, Academic, New York, 1972.\n% It arises when modelling a tubular reactor with axial dispersion. An\n% isothermal situation with n-th order irreversible reaction leads to \n% \n% y'' = Pe*(y' - R*y^n)\n% \n% Here Pe is the axial Peclet number and R is the reaction rate group.\n% The boundary conditions are\n% \n% y'(0) = Pe*(y(0) - 1), y'(1) = 0.\n% \n% Finlayson compares results he obtains with an orthogonal collocation\n% method to results obtained by others with finite differences when \n% Pe = 1, R = 2, and n = 2. These results are compared here to results\n% obtained with BVP4C. BVPVAL is used to get a smoother graph of y(x). \n\n% Copyright 1999, The MathWorks, Inc.\n\n% Known parameter\nPe = 1;\n\noptions = bvpset('stats','on');\nsolinit = bvpinit(linspace(0,1,5),[0.5 0]);\nsol = bvp4c(@trode,@trbc,solinit,options,Pe);\n\nfprintf('\\n');\nfprintf('Other authors report y(0) = 0.63678, y(1) = 0.45759.\\n');\nfprintf('Values computed are y(0) = %7.5f, y(1) = %7.5f\\n',sol.y(1,1),sol.y(1,end));\n\nclf reset\nxint = linspace(0,1);\nSxint = bvpval(sol,xint);\nplot(xint,Sxint(1,:))\ntitle('Mass transfer in a tubular reactor.')\nxlabel('x')\nylabel('y')\nshg\n\n% --------------------------------------------------------------------------\n\nfunction dydx = trode(x,y,Pe)\n%TRODE ODE function for the exercise of Example 3 of the BVP tutorial.\ndydx = [ y(2)\n Pe*(y(2) + 2*y(1)^2)];\n\n% --------------------------------------------------------------------------\n\nfunction res = trbc(ya,yb,Pe)\n%TRBC Boundary conditions for the exercise of Example 3 of the BVP tutorial.\nres = [ ya(2) - Pe*(ya(1) - 1)\n yb(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/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples/trbvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7596657777544976}} {"text": "% Compute y = log( sum(exp(x),2) ), the softmax in a numerically safe way by\n% subtracting the row maximum to avoid cancelation after taking the exp\n% the sum is done along the rows.\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-16.\n\nfunction [y,x] = logsumexp2(logx)\n N = size(logx,2); max_logx = max(logx,[],2);\n % we have all values in the log domain, and want to calculate a sum\n x = exp(logx-max_logx*ones(1,N));\n y = log(sum(x,2)) + max_logx;", "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/logsumexp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7596428056790353}} {"text": "function jdate = julian (month, day, year)\n\n% Julian date\n\n% Input\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% Output\n\n% jdate = Julian date\n\n% special notes\n\n% (1) calendar year must include all digits\n\n% (2) will report October 5, 1582 to October 14, 1582\n% as invalid calendar dates and stop\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ny = year;\nm = month;\nb = 0;\nc = 0;\n\nif (m <= 2)\n y = y - 1;\n m = m + 12;\nend\n\nif (y < 0)\n c = -.75;\nend\n\n% check for valid calendar date\n\nif (year < 1582)\n % null\nelseif (year > 1582)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (month < 10)\n % null\nelseif (month > 10)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (day <= 4)\n % null\nelseif (day > 14)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelse\n clc; home;\n \n fprintf('\\n\\n this is an invalid calendar date!!\\n');\n \n keycheck;\n \n return;\nend\n\njd = fix(365.25 * y + c) + fix(30.6001 * (m + 1));\n \njdate = jd + day + b + 1720994.5;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39846-a-matlab-script-for-calculating-greenwich-sidereal-time-with-novas/julian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7596427992211144}} {"text": "function [qp]=da2(input)\t\n% [qp] = da2(input)\n% Dahlin's controller for processes of 2nd order.\n% This function computes parameters of the controller (q0, q1, q2, p1, p2).\n% Transfer function of the controller is as follows:\n%\n% q0 + q1*z^-1 + q2*z^-2 q0 + q1*z^-1 + q2*z^-2\n% G(z^-1) = ------------------------ = ------------------------\n% 1 - z^-1 1 + p1*z^-1 + p2*z^-2\n%\n% where p1=-1 and p2=0.\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1\n% Gs(z^-1) = -----------------------\n% 1 + a1*z^-1 + a2*z^-2\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... sample time T0\n% input(5) ... adjustment factor B\n% Output: qp ... controller parameters \n% qp(1) ... q0\n% qp(2) ... q1\n% qp(3) ... q2\n% qp(4) ... -1 (p1 of the controller)\n% qp(5) ... 0 (p2 of the controller)\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nT0 = input(4);\nB = input(5);\n\n% check inputs\nif (T0 <= 0)\n disp('da2.m: Input parameter T0 (sample time) must be greater than 0');\n disp(' parameter value has been changed to 1');\n T0 = 1;\nend;\nif (B <= 0)\n disp('da2.m: Input parameter B (adjustment factor) must be greater than 0');\n disp(' parameter value has been changed to 1e-6');\n B = 1e-6;\nend;\n\nQ = 1-exp(-T0/B);\nKp = -(a1+2*a2)*Q/b1;\nTd = T0*a2*Q/(Kp*b1);\nTi = -T0/((1/(a1+2*a2))+1+Td/T0);\n\nq0 = Kp*(1+T0/Ti+Td/T0);\nq1 = -Kp*(1+2*Td/T0);\nq2 = Kp*Td/T0;\np1 = -1;\np2 = 0;\n\nqp=[q0; q1; q2; p1; p2];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8381-stcsl-standard-version/da2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7595131550582614}} {"text": "function D = EuDist2(fea_a,fea_b,bSqrt)\n%EUDIST2 Efficiently Compute the Euclidean Distance Matrix by Exploring the\n%Matlab matrix operations.\n%\n% D = EuDist(fea_a,fea_b)\n% fea_a: nSample_a * nFeature\n% fea_b: nSample_b * nFeature\n% D: nSample_a * nSample_a\n% or nSample_a * nSample_b\n%\n% Examples:\n%\n% a = rand(500,10);\n% b = rand(1000,10);\n%\n% A = EuDist2(a); % A: 500*500\n% D = EuDist2(a,b); % D: 500*1000\n%\n% version 2.1 --November/2011\n% version 2.0 --May/2009\n% version 1.0 --November/2005\n%\n% Written by Deng Cai (dengcai AT gmail.com)\n\n\nif ~exist('bSqrt','var')\n bSqrt = 1;\nend\n\nif (~exist('fea_b','var')) || isempty(fea_b)\n aa = sum(fea_a.*fea_a,2);\n ab = fea_a*fea_a';\n \n if issparse(aa)\n aa = full(aa);\n end\n \n D = bsxfun(@plus,aa,aa') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\n D = max(D,D');\nelse\n aa = sum(fea_a.*fea_a,2);\n bb = sum(fea_b.*fea_b,2);\n ab = fea_a*fea_b';\n\n if issparse(aa)\n aa = full(aa);\n bb = full(bb);\n end\n\n D = bsxfun(@plus,aa,bb') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\nend\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/EuDist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.759470258648801}} {"text": "%% Wigner-D functions\n%\n%% Theorie\n%\n% The Wigner-D functions are special functions on the rotation group\n% $SO(3)$.\n%\n% In terms of Matthies (ZYZ-convention) Euler angles ${\\bf R} = {\\bf\n% R}(\\alpha,\\beta,\\gamma)$ the $L_2$-normalized Wigner-D function of degree\n% $n$ and orders $k,l \\in \\{-n,\\dots,n\\}$ is defined by\n%\n% $$ D_n^{k,l}({\\bf R}) = \\sqrt{2n+1} \\, \\mathrm e^{-\\mathrm i k\\gamma}\n% \\mathrm d_n^{k,l}(\\cos\\beta) \\,e^{-\\mathrm i l\\alpha} $$\n%\n% where $d_n^{k,l}$, denote the real valued Wigner-d functions, which are\n% defined in terms of Jacobi polynomial $P_s^{a,b}$ by\n% \n% $$ d_n^{k,l}(x) = (-1)^{\\nu} \\binom{2n-s}{s+a}^{\\frac12}\n% \\binom{s+b}{b}^{-\\frac12} \\left(\\frac{1-x}{2}\\right)^{\\frac{a}{2}}\n% \\left(\\frac{1+x}{2}\\right)^{\\frac{b}2} P_s^{a,b}(x)$$\n% \n% using the constants $a =|k-l|$, $b =|k+l|$, $s = n - \\max\\{|k|,|l|\\}$ and\n% $\\nu = \\min\\{0,k\\}+\\min\\{0,l\\}$ if $l \\geq k$; $\\nu =\n% \\min\\{0,k\\}+\\min\\{0,l\\} + k+l$ otherwise.\n%\n% This definition is slightly different to other well known definitions,\n% because the Wigner-D functions are defined compatible to the\n% which form an orthonormal\n% basis on the 2-sphere.\n%\n%% \n% In MTEX the Wigner-D and Wigner-d functions are available through the\n% command \n\n% the Wigner-d function of degree 1\nbeta = 0.5;\nd = Wigner_D(1,beta)\n\n% the Wigner-D function of degree 1\nR = rotation.rand;\nD = sqrt(3) * Wigner_D(1,R)\n\n%%\n% Here the orders $k$, $l$ work as row and column indices.\n%\n%% Series Expansion\n%\n% The Wigner-D functions form an orthonormal basis in $L_2(SO(3))$. Hence,\n% we can describe functions on the rotation group $SO(3)$ by there harmonic\n% representation using the class .\n%\n% Hence we define the Wigner-D function $D_1^{1,-1}$ by\n\nD = SO3FunHarmonic([0;0;0;1])\nD.eval(R)\n\n%%\n% Various normalizations for the Wigner-D functions are common in the\n% literature.\n%\n% Here we define the $L_2$-norm by\n%\n% $$ \\| f \\|_2 = \\left(\\frac1{8\\pi^2}\\,\\int_{SO(3)} \\lvert f(\\bf R) \\rvert^2 \\,\\mathrm d \\bf R \\right)^{1/2} $$\n%\n% such that the norm of the constant function $f=1$ is $1$. Take a look on the section \n% .\n%\n% Using that definition the Wigner-D functions in MTEX are normalized, i.e. $\\|\n% D_n^{k,l} \\|_2 = 1$ for all $n,k,l$.\n\n\nnorm(D)\n\n%% Some important formulas for Wigner-D functions\n%\n% The Wigner-D functions are the matrix elements of the representations\n% $D_n \\colon SO(3) \\to \\mathbb C^{(2n+1)\\times(2n+1)}$ on $SO(3)$. \n% Since representations are group homomorphisms, we have\n% $D_n(\\bf{R} \\, \\bf{Q}) = \\frac1{\\sqrt{2n+1}} \\, D_n(\\bf{Q}) \\, D_n(\\bf{R}).$\n% Hence we get\n% \n% $$ D_n^{k,l}(\\bf{R}\\,\\bf{Q}) = \\frac1{2n+1} \\sum_{j=-n}^n D_n^{k,j}(\\bf{Q})\\,D_n^{j,l}(\\bf{R}). $$\n%\n%%\n% Some symmetry properties of Wigner-D functions yields\n%\n% $$ D_n^{k,l}(\\bf{R}) = \\overline{D_n^{l,k}(\\bf{R}^{-1})}. $$\n%\n\n%% Symmetry properties of Wigner-d functions\n% \n% The Wigner-d functions by construction fulfill a lot of symmetry \n% properties. Some importants are\n% \n% $$ d_n^{k,l}(x) = d_n^{-k,-l}(x) = (-1)^{k+l}\\, d_n^{l,k}(x) = (-1)^{k+l}\\, d_n^{-l,-k}(x)$$\n% \n% $$ d_n^{k,l}(x) = (-1)^{n+k+l}\\,d_n^{-k,l}(-x) = (-1)^{n+k+l}\\,d_n^{k,-l}(-x) $$\n%\n% $$d_n^{k,l}(\\cos\\beta) = (-1)^{k+l}\\,d_n^{k,l}(\\cos(-\\beta))$$\n%\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/SO3Functions/WignerFunctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7594702530913698}} {"text": "function [xt_prf, sw_prf] = BLanalytical(muw, muo)\n%BLANALYTICAL Analytical solution of Buckley-Leverett equation\n% Written by Ali A. Eftekhari\n% See the license file\n%muw = 10e-3;\n%muo = 10e-3;\nu = 1e-3;\nphi = 0.2;\nsw_in = 1;\nsw_end = 0;\nkrw = @(sw)(sw.^4);\ndkrwdsw = @(sw)(4*sw.^3);\nkro = @(sw)((1-sw.^2).*(1-sw).^2);\ndkrodsw = @(sw)(-2*sw.*(1-sw).^2-2*(1-sw).*(1-sw.^2));\nfw = @(sw)((krw(sw)/muw)./(krw(sw)/muw+kro(sw)/muo));\ndfwdsw = @(sw)((dkrwdsw(sw)/muw.*(krw(sw)/muw+kro(sw)/muo)- ...\n (dkrwdsw(sw)/muw+dkrodsw(sw)/muo).*krw(sw)/muw)./ ...\n (krw(sw)/muw+kro(sw)/muo).^2);\ns = linspace(0,1,100);\nfigure(1)\nsubplot(2,2,1);\nplot(s, krw(s), s, kro(s));\nF = @(sw)(dfwdsw(sw)-(fw(sw)-fw(sw_end))/(sw-sw_end));\nsw_shock = fzero(F, [eps,1]);\nsubplot(2,2,2);\nplot(s, fw(s), [sw_end sw_shock], [fw(sw_end) fw(sw_shock)]);\n% plot(s, fw(s), [sw_end sw_shock], [fw(sw_end) fw(sw_shock)]);\ns1 = linspace(sw_in, sw_shock, 50);\nxt_s1 = u/phi*dfwdsw(s1);\nxt_s = u/phi*dfwdsw(s);\nxt_shock = u/phi*dfwdsw(sw_shock);\nsubplot(2,2,3);\nplot(xt_s, s, '--', ...\n [xt_s1 xt_shock xt_shock max(xt_s)], [s1 sw_shock sw_end sw_end])\nsw_prf = [s1 sw_shock sw_end sw_end];\nxt_prf = [xt_s1 xt_shock xt_shock max(xt_s)];\nend\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Physics/BLanalytical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7594702427129058}} {"text": "function spline_test235 ( )\n\n%*****************************************************************************80\n%\n%% TEST235 tests SPLINE_PCHIP_SET and SPLINE_PCHIP_VAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2005\n%\n% Author\n%\n% John Burkardt\n%\n n = 21;\n ne = 101;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST235\\n' );\n fprintf ( 1, ' SPLINE_PCHIP_SET sets up a piecewise cubic \\n' );\n fprintf ( 1, ' Hermite interpolant.\\n' );\n fprintf ( 1, ' SPLINE_PCHIP_VAL evaluates the interpolant.\\n' );\n fprintf ( 1, '\\n' );\n%\n% Compute Runge's function at N points in [-1,1].\n%\n for i = 1 : n\n x(i) = -1.0 + ( i - 1 ) / 10.0;\n f(i) = frunge ( x(i) );\n end\n%\n% SPLINE_PCHIP_SET takes the data in X and F, and constructs a table in D\n% that defines the interpolant.\n%\n d = spline_pchip_set ( n, x, f );\n%\n% Evaluate the interpolant and derivative at NE points from -1 to 0.\n%\n for i = 1 : ne\n xe(i) = -1.0 + ( i - 1 ) / ( ne - 1 );\n end\n\n fe = spline_pchip_val ( n, x, f, d, ne, xe );\n%\n% Print the table of X, F(exact) and F(interpolated)\n%\n for i = 1 : ne\n diff = fe(i) - frunge ( xe(i) );\n fprintf ( 1, ' %8f %10f %10f %14e\\n', ...\n xe(i), frunge ( xe(i) ), fe(i), diff );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/spline_test235.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.75942171781128}} {"text": "function result = p00_exp_transform ( problem, order )\n\n%*****************************************************************************80\n%\n%% P00_EXP_TRANSFORM applies an exponential transform and Gauss-Legendre rule.\n%\n% Discussion:\n%\n% To approximate:\n%\n% Integral ( alpha <= x < Infinity ) f(x) dx\n%\n% Transform:\n%\n% u = exp ( -x )\n% du = - exp ( -x ) dx\n%\n% x = - log ( u )\n% dx = - du / u\n%\n% x = alpha => u = exp ( -alpha )\n% x = Infinity => u = 0\n%\n% Transformed integral:\n%\n% Integral ( 0 <= u <= exp ( -alpha ) ) f ( -log(u) ) du / u\n%\n% We apply a Gauss-Legendre rule here, but we could easily use any rule\n% that avoids evaluation at U = 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the index of the problem.\n%\n% Input, integer ORDER, the order of the Gauss-Legendre rule\n% to apply.\n%\n% Output, real RESULT, the approximate integral.\n%\n alpha = p00_alpha ( problem );\n%\n% Get the abscissas and weights for Gauss-Legendre quadrature.\n%\n [ u, weight ] = legendre_compute ( order );\n%\n% Modify the weights from [-1,1] to [0,exp(-alpha)].\n%\n weight(1:order) = exp ( -alpha ) * weight(1:order) / 2.0;\n%\n% Linear transform of abscissas from [-1,1] to [0,exp(-alpha)].\n%\n u(1:order) = ( ( 1.0 + u(1:order) ) * exp ( - alpha ) ...\n + ( 1.0 - u(1:order) ) * 0.0 ) ...\n / ( 2.0 );\n%\n% Define U_LOG = - log ( U )\n%\n u_log(1:order) = - log ( u(1:order) );\n%\n% Evaluate F ( -LOG(U) ).\n%\n f_vec = p00_fun ( problem, order, u_log );\n%\n% The integrand is F ( -LOG(U) ) / U\n%\n f_vec(1:order) = f_vec(1:order) ./ u(1:order);\n%\n% Sum.\n%\n result = weight(1:order) * f_vec(1:order)';\n\n return\nend\n", "meta": {"author": "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/p00_exp_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7593959000662779}} {"text": "function mean = folded_normal_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% FOLDED_NORMAL_MEAN returns the mean of the Folded Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 <= A,\n% 0.0 < B.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n a2 = a / b;\n\n cdf = normal_01_cdf ( a2 );\n\n mean = b * sqrt ( 2.0 / pi ) * exp ( -0.5 * a2 * a2 ) - a * ( 1.0 - 2.0 * cdf );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/folded_normal_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7593958961589733}} {"text": "\n% by Tolga Birdal\n% A sample application and a function for solving the maximum inscribed\n% circle problem. \n% Unlike my other submission \"Maximum Inscribed Circle using Distance \n% Transform\", this algorithm is subpixel accurate. It operates only on the\n% polygon and not the image points. Therefore, if the polygon is given in\n% sub-pixels, the result will be accurate. \n% I use an O(n log(n)) algorithm as follows:\n% Construct the Voronoi Diagram of the polygon.\n% For Voronoi nodes which are inside the polygon:\n% Find the node with the maximum distance to edges in P. This node is\n% the centre of the maximum inscribed circle.\n% \n% For more details on the problem itself please checkout my previous \n% submission as mentioned above.\n% \n% To speed things up:\n% Replace \"inpolygon\" function by Bruno Lunog's faster implementation:\n% \"2D polygon interior detection\" :\n% http://www.mathworks.com/matlabcentral/fileexchange/27840-2d-polygon-inte\n% rior-detection\n% Copyright (c) 2011, Tolga Birdal \n\nfunction []=test_max_circle2()\nclose all;\nfigure,\n\n% Read the boundary segmented and the original image. Original image is\n% only needed for visualization\nIorg=imread('hand.jpg');\nI=imread('hand_contour.png');\nimshow(Iorg);\n\n% obtain the boundary\n[y,x]=find(I>0);\ncontour = bwtraceboundary(logical(I), [y(1),x(1)], 'E', 8);\n\n% get the circle\n[cx,cy,r]=find_inner_circle(contour(:,2),contour(:,1));\n\n% plot\ntheta = [linspace(0,2*pi) 0];\nhold on, plot(x, y,'g.', 'MarkerSize',1);\nhold on, plot(cos(theta)*r+cx,sin(theta)*r+cy,'r', 'LineWidth', 1);\n\nend\n\n% given a polygon [x,y] find the inner circle [cx,cy,r]\nfunction [cx,cy,r]=find_inner_circle(x,y)\n\n% make a voronoi diagram\n[vx,vy]=voronoi(x,y);\n\n% find voronoi nodes inside the polygon [x,y]\nVx=vx(:);\nVy=vy(:);\n% Here, you could also use a faster version of inpolygon\nIN=inpolygon(Vx,Vy, x,y);\nind=find(IN==1);\nVx=Vx(ind);\nVy=Vy(ind);\n\n% maximize the distance of each voronoi node to the closest node on the\n% polygon.\nminDist=0;\nminDistInd=-1;\nfor i=1:length(Vx)\n dx=(Vx(i)-x);\n dy=(Vy(i)-y);\n r=min(dx.*dx+dy.*dy);\n if (r>minDist)\n minDist=r;\n minDistInd=i;\n end\nend\n\n% take the center and radius\ncx=Vx(minDistInd);\ncy=Vy(minDistInd);\nr=sqrt(minDist);\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/32543-maximum-inscribed-circle-using-voronoi-diagram/test_max_circle2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7593958925089916}} {"text": "function value = r8_gami ( a, x )\n\n%*****************************************************************************80\n%\n%% R8_GAMI evaluates the incomplete gamma function for an R8 argument.\n%\n% Discussion:\n%\n% GAMI = Integral ( 0 <= T <= X ) exp ( - t ) * t^( a - 1 ) dt\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real A, the parameter.\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the value of the incomplete\n% gamma function.\n%\n if ( a <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAMI - Fatal error!\\n' );\n fprintf ( 1, ' A <= 0.\\n' );\n error ( 'R8_GAMI - Fatal error!' )\n end\n\n if ( x < 0.0 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAMI - Fatal error!\\n' );\n fprintf ( 1, ' X < 0.\\n' );\n error ( 'R8_GAMI - Fatal error!' )\n\n elseif ( x == 0.0 )\n\n value = 0.0;\n\n else\n\n factor = exp ( r8_lngam ( a ) + a * log ( x ) );\n\n value = factor * r8_gamit ( a, x );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_gami.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7593958905124524}} {"text": "function pdf = normal_truncated_b_pdf ( x, mu, s, b )\n\n%*****************************************************************************80\n%\n%% NORMAL_TRUNCATED_B_PDF evaluates the upper truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real MU, S, the mean and standard deviation of the\n% parent Normal distribution.\n%\n% Input, real B, the upper truncation limit.\n%\n% Output, real PDF, the value of the PDF.\n%\n beta = ( b - mu ) / s;\n xi = ( x - mu ) / s;\n\n beta_cdf = normal_01_cdf ( beta );\n xi_pdf = normal_01_pdf ( xi );\n\n pdf = xi_pdf / beta_cdf / s;\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/normal_truncated_b_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7593958768797732}} {"text": "function [V2Dr,V2Ds] = GradVandermonde2D(N,r,s)\n\n% function [V2Dr,V2Ds] = GradVandermonde2D(N,r,s)\n% Purpose : Initialize the gradient of the modal basis (i,j) at (r,s) at order N\t\n\nV2Dr = zeros(length(r),(N+1)*(N+2)/2); V2Ds = zeros(length(r),(N+1)*(N+2)/2);\n\n% find tensor-product coordinates\n[a,b] = rstoab(r,s);\n\n% Initialize matrices\nsk = 1;\nfor i=0:N\n for j=0:N-i\n [V2Dr(:,sk),V2Ds(:,sk)] = GradSimplex2DP(a,b,i,j);\n sk = sk+1;\n end\nend\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/GradVandermonde2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7593585061167453}} {"text": "function P = cubic_eval(C,t);\n % CUBIC_EVAL Evaluate a cubic Bezier curve.\n %\n % P = cubic_eval(C,t);\n %\n % Inputs:\n % C 4 by dim list of control points\n % t #t list of evaluation parameters\n % Outputs:\n % P #t by dim list of evaluated points\n %\n % See also: readSVG_cubics, cubic_split\n %\n t = reshape(t,numel(t),1);\n %B = bernstein_eval([0 1 2 3],3,t);\n %P = B*C;\n P = ...\n 1*(1-t).^3.*t.^0.*C(1,:) + ...\n 3*(1-t).^2.*t.^1.*C(2,:) + ...\n 3*(1-t).^1.*t.^2.*C(3,:) + ...\n 1*(1-t).^0.*t.^3.*C(4,:);\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_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7593585050374326}} {"text": "function choices = simplex_grid(dim, discretization, include_edges)\n%SIMPLEX_GRID returns a discrete set of points from a simplex\n%\n% points = simplex_grid(dim, discretization[, include_edges=false]);\n%\n% Inputs:\n% dim 1x1 dimensionality D\n% discretization 1x1 Number of discrete points along each axis.\n% include_edges 1x1 If true, allow components to be exactly zero or one.\n% As this often causes problems, the default is false.\n%\n% Outputs:\n% choices LOTS x D, It should be that all(1 == sum(choices, 2)).\n\n% Iain Murray, January 2009\n\n% If dim==1, the only point that is allowed is [1], and that disagrees with the\n% include_edges default. For now, just don't allow this silly case.\nassert(dim > 1);\n\nvec = @(x) x(:);\n\nif ~exist('include_edges', 'var')\n include_edges = false;\nend\n\nif include_edges\n ww = 1/(discretization-1);\n tics = (0:ww:1)';\nelse\n ww = 1/(discretization+1);\n tics = (ww:ww:(1-ww))';\nend\n\nchoices = tics;\ncur_sum = choices;\n\n% Build up choices one component at a time\nfor d = 2:(dim-1)\n % For each existing choice, consider setting next component to every choice\n % in tics\n prev_length = size(choices, 1);\n proposed_next = vec(repmat(tics', prev_length, 1));\n proposed_sum = proposed_next + repmat(cur_sum, discretization, 1);\n proposed_choices = [proposed_next, repmat(choices, discretization, 1)];\n % Only keep proposals that can lead to valid points on simplex\n idx = proposed_sum <= (1 - tics(1)*(dim-d));\n choices = proposed_choices(idx, :);\n cur_sum = proposed_sum(idx);\nend\n\n% Final component must be chosen to make choices normalized\nchoices = [choices, 1-cur_sum];\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/simplex_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8670357598021708, "lm_q1q2_score": 0.7593386453502292}} {"text": "function value = r8_factorial ( n )\n\n%*****************************************************************************80\n%\n%% R8_FACTORIAL returns N!.\n%\n% Discussion:\n%\n% factorial ( N ) = Product ( 1 <= I <= N ) I\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the argument of the function.\n% 0 <= N.\n%\n% Output, real VALUE, the factorial of N.\n%\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_FACTORIAL - Fatal error!\\n' );\n fprintf ( 1, ' N < 0.\\n' );\n error ( 'R8_FACTORIAL - Fatal error!' );\n end\n\n value = 1.0;\n\n for i = 2 : n\n value = value * i;\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/r8_factorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7593386453502291}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% z-Transform properties\n\n\n%\tRight shift of x[n]\n\nn=-3:3;\nx=0.8.^n;\n\nxminus3=x(1)\nxminus2=x(2)\nxminus1=x(3)\n\nsyms n z\nxn1=0.8^(n-1);\nLeft=ztrans(xn1,z) ; \nsimplify(Left)\n\nx=0.8^n;\nX=ztrans(x,z);\nRight=z^-1*X +xminus1;\nsimplify(Right)\n\n\n\nxn2=0.8^(n-2);\nLeft=ztrans(xn2,z) ; \nsimplify(Left)\n\nRight=z^-2*X+xminus2+z^-1 *xminus1;\nsimplify(Right)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/10/c105c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7593386404406643}} {"text": "function [ x, w ] = fejer2_compute ( n )\n\n%*****************************************************************************80\n%\n%% FEJER2_COMPUTE computes a Fejer type 2 quadrature rule.\n%\n% Discussion:\n%\n% This method uses a direct approach. The paper by Waldvogel\n% exhibits a more efficient approach using Fourier transforms.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Walter Gautschi,\n% Numerical Quadrature in the Presence of a Singularity,\n% SIAM Journal on Numerical Analysis,\n% Volume 4, Number 3, 1967, pages 357-362.\n%\n% Joerg Waldvogel,\n% Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules,\n% BIT Numerical Mathematics,\n% Volume 43, Number 1, 2003, pages 1-18.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n x = zeros ( n, 1 );\n w = zeros ( n, 1 );\n\n if ( n == 1 )\n x(1) = 0.0;\n w(1) = 2.0;\n return\n elseif ( n == 2 )\n x(1) = -0.5;\n x(2) = 0.5;\n w(1:2) = 1.0;\n return\n end\n\n theta(1:n) = ( n : -1 : 1 ) * pi / ( n + 1 );\n x(1:n) = cos ( theta(1:n) );\n\n for i = 1 : n\n\n w(i) = 1;\n\n for j = 1 : floor ( ( n - 1 ) / 2 )\n w(i) = w(i) - 2 * cos ( 2 * j * theta(i) ) / ( 4 * j * j - 1 );\n end\n\n if ( 2 < n )\n p = 2 * floor ( ( n + 1 ) / 2 ) - 1;\n w(i) = w(i) - cos ( ( p + 1 ) * theta(i) ) / p;\n end\n\n end\n\n w(1:n) = 2 * w(1:n) / ( 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/quadrule/fejer2_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7593386375115091}} {"text": "% This script demonstrate that even if several sparse linear arrays\n% share the same virtual ULA, they exhibit different performances under\n% different SNR settings and different numbers of sources.\n% This script will produce results similar to Fig. 1 in the following\n% paper:\n% * M. Wang, Z. Zhang, and A. Nehorai, \"Performance analysis of\n% coarray-based MUSIC and the Cramér-Rao bound,\" in 2017 IEEE\n% International Conference on Acoustics, Speech and Signal Processing\n% (ICASSP), 2017, pp. 3061-3065.\n\n\nclear(); close all;\n\nwavelength = 1; % normalized wavelength\nd_0 = wavelength / 2;\ndesigns = {...\n design_array_1d('nested', [5 6], d_0, 'Nested (5, 6)') ...\n design_array_1d('nested', [2 12], d_0, 'Nested (2, 12)') ...\n design_array_1d('nested', [3 9], d_0, 'Nested (3, 9)') ...\n design_array_1d('nested', [1 18], d_0, 'Nested (1, 18)') ...\n};\nn_designs = length(designs);\n\npower_source = 1;\nn_snaphots = 1000;\n\nn_grid = 20;\nSNRs = linspace(-10, 20, n_grid);\n\ndoas1 = linspace(-pi/3, pi/3, 8);\n\nMSEs_SNR_ana1 = zeros(n_designs, n_grid);\nfor dd = 1:n_designs\n design = designs{dd};\n A = steering_matrix(design, wavelength, doas1);\n for ii = 1:n_grid\n power_noise = power_source*10^(-SNRs(ii)/10);\n MSEs_SNR_ana1(dd, ii) = mean(ecov_coarray_music_1d(design, wavelength, ...\n doas1, power_source, power_noise, n_snaphots, 'DiagonalsOnly'));\n end\nend\n\ndoas2 = linspace(-pi/3, pi/3, 20);\n\nMSEs_SNR_ana2 = zeros(n_designs, n_grid);\nfor dd = 1:n_designs\n design = designs{dd};\n A = steering_matrix(design, wavelength, doas2);\n for ii = 1:n_grid\n power_noise = power_source*10^(-SNRs(ii)/10);\n MSEs_SNR_ana2(dd, ii) = mean(ecov_coarray_music_1d(design, wavelength, ...\n doas2, power_source, power_noise, n_snaphots, 'DiagonalsOnly'));\n end\nend\n\nfigure;\nsubplot(1,2,1);\nsemilogy(SNRs, rad2deg(sqrt(MSEs_SNR_ana1)));\nxlabel('SNR (dB)'); ylabel('RMSE (deg)'); grid on;\nlegend(arrayfun(@(x) x{1}.name, designs, 'UniformOutput', false));\ntitle(sprintf('K = %d', length(doas1)));\nsubplot(1,2,2);\nsemilogy(SNRs, rad2deg(sqrt(MSEs_SNR_ana2)));\nxlabel('SNR (dB)'); ylabel('RMSE (deg)'); grid on;\nlegend(arrayfun(@(x) x{1}.name, designs, 'UniformOutput', false));\ntitle(sprintf('K = %d', length(doas2)));\n", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/examples/experiments/coarrays_music_crb/sim_mse_same_coarray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7593184524332798}} {"text": "%\n% rho=findrhoc(n,p)\n%\n% Finds an intensity rho such that C(n,rho)=p. \n%\n% Note: Must have 01.0))\n warning('Invalid p value!');\n rho=NaN;\n return;\n end;\n%\n% We know that at rho=0, p=0, and at rho=+Inf, p=1. We start by finding\n% an interval [0,a] containing the root.\n%\na=1.0;\ntestp=erlangc(n,a);\nwhile (testp < p),\n a=a*2.0;\n testp=erlangc(n,a);\nend;\n%\n% Now, the root is somewhere between 0 and a. Use bisection to find it.\n% \n%\nleft=0.0;\nright=a;\nmid=(left+right)/2;\nmidp=erlangc(n,mid);\nwhile ((right-left) > 0.0001*max([1 left])),\n if (midp < p),\n left=mid;\n mid=(left+right)/2;\n midp=erlangc(n,mid); \n else\n right=mid;\n mid=(left+right)/2;\n midp=erlangc(n,mid); \n end;\nend;\n%\n% Return the left end point of the current interval, which has prob < p.\n%\nrho=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/824-erlang-b-and-c-probabilities/erlang/findrhoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7593184481639788}} {"text": "function [ t1, t2, pi ] = lines_par_int_2d ( f1, g1, x1, y1, f2, g2, ...\n x2, y2 )\n\n%*****************************************************************************80\n%\n%% LINES_PAR_INT_2D determines where two parametric lines intersect in 2D.\n%\n% Discussion:\n%\n% The parametric form of a line in 2D is:\n%\n% X = X0 + F * T\n% Y = Y0 + G * T\n%\n% We normalize by choosing F*F+G*G=1 and 0 <= F.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Adrian Bowyer and John Woodwark,\n% A Programmer's Geometry,\n% Butterworths, 1983.\n%\n% Parameters:\n%\n% Input, real F1, G1, X1, Y1, define the first parametric line.\n%\n% Input, real F2, G2, X2, Y2, define the second parametric line.\n%\n% Output, real T1, T2, the T parameters on the first and second\n% lines of the intersection point.\n%\n% Output, real PI(2,1), the intersection point.\n%\n det = f2 * g1 - f1 * g2;\n\n if ( det == 0.0 )\n t1 = 0.0;\n t2 = 0.0;\n pi = [];\n else\n t1 = ( f2 * ( y2 - y1 ) - g2 * ( x2 - x1 ) ) / det;\n t2 = ( f1 * ( y2 - y1 ) - g1 * ( x2 - x1 ) ) / det;\n pi(1,1) = x1 + f1 * t1;\n pi(2,1) = y1 + g1 * t1;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/lines_par_int_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7593150665749202}} {"text": "function r8_fall_test ( )\n\n%*****************************************************************************80\n%\n%% R8_FALL_TEST tests R8_FALL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 25 December 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_FALL_TEST\\n' );\n fprintf ( 1, ' R8_FALL evaluates the falling factorial Fall(X,N).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X N Exact' );\n fprintf ( 1, ' Computed\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, n, f1 ] = r8_fall_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n f2 = r8_fall ( x, n );\n\n fprintf ( 1, ' %8.4f %4d %24.16g %24.16g\\n', x, n, f1, f2 );\n\n end\n \n return\nend\n", "meta": {"author": "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_fall_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7593150573556693}} {"text": "function X = polar2xyz(P)\n% POLAR2XYZ Transformation of polar coordinates to cartesian coordinates.\n% ------------------------------------------------------------------------------\n% DESCRIPTION/NOTES\n% Transformation of polar coordinates [distance, horizontal angle, vertical\n% angle] to cartesian coordinates [x, y, z].\n% ------------------------------------------------------------------------------\n% INPUT\n% P\n% Matrix of polar coordinates distace, horizontal angle and vertical angle.\n% Each point in a row.\n% Horizontal angle is defined mathematically positive starting from x-axis.\n% Vertical angle is defined as angle between point and zenith.\n% ------------------------------------------------------------------------------\n% OUTPUT\n% X\n% Matrix of cartesian coordinates x, y and z. Each point in a row.\n% ------------------------------------------------------------------------------\n% EXAMPLES\n% Transformation of randomly generated points into polar coordinates and back.\n% X1 = [rand(10,1)*10 rand(10,1)*5 rand(10,1)];\n% P = xyz2polar(X1);\n% X2 = polar2xyz(P);\n% Diff = X1-X2;\n% ------------------------------------------------------------------------------\n% pg@geo.tuwien.ac.at\n% ------------------------------------------------------------------------------\n\n% Input parsing ----------------------------------------------------------------\n\np = inputParser;\np.addRequired('P', @(x) isreal(x) && size(x,2) == 3);\np.parse(P);\np = p.Results;\n% Clear required inputs to avoid confusion\nclear P\n\n% Transformation ---------------------------------------------------------------\n\nd = p.P(:,1);\nha = p.P(:,2);\nva = p.P(:,3);\n\nx = d .* cosg(ha) .* sing(va);\ny = d .* sing(ha) .* sing(va);\nz = d .* cosg(va);\n\n% Output -----------------------------------------------------------------------\n\nX = [x y z];\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/functions/polar2xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.759313759527206}} {"text": "function x = hermitian_semidefinite( n )\n\n%HERMITIAN_SEMIDEFINITE Complex Hermitian positive semidefinite matrices.\n% HERMITIAN_SEMIDEFINITE(N), where N is an integer, creates a complex \n% Hermitian matrix variable of size [N,N] and constrains it to be \n% positive semidefinite. Therefore, given the declaration\n% variable x(n,n) Hermitian\n% the constraint\n% x == hermitian_semidefinite(n)\n% is equivalent to\n% lambda_min(x) >= 0;\n% In fact, lambda_min is implemented in CVX using HERMITIAN_SEMIDEFINITE\n% for complex matrices.\n%\n% HERMITIAN_SEMIDEFINITE(SX), where SX is a valid size vector, creates\n% an array variable of size SX and constrains each subarray along the \n% leading two dimensions to be positive semidefinite. SX(1) and SX(2)\n% must be equal. Therefore, given the declaration\n% variable x(sx) Hermitian\n% the constraint\n% x == hermitian_semidefinite(sx)\n% is equivalent to\n% for k = 1:prod(sx(3:end)),\n% lambda_min(x(:,:,k)) >= 0;\n% end\n%\n% Disciplined convex programming information:\n% SEMIDEFINITE is a cvx set specification. See the user guide for\n% details on how to use sets.\n\nx = semidefinite( n, true );\n\n% Copyright 2005-2014 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/sets/hermitian_semidefinite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7593084634743265}} {"text": "% PLOT_ELLIPSE\n% h=plot_ellipse(x,y,theta,a,b)\n%\n% This routine plots an ellipse with centre (x,y), axis lengths a,b\n% with major axis at an angle of theta radians from the horizontal.\n\n%\n% Author: P. Fieguth\n% Jan. 98\n%\n%http://ocho.uwaterloo.ca/~pfieguth/Teaching/372/plot_ellipse.m\n\nfunction h=plot_ellipse(x,y,theta,a,b)\n\nnp = 100;\nang = [0:np]*2*pi/np;\nR = [cos(theta) -sin(theta); sin(theta) cos(theta)];\npts = [x;y]*ones(size(ang)) + R*[cos(ang)*a; sin(ang)*b];\nh=plot( pts(1,:), pts(2,:) );\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/murphy/KPMtools/plot_ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7593084511666246}} {"text": "function [x,F,JAC,EXITFLAG] = NewtonRaphson(FUN,x,lambda, maxIter ,Display)\n%NewtonRaphson solves a system of nonlinear equations via newton method \n%\n% NewtonRaphson solves equations of the form:\n% \n% F(X) = 0 where F and X may be scalars or vectors\n%\n% NewtonRaphson implements the damped newton method with adaptive step\n% size. Theory and discussion can be found here:\n% http://forum.vis.ethz.ch/showthread.php?13434-Damped-Newton-method-Schrittweitensteuerung\n%\n% The Jacobian is calculated numerically by a simple forward differential \n% method. Find more here:\n% http://en.wikipedia.org/wiki/Numerical_differentiation\n%\n% The error estimation ist made by root-mean-square\n% http://en.wikipedia.org/wiki/Root_mean_square\n%\n%\n% x = NewtonRaphson(FUN,X0) starts at the initial guess X0 and tries to \n% solve the equations in FUN. FUN is a function handle and has to accept\n% input x and return a vector of equation values F evaluated at x.\n% Default values for solver and display setting.\n% \n% x = NewtonRaphson(FUN,X0,lambda) starts at the initial guess X0 and tries to \n% solve the equations in FUN with user supplied initial relaxation factor. Might\n% be useful to increase solution speed.\n% default value: lambda = 0.1\n%\n% x = NewtonRaphson(FUN,X0,lambda,maxIter) ...\n% User supplied maximum number of iterations\n% default value: maxIter = 100\n%\n% x = NewtonRaphson(FUN,X0,lambda,maxIter,Display) ...\n% Display options: \n% 'on' - full output during solution process\n% 'off' - hide output\n% default value: maxIter = 'off'\n%\n% OUTPUT Arguments:\n% x - Solution\n% F - Value at x\n% Jac - Jacobian at x\n% Exitflat: exit conditions of damped newton\n% 1: all ok. Solution found\n% -1: no solution found\n% -2: FUN is not a function handle \n%\n% To enter Demo Mode start without any arguments\n% NewtonRaphson();\n% \n% Examples:\n%\n% Find zero of function atan(x)\n%\n% create function handle (here as an anonymous function)\n% F = @(x)atan(x);\n% x0 = 5; % start value /initial guess\n%\n% x = NewtonRaphson(F,x0,1); \n% \n% Find solution of following system of equations (same as in fsolve help)\n% F = @(x)[2*x(1) - x(2) - exp(-x(1));\n% -x(1) + 2*x(2) - exp(-x(2))];\n% x0 = [1;2];\n%\n% x = NewtonRaphson(F,x0,0.1,100,'on');\n%\n% Open Issues:\n% - At least some input error checks have to be done... I'm so lazy...\n% - correct some wording/grammar/spelling\n% \n% Author: Andi S. 2013\n\n% Check Input arguments / find more at help nargin\nif nargin < 5, Display = 'off'; end\nif nargin < 4, maxIter = 100; end\nif nargin < 3, lambda = .1; end\n\n\nif(nargin==0)\n disp('Demo-Mode on f(x) = atan(x)');\n FUN = @(x)atan(x);\n x = 5; % initial guess\n Display = 'on';\n % maximum number of iterations \n maxIter = 100; \n % Initial relaxation factor\n lambda = 1.; \n \nend\n\n% check for Input Arguments error\nif(~isa(FUN,'function_handle'))\n disp('FUN must be a function handle.');\n x = 0; F = 0; JAC = 0; EXITFLAG = -2;\n return\nend\n\n% -------------------------------------------------------------------------\n% Solver settings\n% -------------------------------------------------------------------------\n% Estimate problem size\nN = length(x);\n\n% Minimal relaxation factor\nLmin = 1e-10;\n\n% Convergence Criteria\nConvCrit = 1e-6;\n\n% Allocate Memory for Jacobian\nJAC = zeros(N);\n\n% -------------------------------------------------------------------------\n% Solution\n% -------------------------------------------------------------------------\n\n% First Newton Step\n% get first Values for x\nF = FUN(x);\n\n% numerical Jacobian\nfor i = 1:N\n xtemp = x;\n h = sqrt(eps)*x(i);\n xtemp(i) = xtemp(i)+h;\n JAC(i,:) = (FUN(xtemp)-F)./h;\nend\n\n% calculate step size\ns = (JAC\\-F);\n\n% first newton step \nx = x + lambda*s; \nF = FUN(x);\nerr = sqrt(sum(F.^2)/N);\n\nn = 0; % Iteration counter \n\nif(strcmp(Display,'on'));\n fprintf('n: %i rlx fac: %e error: %e x: ',n,lambda,err);\n fprintf(repmat('%e ',1,N),x);\n fprintf('\\n');\nend\n\nwhile( err > ConvCrit && n < maxIter) \n \n n = n+1;\n \n % calculate Jacobian \n for i = 1:N\n xtemp = x;\n h = sqrt(eps)*x(i);\n xtemp(i) = xtemp(i)+h;\n JAC(i,:) = (FUN(xtemp)-F)./h;\n end\n\n\n sTemp = (JAC\\-F);\n\n % Find optimal step size\n \n if(~(max(abs(lambda * sTemp)) < max(abs(s)) )) \n \n % step size is not gettin' shorter. So we decrease relaxation factor\n while( ( max(abs(s)) < max(abs(lambda * sTemp))))\n \n % till step size decreases\n lambda = lambda / 2;\n if( lambda < Lmin )\n fprintf('Damping to strong. No convergence.\\n');\n return; \n end\n end % step size is ok now\n end\n \n % next newton step\n s = sTemp; \n x = x + lambda*s;\n F = FUN(x);\n \n lambda = min( 1., lambda * 2);% increase relaxation factor\n\n err = sqrt(sum(F.^2)/N);\n \n if(strcmp(Display,'on'));\n fprintf('n: %i rlx fac: %e error: %e x: ',n,lambda,err);\n fprintf(repmat('%e ',1,N),x);\n fprintf('\\n');\n end\n \n \nend % End of while loop\n\n% -------------------------------------------------------------------------\n% Some Postprocessing\n% -------------------------------------------------------------------------\nif(n.\n\nif (nargin < 4)\n error ('usage: prox_quadratic(x,A,b,alpha)') ;\nend\n\nif (alpha < 0)\n error('usage: prox_quadratic(x,A,b,alpha) - alpha should be positive')\nend\n\neps = 1e-10 ;\n \nif (norm( A - A') > eps)\n error('usage: prox_quadratic(x,A,b,alpha) - A should be a symmetric matrix') ;\nend\nA = A + eps * eye(size(A,1)) ;\nA = (A + A') / 2;\n\n[~,p] = chol(A) ;\n\nif (p > 0)\n error('usage: prox_quadratic(x,A,b,alpha) - A should be positive semidefinite\"') ;\nend\n\nn = length(x) ;\n\nout = (eye(n) + alpha * A) \\ (x - alpha * b) ; \n\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/prox_quadratic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.75915602202977}} {"text": "function [ r, seed ] = r4_uniform_01 ( seed )\n\n%*****************************************************************************80\n%\n%% R4_UNIFORM_01 is a uniform random number generator.\n%\n% Discussion:\n%\n% This routine implements the recursion\n%\n% seed = 16807 * seed mod ( 2**31 - 1 )\n% r4_uniform_01 = seed / ( 2**31 - 1 )\n%\n% The integer arithmetic never requires more than 32 bits,\n% including a sign bit.\n%\n% If the initial seed is 12345, then the first three computations are\n%\n% Input Output R4_UNIFORM_01\n% SEED SEED\n%\n% 12345 207482415 0.096616\n% 207482415 1790989824 0.833995\n% 1790989824 2035175616 0.947702\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 July 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley Interscience, page 95, 1998.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer SEED, the integer \"seed\" used to generate\n% the output random number. SEED should not be 0.\n%\n% Output, real R, a random value 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 seed = floor ( seed );\n\n seed = mod ( seed, 2147483647 );\n\n if ( seed < 0 ) \n seed = seed + 2147483647;\n end \n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + 2147483647;\n end\n\n r = seed * 4.656612875E-10;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sobol/r4_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7591352979205267}} {"text": " function centre=computeCOR(data,geo,angles,slice)\n% Code modified from SophiaBeads\n% (https://github.com/Sophilyplum/sophiabeads-datasets/blob/master/tools/centre_geom.m)\n% Reference:\n% T. Liu - \"Direct central ray determination in computed microtomography\",\n% Optical Engineering, April 2009.\n\n% Get central slice\nif nargin<4\n slice=floor(size(data,1)/2)+1;\nend\ndata=squeeze(data(slice,:,:));\n\nif size(angles,1)==1\n angles=angles'; \nend\n\n% Set up coordinate grids for testing the fit to data\n[angle_grid, det_grid] = meshgrid(angles',linspace(-geo.sDetector(1)/2+geo.dDetector(1)/2,+geo.sDetector(1)/2-geo.dDetector(1)/2,geo.nDetector(1))');\n% Wrap grids in the angular direction to avoid value out of range errors\nangle_grid = [(angle_grid - 2*pi) angle_grid (angle_grid + 2*pi)];\ndet_grid = repmat(det_grid,1,3);\ntest_data = double(repmat(data,1,3));\n\n% Start search using midpoint at zero\nmidpoint = 0;\n% Vector of precision values to search at\nprecision = [1 0.1 0.01 0.001 0.0001 0.00001 0.000001];\n\nfor i = 1:length(precision)\n \n COR = (midpoint - 10*precision(i)):precision(i):(midpoint + 10*precision(i)); % values for centre of rotation\n M = zeros(length(COR),1);\n \n for j = 1:length(COR)\n \n gamma = atan(linspace(-geo.sDetector(1)/2+geo.dDetector(1)/2,+geo.sDetector(1)/2-geo.dDetector(1)/2,geo.nDetector(1))' / geo.DSD); % angle of each ray relative to theoretical central ray \n gamma_c = atan(COR(j) / geo.DSD); % angle of assumed centre of rotation to central ray\n gamma_i = gamma - gamma_c;\n beta = 2 * gamma_i + pi;\n \n s2 = geo.DSD * tan(2 * gamma_c - gamma);\n s2 = repmat(s2, 1, size(angles,2));\n \n angles_aux = repmat(angles', geo.nDetector(1), 1) + repmat(beta, 1, size(angles,2));\n test = interp2(angle_grid, det_grid, test_data, angles_aux, s2, 'linear', 0);\n \n nonzero = find(test > 0);\n % We want the number of non-zero values for the average, not the sum of their positions\n M(j) = sum((test(nonzero) - data(nonzero)).^2)*(1/length(nonzero));\n end\n \n [~, indM] = min(M); % minimum value and index\n midpoint = COR(indM); % set midpoint for next search\nend\n\n% transform centre to required value\ncentre =- midpoint * geo.DSO / geo.DSD;\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/computeCOR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7591352964723538}} {"text": "function K = besselj_correlation ( s, t )\n\n%*****************************************************************************80\n%\n%% BESSELJ_CORRELATION evaluates the Bessel J correlation function.\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, real S(*), T(*), pairs of argument values.\n%\n% Output, real K(*), the correlation function values\n%\n K = besselj ( 0, abs ( s - 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/correlation_chebfun/besselj_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.759135290682906}} {"text": "function [y,pm0]=anaqpsk(N,Ncomp,f0);\n%ANAQPSK Quaternary Phase Shift Keying (QPSK) signal.\n% \t[Y,PM]=ANAQPSK(N,NCOMP,F0) returns a complex phase modulated signal\n% \tof normalized frequency F0, whose phase changes every NCOMP point according\n%\tto a discrete uniform law, between the values (0, pi/2, pi, 3*pi/2).\n% \tSuch signal is only 'quasi'-analytic.\n%\t\n%\tN : number of points\n%\tNCOMP : number of points of each component (default: N/5)\n% \tF0 : normalized frequency. (default: 0.25)\n% \tY : signal\n% \tPM0 : initial phase of each component\t (optional).\n%\n%\tExample :\n%\t [signal,pm0]=anaqpsk(512,64,0.05); clf; figure(gcf);\n% \t subplot(211); plot(real(signal)); subplot(212); plot(pm0);\n%\n%\tSee also ANAFSK, ANABPSK, ANAASK.\n\n%\tO. Lemoine - October 1995\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error('The number of parameters must be at least 1.');\nelseif (nargin == 1),\n Ncomp=round(N/5); f0=0.25;\nelseif (nargin == 2),\n f0=0.25;\nend;\n\nif (N <= 0),\n error('The signal length N must be strictly positive' );\nelseif (f0<0)|(f0>0.5),\n error('f0 must be between 0 and 0.5');\nend;\n\nMatlabVersion=version; MatlabVersion=str2num(MatlabVersion(1));\nif (MatlabVersion==4), rand('uniform'); end;\n\nm=ceil(N/Ncomp);\n\n% jumps=round(3*rand(m,1));\n% This is a modification proposed by Alpesh Patel, McMaster University\njumps=floor(4*rand(m,1)); jumps(jumps==4)=3;\n\npm0=pi*kron(jumps,ones(Ncomp,1))/2; pm0=pm0(1:N,1);\ntm=(1:N)'-1;\npm=(2.0*pi*f0*tm+pm0);\n\ny = exp(j*pm);\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/anaqpsk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8633915976709975, "lm_q1q2_score": 0.7590479403889501}} {"text": "function line_fekete_rule_test03 ( m )\n\n%*****************************************************************************80\n%\n%% LINE_FEKETE_RULE_TEST03 seeks Fekete points in [-1,+1].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the dimension of the polynomial space.\n%\n n = 5001;\n a = -1.0;\n b = +1.0;\n if ( nargin < 1 )\n m = 5;\n end\n x = linspace ( a, b, n );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_FEKETE_RULE_TEST03:\\n' );\n fprintf ( 1, ' Seek Fekete points in [%g,%g]\\n', a, b );\n fprintf ( 1, ' using %d equally spaced sample points\\n', n );\n fprintf ( 1, ' for polynomials of degree M = %d\\n', m );\n fprintf ( 1, ' with the Legendre basis and uniform weight.\\n' );\n\n [ nf, xf, wf, vf ] = line_fekete_legendre ( m, a, b, n, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NF = %d\\n', nf );\n r8vec_print ( nf, xf, ' Estimated Fekete points XF:' );\n\n wf_sum = sum ( wf(1:nf) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sum(WF) = %g\\n', wf_sum );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/line_fekete_rule/line_fekete_rule_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7590479352776176}} {"text": "function xy = ellipse_grid ( n, r, c, ng )\n\n%*****************************************************************************80\n%\n%% ELLIPSE_GRID generates grid points inside an ellipse.\n%\n% Discussion:\n%\n% The ellipse is specified as\n%\n% ( ( X - C1 ) / R1 )^2 + ( ( Y - C2 ) / R2 )^2 = 1\n%\n% The user supplies a number N. There will be N+1 grid points along\n% the shorter axis.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of subintervals.\n%\n% Input, real R(2), the half axis lengths.\n%\n% Input, real C(2), the center of the ellipse.\n%\n% Input, integer NG, the number of grid points inside the ellipse.\n%\n% Output, real XY(2,NG), the grid points.\n%\n if ( r(1) < r(2) )\n h = 2 * r(1) / ( 2 * n + 1 );\n ni = n;\n nj = ceil ( r(2) / r(1) ) * n;\n else\n h = 2 * r(2) / ( 2 * n + 1 );\n nj = n;\n ni = ceil ( r(1) / r(2) ) * n;\n end\n\n p = 0;\n\n for j = 0 : nj\n i = 0;\n x = c(1);\n y = c(2) + j * h;\n p = p + 1;\n xy(1:2,p) = [ x, y ]';\n if ( 0 < j )\n p = p + 1;\n xy(1:2,p) = [ x, 2 * c(2) - y ]';\n end\n while ( 1 )\n i = i + 1;\n x = c(1) + i * h;\n if ( 1 < ( ( x - c(1) ) / r(1) ).^2 + ( ( y - c(2) ) / r(2) ).^2 )\n break\n end\n p = p + 1;\n xy(1:2,p) = [ x, y ]';\n p = p + 1;\n xy(1:2,p) = [ 2 * c(1) - x, y ]';\n if ( 0 < j )\n p = p + 1;\n xy(1:2,p) = [ x, 2 * c(2) - y ]';\n p = p + 1;\n xy(1:2,p) = [ 2 * c(1) - x, 2 * c(2) - y ]';\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/ellipse_grid/ellipse_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7589224780494346}} {"text": "function [ll,ei] = minlen2(pp,tt)\n%MINLEN2 return the minimum length edge for each triangle in \n%a two-dimensional triangulation.\n% [ELEN,IMIN] = MINLEN2(VERT,TRIA) returns the minimum le-\n% ngth ELEN and local edge index IMIN for all triangles in\n% the triangulation {VERT,TRIA}.\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 16/01/2017\n\n%---------------------------------------------- basic checks \n if (~isnumeric(pp) || ~isnumeric(tt) )\n error('minlen2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ndims(tt) ~= +2 )\n error('minlen2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(pp,2)~= +2 || size(tt,2) < +3 )\n error('minlen2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nnod = size(pp,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(tt(:,1:3))) < +1 || ...\n max(max(tt(:,1:3))) > nnod )\n error('minlen2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n \n%------------------------------------------ compute edge-len\n l1 = sum((pp(tt(:,2),:) ...\n -pp(tt(:,1),:)).^2,2);\n l2 = sum((pp(tt(:,3),:) ...\n -pp(tt(:,2),:)).^2,2);\n l3 = sum((pp(tt(:,1),:) ...\n -pp(tt(:,3),:)).^2,2);\n\n%------------------------------------------ compute min.-len\n [ll,ei] = min([l1,l2,l3],[],+2);\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/mesh-util/minlen2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7589127586932253}} {"text": "function y = contrast_enhance ( x )\n\n%*****************************************************************************80\n%\n%% CONTRAST_ENHANCE applies contrast enhancement to a pixel.\n%\n% Discussion:\n%\n% This function accepts an array representing a pixel\n% neighborhood, and computes a value for the center pixel according to\n% a contrast enhancement algorithm. \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, uint8 X(N,N), the pixel values.\n%\n% Output, double Y, the new value to be assigned to the pixel\n% at X((N+1)/2,(N+1)/2) for enhanced contrast.\n%\n\n%\n% Convert image data from UINT8 to DOUBLE.\n%\n x = double ( x );\n%\n% Get the size of the array.\n%\n n = size ( x, 1 );\n%\n% Calculate the average value.\n%\n x_average = sum ( sum ( x(:,:) ) ) / n / n;\n%\n% The constant S should be chosen to be greater than 1;\n%\n s = 3.0;\n%\n% Compute the new value for the center pixel.\n%\n y = ( 1.0 - s ) * x_average + s * x((n+1)/2,(n+1)/2);\n\n return\nend\n\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/contrast_spmd/contrast_enhance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7588751540413727}} {"text": "% Compressed Sensing Examples\n% \n% Copyright 2016, All Rights Reserved\n% Code by Steven L. Brunton (sbrunton@uw.edu)\n\n% Download and install CVX to run this example: http://cvxr.com/cvx/download/\n\nclear all, close all, clc\n\nx = sort(4*(rand(25,1)-.5)); % Random data from [-2,2]\nb = .9*x + .1*randn(size(x)); % Line y=.9x with noise \natrue = x\\b; % Least-squares slope (no outliers)\n\nb(end) = -5.5; % Introduce outlier \nacorrupt = x\\b; % New slope\n\ncvx_begin; % L1 optimization to reject outlier\n variable aL1; % aL1 is slope to be optimized \n minimize( norm(aL1*x-b,1) ); % aL1 is robust\ncvx_end;\n\nhold on\nscatter(x(1:end-1),b(1:end-1),'bo') % Data\nscatter(x(end),b(end),'ro') % Outlier\nxgrid = -2:.01:2;\nplot(xgrid,xgrid*atrue,'k--') % L2 fit (no outlier)\nplot(xgrid,xgrid*acorrupt,'r--') % L2 fit (outlier)\nplot(xgrid,xgrid*aL1,'b--') % L1 fit\naxis([-2 2 -6 2])\n\n%%\nset(gcf,'Position',[100 100 600 400])\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', '-loose', '../figures/f_chCS_robustregression');", "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_SEC05_1_RobustRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7588392496263289}} {"text": "function [c,tc]=melcepst(s,fs,w,nc,p,n,inc,fl,fh)\n%MELCEPST Calculate the mel cepstrum of a signal C=(S,FS,W,NC,P,N,INC,FL,FH)\n%\n%\n% Simple use: (1) c=melcepst(s,fs) % calculate mel cepstrum with 12 coefs, 256 sample frames\n%\t\t\t (2) c=melcepst(s,fs,'E0dD') % include log energy, 0th cepstral coef, delta and delta-delta coefs\n%\n% Inputs:\n% s\t speech signal\n% fs sample rate in Hz (default 11025)\n% w mode string (see below)\n% nc number of cepstral coefficients excluding 0'th coefficient [default 12]\n% p number of filters in filterbank [default: floor(3*log(fs)) = approx 2.1 per ocatave]\n% n length of frame in samples [default power of 2 < (0.03*fs)]\n% inc frame increment [default n/2]\n% fl low end of the lowest filter as a fraction of fs [default = 0]\n% fh high end of highest filter as a fraction of fs [default = 0.5]\n%\n%\t\tw any sensible combination of the following:\n%\n% 'R' rectangular window in time domain\n%\t\t\t\t'N'\t Hanning window in time domain\n%\t\t\t\t'M'\t Hamming window in time domain (default)\n%\n% 't' triangular shaped filters in mel domain (default)\n% 'n' hanning shaped filters in mel domain\n% 'm' hamming shaped filters in mel domain\n%\n%\t\t\t\t'p'\t filters act in the power domain\n%\t\t\t\t'a'\t filters act in the absolute magnitude domain (default)\n%\n% '0' include 0'th order cepstral coefficient\n%\t\t\t\t'E' include log energy\n%\t\t\t\t'd'\t include delta coefficients (dc/dt)\n%\t\t\t\t'D'\t include delta-delta coefficients (d^2c/dt^2)\n%\n% 'z' highest and lowest filters taper down to zero (default)\n% 'y' lowest filter remains at 1 down to 0 frequency and\n%\t\t\t \t highest filter remains at 1 up to nyquist freqency\n%\n%\t\t If 'ty' or 'ny' is specified, the total power in the fft is preserved.\n%\n% Outputs:\tc mel cepstrum output: one frame per row. Log energy, if requested, is the\n% first element of each row followed by the delta and then the delta-delta\n% coefficients.\n% tc fractional time in samples at the centre of each frame\n% with the first sample being 1.\n%\n\n% BUGS: (1) should have power limit as 1e-16 rather than 1e-6 (or possibly a better way of choosing this)\n% and put into VOICEBOX\n% (2) get rdct to change the data length (properly) instead of doing it explicitly (wrongly)\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: melcepst.m 4914 2014-07-24 08:44:26Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<2 fs=11025; end\nif nargin<3 w='M'; end\nif nargin<4 nc=12; end\nif nargin<5 p=floor(3*log(fs)); end\nif nargin<6 n=pow2(floor(log2(0.03*fs))); end\nif nargin<9\n fh=0.5; \n if nargin<8\n fl=0;\n if nargin<7\n inc=floor(n/2);\n end\n end\nend\n\nif isempty(w)\n w='M';\nend\nif any(w=='R')\n [z,tc]=enframe(s,n,inc);\nelseif any (w=='N')\n [z,tc]=enframe(s,hanning(n),inc);\nelse\n [z,tc]=enframe(s,hamming(n),inc);\nend\nf=rfft(z.');\n[m,a,b]=melbankm(p,n,fs,fl,fh,w);\npw=f(a:b,:).*conj(f(a:b,:));\npth=max(pw(:))*1E-20;\nif any(w=='p')\n y=log(max(m*pw,pth));\nelse\n ath=sqrt(pth);\n y=log(max(m*abs(f(a:b,:)),ath));\nend\nc=rdct(y).';\nnf=size(c,1);\nnc=nc+1;\nif p>nc\n c(:,nc+1:end)=[];\nelseif p0.5\n l = l + 1;\n A(i,l) = 1;\n A(j,l) = -1;\n end;\n end;\nend;\nA = sparse(A);\n\n% Compute edge weights: some optimal, some based on heuristics\n[n,m] = size(A);\n\n[ w_fdla, rho_fdla ] = fdla(A);\n[ w_fmmc, rho_fmmc ] = fmmc(A);\n[ w_md, rho_md ] = max_deg(A);\n[ w_bc, rho_bc ] = best_const(A);\n[ w_mh, rho_mh ] = mh(A);\n\ntau_fdla = 1/log(1/rho_fdla);\ntau_fmmc = 1/log(1/rho_fmmc);\ntau_md = 1/log(1/rho_md);\ntau_bc = 1/log(1/rho_bc);\ntau_mh = 1/log(1/rho_mh);\n\neig_opt = sort(eig(eye(n) - A * diag(w_fdla) * A'));\neig_fmmc = sort(eig(eye(n) - A * diag(w_fmmc) * A'));\neig_mh = sort(eig(eye(n) - A * diag(w_mh) * A'));\neig_md = sort(eig(eye(n) - A * diag(w_md) * A'));\neig_bc = sort(eig(eye(n) - A * diag(w_bc) * A'));\n\nfprintf(1,'\\nResults:\\n');\nfprintf(1,'FDLA weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_fdla,tau_fdla);\nfprintf(1,'FMMC weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_fmmc,tau_fmmc);\nfprintf(1,'M-H weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_mh,tau_mh);\nfprintf(1,'MAX_DEG weights:\\t rho = %5.4f \\t tau = %5.4f\\n',rho_md,tau_md);\nfprintf(1,'BEST_CONST weights:\\t rho = %5.4f \\t tau = %5.4f\\n',rho_bc,tau_bc);\n\n% plot results\nfigure(1), clf\ngplot(Ad,xy);\nhold on;\nplot(xy(:,1), xy(:,2), 'ko','LineWidth',4, 'MarkerSize',4);\naxis([0.05 1.1 -0.1 0.95]);\ntitle('Graph')\nhold off;\n\nfigure(2), clf\nv_fdla = [w_fdla; diag(eye(n) - A*diag(w_fdla)*A')];\n[ifdla, jfdla, neg_fdla] = find( v_fdla.*(v_fdla < -0.001 ) );\nv_fdla(ifdla) = [];\nwbins = [-0.6:0.012:0.6];\nhist(neg_fdla,wbins); hold on,\nh = findobj(gca,'Type','patch');\nset(h,'FaceColor','r')\nhist(v_fdla,wbins); hold off,\naxis([-0.6 0.6 0 12]);\nxlabel('optimal FDLA weights');\nylabel('histogram');\n\nfigure(3), clf\nxbins = (-1:0.015:1)';\nymax = 6;\nsubplot(3,1,1)\nhist(eig_md, xbins); hold on;\nmax_md = max(abs(eig_md(1:n-1)));\nplot([-max_md -max_md],[0 ymax], 'b--');\nplot([ max_md max_md],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'MAX DEG');\ntitle('Eigenvalue distributions')\nsubplot(3,1,2)\nhist(eig_bc, xbins); hold on;\nmax_opt = max(abs(eig_bc(1:n-1)));\nplot([-max_opt -max_opt],[0 ymax], 'b--');\nplot([ max_opt max_opt],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'BEST CONST');\nsubplot(3,1,3)\nhist(eig_opt, xbins); hold on;\nmax_opt = max(abs(eig_opt(1:n-1)));\nplot([-max_opt -max_opt],[0 ymax], 'b--');\nplot([ max_opt max_opt],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'FDLA');\n\nfigure(4), clf\nxbins = (-1:0.015:1)';\nymax = 6;\nsubplot(3,1,1)\nhist(eig_md, xbins); hold on;\nmax_md = max(abs(eig_md(1:n-1)));\nplot([-max_md -max_md],[0 ymax], 'b--');\nplot([ max_md max_md],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'MAX DEG');\ntitle('Eigenvalue distributions')\nsubplot(3,1,2)\nhist(eig_mh, xbins); hold on;\nmax_opt = max(abs(eig_mh(1:n-1)));\nplot([-max_opt -max_opt],[0 ymax], 'b--');\nplot([ max_opt max_opt],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'MH');\nsubplot(3,1,3)\nhist(eig_fmmc, xbins); hold on;\nmax_opt = max(abs(eig_fmmc(1:n-1)));\nplot([-max_opt -max_opt],[0 ymax], 'b--');\nplot([ max_opt max_opt],[0 ymax], 'b--');\naxis([-1 1 0 ymax]);\ntext(0,5,'FMMC');\n\nfigure(5), clf\nv_fmmc = [w_fmmc; diag(eye(n) - A*diag(w_fmmc)*A')];\n[ifmmc, jfmmc, nonzero_fmmc] = find( v_fmmc.*(v_fmmc > 0.001 ) );\nhist(nonzero_fmmc,80);\naxis([0 1 0 10]);\nxlabel('optimal positive FMMC weights');\nylabel('histogram');\n\nfigure(6), clf\nAn = abs(A*diag(w_fmmc)*A');\nAn = (An - diag(diag(An))) > 0.0001;\ngplot(An,xy,'b-'); hold on;\nh = findobj(gca,'Type','line');\nset(h,'LineWidth',2.5)\ngplot(Ad,xy,'b:');\nplot(xy(:,1), xy(:,2), 'ko','LineWidth',4, 'MarkerSize',4);\naxis([0.05 1.1 -0.1 0.95]);\ntitle('Subgraph with positive transition prob.')\nhold off;\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/graph_laplacian/larger_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.758752619771548}} {"text": "function [val,idx] = of_MARE(obs,sim,idx)\n% of_MARE Calculates the Mean Absolute Relative Error of simulated \n% streamflow. Ignores time steps with negative flow values. Adds a constant\n% e of 1/100 of mean(obs) to avoid issues with zero flows (Pushpalatha et\n% al., 2012).\n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% In:\n% obs - time series of observations [nx1]\n% sim - time series of simulations [nx1]\n% idx - optional vector of indices to use for calculation, can be\n% logical vector [nx1] or numeric vector [mx1], with m <= n\n%\n% Out:\n% val - objective function value [1x1]\n% idx - vector of indices used for calculation\n\n% Pushpalatha, R.; Perrin, C.; le Moine, N. and Andréassian V. (2012). \"A\n% review of efficiency criteria suitable for evaluating low-flow\n% simulations\". Journal of Hydrology. 420-421, 171-182. \n% doi:10.1016/j.jhydrol.2011.11.055\n\n%% Check inputs and select timesteps\nif nargin < 2\n error('Not enugh input arguments') \nend\n\nif nargin < 3; idx = []; end\n[sim, obs, idx] = check_and_select(sim, obs, idx); \n\n%% Find the constant e\ne = mean(obs)/100;\n\n%% Apply constant and transform flows\nobs = obs+e;\nsim = sim+e;\n\n%% Calculate metric\nval = mean(abs((sim-obs)./obs));\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Functions/Objective functions/of_MARE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7585898705906635}} {"text": "function [alpha, beta, mu, delta] = nigpar(m, v, s, k)\n%NIGPAR Parameters for the Normal-Inverse-Gaussian distribution.\n% [ALPHA, BETA, MU, DELTA] = NIGPAR(M, V, S, K) returns the scale \n% paramter ALPHA, BETA which determines the skewness, the location \n% parameter MU and the scale parameter DELTA of the Normal-Inverse-Gaussian \n% distribution with mean M, variance V, skewness S and kurtosis K.\n%\n% See also NIGPDF, NIGCDF, NIGINV, NIGRND, NIGSTATS.\n%\n% References:\n% [1] Prause, K. (1999). The Generalized Hyperbolic Model\n\n% -------------------------------------------------------------------------\n% \n% Allianz, Group Risk Controlling\n% Risk Methodology\n% Koeniginstr. 28\n% D-80802 Muenchen\n% Germany\n% Internet: www.allianz.de\n% email: ralf.werner@allianz.de\n% \n% Implementation Date: 2006 - 05 - 01\n% Author: Dr. Ralf Werner\n%\n% -------------------------------------------------------------------------\n\nTol = 1.0e-007;\n\n%% Default values\nif nargin < 1\n m = 0;\nend\nif nargin < 2\n v = 1;\nend\nif nargin < 4\n if nargin < 3\n s = 0;\n k = 3 + Tol;\n else\n k = 3 + 5/3*s^2 + Tol;\n end\nend\n\n%% Constraints for the parameters\n\nif v <= 0\n error('The variance V must be positive.');\nend\n\nif (k - 5/3*s^2 - 3 <= 0)\n error('K must be greater than 3 + 5/3 S^2.');\nend\n \nalpha = sqrt((3*k - 4*s^2 - 9) / (v*(k-5/3*s^2 - 3)^2));\nbeta = s/(sqrt(v)*(k - 5/3*s^2 - 3));\nmu = m - 3*s*sqrt(v)/(3*k - 4*s^2 - 9);\ndelta = 3^(3/2)*sqrt(v*(k - 5/3*s^2 - 3))/(3*k - 4*s^2 - 9);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/10934-normal-inverse-gaussian-nig-distribution-updated-version/nigpar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7585898695541016}} {"text": "function D = EuDist2(fea_a,fea_b,bSqrt)\n%EUDIST2 Efficiently Compute the Euclidean Distance Matrix by Exploring the\n%Matlab matrix operations.\n%\n% D = EuDist(fea_a,fea_b)\n% fea_a: nSample_a * nFeature\n% fea_b: nSample_b * nFeature\n% D: nSample_a * nSample_a\n% or nSample_a * nSample_b\n%\n% Examples:\n%\n% a = rand(500,10);\n% b = rand(1000,10);\n%\n% A = EuDist2(a); % A: 500*500\n% D = EuDist2(a,b); % D: 500*1000\n%\n% version 2.1 --November/2011\n% version 2.0 --May/2009\n% version 1.0 --November/2005\n%\n% Written by Deng Cai (dengcai AT gmail.com)\n\n\nif ~exist('bSqrt','var')\n bSqrt = 1;\nend\n\nif (~exist('fea_b','var')) || isempty(fea_b)\n aa = sum(fea_a.*fea_a,2);\n ab = fea_a*fea_a';\n \n if issparse(aa)\n aa = full(aa);\n end\n \n D = bsxfun(@plus,aa,aa') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\n D = max(D,D');\nelse\n aa = sum(fea_a.*fea_a,2);\n bb = sum(fea_b.*fea_b,2);\n ab = fea_a*fea_b';\n\n if issparse(aa)\n aa = full(aa);\n bb = full(bb);\n end\n\n D = bsxfun(@plus,aa,bb') - 2*ab;\n D(D<0) = 0;\n if bSqrt\n D = sqrt(D);\n end\nend\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/EuDist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7585898668643793}} {"text": "function [ vX ] = ProjectL2Ball( vY, ballRadius )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = ProjectL2Ball( vY, ballRadius, stopThr )\n% Solving the Orthogonal Projection Problem of the input vector onto the\n% L2 Ball.\n% Input:\n% - vY - Input Vector.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - ballRadius - Ball Radius.\n% Sets the Radius of the L2 Ball. For Unit L2 Ball\n% set to 1.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% Output:\n% - vX - Output Vector.\n% The projection of the Input Vector onto the L2\n% Ball.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. h\n% Remarks:\n% 1. a\n% TODO:\n% 1. U.\n% Release Notes:\n% - 1.0.000 29/06/2017 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nvX = min((ballRadius / norm(vY, 2)), 1) * vY;\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q2327504/ProjectL2Ball.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.758539789399421}} {"text": "function [ pr, pq ] = plane_normal_basis_3d ( pp, normal )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_BASIS_3D finds two perpendicular vectors in a plane in 3D.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% N is a normal vector to the plane.\n%\n% The two vectors to be computed, PQ and PR, can be regarded as\n% the basis of a Cartesian coordinate system for points in the plane.\n% Any point in the plane can be described in terms of the \"origin\"\n% point PP plus a weighted sum of the two vectors PQ and PR:\n%\n% P = PP + a * PQ + b * PR.\n%\n% The vectors PQ and PR have unit length, and are perpendicular to N\n% and to each other.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane. (Actually,\n% we never need to know these values to do the calculation!)\n%\n% Input, real NORMAL(3), a normal vector N to the plane. The\n% vector must not have zero length, but it is not necessary for N\n% to have unit length.\n%\n% Output, real PR(3), a vector of unit length,\n% perpendicular to the vector N and the vector PQ.\n%\n% Output, real PQ(3), a vector of unit length,\n% perpendicular to the vector N and the vector PR.\n%\n dim_num = 3;\n%\n% Compute the length of NORMAL.\n%\n normal_norm = norm ( normal );\n\n if ( normal_norm == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_NORMAL_BASIS_3D - Fatal error!\\n' );\n fprintf ( 1, ' The normal vector is 0.\\n' );\n error ( 'PLANE_NORMAL_BASIS_3D - Fatal error!' );\n end\n%\n% Find a vector PQ that is normal to NORMAL and has unit length.\n%\n pq = r8vec_any_normal ( dim_num, normal );\n%\n% Now just take the cross product NORMAL x PQ to get the PR vector.\n%\n pr = r8vec_cross_product_3d ( normal, pq );\n\n pr_norm = norm ( pr );\n\n pr(1:dim_num) = pr(1:dim_num) / pr_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/sphere_stereograph/plane_normal_basis_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7585268383521002}} {"text": "function [x,param,values] = coarserefine(f,intrv,theta,N,alpha)\n% 1-D adaptive residual subsampling method for radial basis function \n% interpolation\n%\n% f: function defined on interval intrv = [a b].\n% intrv: interval [a b] where f is defined.\n% theta: threshold interval [thetar thetac] where thetac < thetar.\n% thetar: refinement threshold.\n% thetac: coarsening threshold.\n% N: Initial equally-spaced N centers.\n% alpha: global multiplier of multiquadric parameters\n%\n% Example 1 : f = @(x) abs(x+.04)\n% coarserefine(f,[-1 1],[5e-5 5e-7],11,0.75)\n%\n% Example 2 : coarserefine(@(x)myfun(x,5),[-1 1],[5e-5 5e-7],11,0.75)\n% %----------------------%\n% function y = myfun2(x,c)\n% y = 1./(1 + (c*x).^2);\n% %----------------------% \n% For reference, see:\n% Adaptive residual subsampling methods for radial basis function\n% interpolation and collocation problems. submitted to Computers Math. Appl\n%\n% Tobin A. Driscoll and Alfa R.H. Heryudono 05/14/2006\n% MATLAB 7 is recommended.\n\n% Initial points\nx = linspace(intrv(1),intrv(2),N)';\nN = length(x); dx = diff(x); \nepsilon = alpha*min([Inf;1./dx],[1./dx;Inf]);\ny = x(1:N-1) + 0.5*dx;\n\nrefine = true;\nwhile any(refine)\n A = zeros(N); B = zeros(N-1,N);\n for j=1:N\n A(:,j) = mq(x,x(j),epsilon(j));\n B(:,j) = mq(y,x(j),epsilon(j));\n end\n lambda = A\\feval(f,x); \n resid = abs(B*lambda - feval(f,y)); \n \n refine = resid > theta(1);\n fprintf('Adding %i centers.',sum(refine))\n vals = sortrows([[x;y(refine)] [feval(f,x);B(refine,:)*lambda]]);\n x = vals(:,1); vals(:,1)=[];\n dx = diff(x); epsilon = alpha*min([Inf;1./dx],[1./dx;Inf]);\n \n coarsen = resid(1:N-2) < theta(2) & resid(2:N-1) < theta(2);\n coarsen = 1+find(coarsen); x(coarsen) = []; vals(coarsen) = []; epsilon(coarsen)=[];\n fprintf(' Removing %i centers.\\n',length(coarsen))\n \n N = length(x);\n y = x(1:N-1) + 0.5*diff(x);\nend\n\nif nargout > 1\n param = epsilon;\n if nargout > 2\n values = vals;\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/11101-adaptive-residual-subsampling-for-radial-basis-functions/adaptburgers_mol/coarserefine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7584886547545481}} {"text": "function determ = poisson_determinant ( nrow, ncol )\n\n%*****************************************************************************80\n%\n%% POISSON_DETERMINANT returns the determinant of the POISSON matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NROW, NCOL, the number of rows and columns \n% in the grid.\n%\n% Output, real DETERM, the determinant.\n%\n cr = zeros ( nrow, 1 );\n for i = 1 : nrow\n angle = i * pi / ( nrow + 1 );\n cr(i) = cos ( angle );\n end\n\n cc = zeros ( ncol, 1 );\n for i = 1 : ncol\n angle = i * pi / ( ncol + 1 );\n cc(i) = cos ( angle );\n end\n\n determ = 1.0;\n\n for i = 1 : nrow\n for j = 1 : ncol\n determ = determ * ( 4.0 - 2.0 * cr(i) - 2.0 * cc(j) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/poisson_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.758488653947962}} {"text": "function xmat = ptrend(p,nobs)\n% PURPOSE: produce an explanatory variables matrix\n% containing a polynomial time-trend\n% ----------------------------------------------------\n% USAGE: xmat = ptrend(p,nobs);\n% where: p = order of the time-trend polynomial\n% p < 0, xmat = iota (nobs x 1) vector of ones\n% p = 1, xmat = time trend\n% p > 1, xmat = higher order polynomial in time\n% nobs = size of the matrix\n% ----------------------------------------------------\n% RETURNS: xmat = matrix containing polynomial trend model data set\n% ----------------------------------------------------\n\n% written by:\n% James P. LeSage, Dept of Economics\n% University of Toledo\n% 2801 W. Bancroft St,\n% Toledo, OH 43606\n% jlesage@spatia-econometrics.com\n\n\n u = ones(nobs,1) ;\n if p > 0\n timep = zeros(nobs,p) ;\n t = 1:nobs;\n t = (t')/nobs;\n m = 1 ;\n while (m <= p)\n timep(:,m) = t.^m ;\n m = m + 1 ;\n end;\n xmat = [u timep];\n else,\n xmat = u ;\n end;\n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/v3dot0/Auxiliary/ptrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7584886439082642}} {"text": "function [ g ] = gsp_design_held(G, param)\n%GSP_DESIGN_HELD Create a Held filterbank\n% Usage: g = gsp_design_held( G );\n% g = gsp_design_held( G, param );\n% \n% Inputs parameters:\n% G : Graph structure or lmax\n% param : Structure of optional parameters\n%\n% Outputs parameters:\n% g : filterbank\n%\n% This function create a parseval filterbank of $2$ filters. The low-pass\n% filter is defined by a function $f_l(x)$: \n%\n% .. / 1 if x <= a \n% .. f_l(x) = | sin(2*pi*mu(val(r2ind)/(8*a))) if a < x <= 2a\n% .. \\ 0 if x > 2a\n%\n% .. math:: f_{l}=\\begin{cases} 1 & \\mbox{if }x\\leq a\\\\ \\sin\\left(2\\pi\\mu\\left(\\frac{x}{8a}\\right)\\right) & \\mbox{if }a2a \\end{cases}\n%\n% with \n%\n% .. mu(x) = -1 + 24*x - 144*x^2 + 256*x^3\n% \n% .. math:: \\mu(x) = -1+24x-144*x^2+256*x^3\n%\n% The high pass filter is adaptated to obtain a tight frame.\n%\n% This function will compute the maximum eigenvalue of the laplacian. To\n% be more efficient, you can precompute it using::\n%\n% G = gsp_estimate_lmax(G);\n%\n% Example:::\n%\n% G = gsp_sensor(100);\n% G = gsp_estimate_lmax(G);\n% g = gsp_design_held(G); \n% gsp_plot_filter(G,g); \n% [A,B] = gsp_filterbank_bounds(G,g)\n%\n% *param* is an optional structure containing the following fields\n%\n% * *param.verbose*: verbosity level. 0 no log - 1 display warnings.\n% (default 1) \n% * *param.a*: see equations above for this parameter. Note that the\n% spectrum is scaled between 0 and 2 (default 2/3).\n%\n\n% Author: Nathanael Perraudin, David Shuman\n% Date : 21 June 2014\n% Testing: test_filter\n\n\nif nargin < 2\n param = struct;\nend\n\n\nif ~isfield(param,'verbose'), param.verbose = 1; end\nif ~isfield(param,'a'), param.a = 2/3; end\n\nif isstruct(G)\n if ~isfield(G,'lmax')\n if param.verbose\n fprintf('GSP_DESIGN_HELD has to compute lmax \\n')\n end\n G = gsp_estimate_lmax(G);\n end\n lmax = G.lmax;\nelse\n lmax = G;\nend\n\n\n\n\na = param.a;\n\ng = cell(2,1);\ng{1} = @(x) held(x*(2/lmax),a);\ng{2} = @(x) real(sqrt(1-(held(x*(2/lmax),a)).^2));\n\nend\n\n\nfunction y = held(val,a)\n\ny = zeros(size(val));\n\nl1 = a;\nl2 = 2*a;\nmu = @(x) -1+24*x-144*x.^2+256*x.^3; \n\nr1ind = val >= 0 & val < l1;\nr2ind = val >= l1 & val < l2;\nr3ind = val >= l2;\n\n\ny(r1ind) = 1;\ny(r2ind) = sin(2*pi*mu(val(r2ind)/(8*a)));\ny(r3ind) = 0;\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_design_held.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7583969054503518}} {"text": "function [L] = lap2DPeriodic(N, h);\n%\n% [L] = lap2DPeriodic(N, h)\n%\n% Constructs the 2D Laplacian for a periodic square mesh using\n% the standard 5-point stencil.\n%\n% Returns:\n% L = discrete Laplacian\n%\n% Input:\n% N = number of mesh points in each direction\n% h = mesh width\n%\n%\n%\n% License: This code is free to use for any purposes, provided\n% any publications resulting from the use of this code\n% reference the original code/author.\n%\n% Author: Samuel Isaacson (isaacson@math.utah.edu)\n% Date: 11/2007\n%\n% Please notify the author of any bugs, and contribute any\n% modifications or bug fixes back to the original author.\n%\n% Disclaimer:\n% This code is provided as is. The author takes no responsibility \n% for its results or effects.\n\nM = N * N;\n\n\n% Periodic 2D Laplace Operator on Square:\nisPeriodic = 1;\ne = ones(M,1);\ned = -4*e;\nif( ~isPeriodic )\n ed(N:N:M) = -3;\n ed(1:N:M) = -3;\n ed(1) = -2;\n ed(N) = -2;\n ed((N-1)*N+1) = -2;\n ed(N*N) = -2;\nend\neu1 = ones(M,1);\neu1((N+1):N:M) = 0;\ned1 = ones(M,1);\ned1(N:N:M) = 0;\n \nL = spdiags([e ed1 ed eu1 e], [-N -1:1 N], M, M);\n\nif( isPeriodic )\n for(i = 1:N)\n L( i, N*N-N+i ) = 1;\n L( N*N-N+i, i ) = 1;\n L( (i-1)*N+1, i*N ) = 1;\n L( i*N, (i-1)*N+1 ) = 1;\n end\nend\n\nL = L ./ (h*h);\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/IBM/lap2DPeriodic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.758364975494737}} {"text": "%NCC Normalized cross correlation\n%\n% M = NCC(I1, I2) is the normalized cross-correlation between the \n% two equally sized image patches I1 and I2. The result M is a scalar in\n% the interval -1 (non match) to 1 (perfect match) that indicates similarity.\n%\n% Notes::\n% - A value of 1 indicates identical pixel patterns.\n% - The NCC similarity measure is invariant to scale changes in image\n% intensity.\n%\n% See also ZNCC, SAD, SSD, ISIMILARITY.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\n\nfunction m = ncc(w1, w2)\n\n\tdenom = sqrt( sum(sum(w1.^2))*sum(sum(w2.^2)) );\n\n\tif denom < 1e-10,\n\t\tm = 0;\n\telse\n\t\tm = sum(sum((w1.*w2))) / denom;\n\tend\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/ncc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7583649734448412}} {"text": "function y = huber_circ( x, dim, varargin )\n\n%HUBER_CIRC Huber penalty function with circular symmetry.\n% For a vector X, HUBER_CIRC(X) computes the Huber penalty function\n%\n% HUBER_CIRC(X) = NORM(X,2)^2 if NORM(X,2)<=1,\n% 2*NORM(X,2)-1 if NORM(X,2)>=1.\n%\n% For matrices and N-D arrays, the penalty function is applied to the\n% first dimens\n%\n% HUBER_CIRC(X,[],M) computes the penalty function with halfwidth M,\n% M.^2.*HUBER_CIRC(X./M). M must be real and positive.\n%\n% HUBER_CIRC(X,[],M,T) computes the penalty function with halfwidth M\n% and concomitant scale T:\n%\n% HUBER_CIRC(X,[],M,T) = T.*HUBER_CIRC(X./T,[],M) if T > 0\n% +Inf if T <= 0\n%\n% See the help file for HUBER for information about this usage.\n%\n% If X is a matrix, the penalty function is applied to the columns of the\n% matrix X, and a row vector is returned. If X is an N-D matrix, the \n% penalties are computed along the first non-singleton dimension.\n%\n% HUBER_CIRC(X,DIM), HUBER_CIRC(X,DIM,M), and HUBER_CIRC(X,DIM,M,T) \n% computes the penalty along the dimension DIM.\n%\n% Disciplined convex programming information:\n% HUBER_CIRC is jointly convex in X and T. It is nonomonotonic in X \n% and nonincreasing in T. Therefore, when used in CVX specifications, \n% X must be affine and T must be concave (or affine). T must be real.\n% X, on the other hand, may be real or complex.\n\nif nargin < 2, dim = []; end\ny = huber_pos( norms( x, 2, dim ), varargin{:} );\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/huber_circ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7583649712532202}} {"text": "function [UX, DX, VX] = fadi( A, B, M, N, p, q )\n%FADI Factored alternating direction implicit method.\n% X = FADI( A, B, M, N, p, q ) solves the Sylvester equation\n%\n% A*X - X*B = M*N.'\n%\n% using the FADI method with ADI shifts p and q. The righthand side must be\n% given in low-rank form, i.e., M and N where rhs = M*N.'.\n\n%% Reference: \n%\n% [1] Benner, Peter, Ren-Cang Li, and Ninoslav Truhar. \n% \"On the ADI method for Sylvester equations.\" J. of Comp. and App. Math.\n% 233.4 (2009): 1035-1045. \n\n[m, rho] = size( M ); \nn = size(N, 1); \nRankOfSolution = rho * numel(p);\nUX = zeros(m, RankOfSolution);\nVX = zeros(n, RankOfSolution);\nDX = diag( kron(q-p, ones(1,rho)) );\nIm = speye(m);\nIn = speye(n);\nUX(:, 1:rho) = (A+p(1)*Im)\\M;\nVX(:, 1:rho) = (B+q(1)*In)\\N;\nfor j = 1:numel(p)-1\n UX(:, j*rho+(1:rho)) = (A+q(j)*Im)*((A+p(j+1)*Im)\\UX(:,(j-1)*rho+(1:rho)));\n VX(:, j*rho+(1:rho)) = (B+p(j)*In)*((B+q(j+1)*In)\\VX(:,(j-1)*rho+(1:rho)));\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/fadi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7583381124663191}} {"text": "function simplex_monte_carlo_test02 ( )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_MONTE_CARLO_TEST02 estimates integrals in 6D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 3;\n e_test = [ ...\n 0, 0, 0, 0, 0, 0; ...\n 1, 0, 0, 0, 0, 0; ...\n 0, 2, 0, 0, 0, 0; ...\n 0, 2, 2, 0, 0, 0; ...\n 0, 0, 0, 4, 0, 0; ...\n 2, 0, 0, 0, 2, 2; ...\n 0, 0, 0, 0, 0, 6 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' Use SIMPLEX01_SAMPLE for a Monte Carlo estimate of an\\n' );\n fprintf ( 1, ' integral over the interior of the unit simplex in 6D.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N' );\n fprintf ( 1, ' 1 ' );\n fprintf ( 1, ' U ' );\n fprintf ( 1, ' V^2 ' );\n fprintf ( 1, ' V^2W^2' );\n fprintf ( 1, ' X^4 ' );\n fprintf ( 1, ' Y^2Z^2' );\n fprintf ( 1, ' Z^6\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = simplex01_sample ( m, n, seed );\n\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e(1:m) = e_test(1:m,j);\n\n value = monomial_value ( m, n, e, x );\n\n result = simplex01_volume ( m ) * sum ( value(1:n) ) / n;\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * n;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact' );\n for j = 1 : 7\n\n e(1:m) = e_test(1:m,j);\n\n result = simplex01_monomial_integral ( m, e );\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/simplex_monte_carlo/simplex_monte_carlo_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7582478897667649}} {"text": "function [delayDopPlot,Doppler,delay]=delayDopplerPlotNBPulseDop(x,y,M1,M2,wDoppler,T0)\n%%DELAYDOPPLERPLOTNBPULSEDOP This function produces the complex\n% delay-Doppler plot for a narrowband signal assuming that\n% the same waveform is repeated every single pulse or that\n% each pulse ends with a region of non-broadcasting (>100%\n% duty cycle) and the maximum delay is less than that\n% duration. Range migration is not taken into account. Such\n% plots can be used for detection.\n%\n%INPUTS: x The NPulseX1 complex baseband waveform that is repeated every\n% pulse repetition interval (PRI). If NPulse=0 for the discrete delay. Also, we\n%will throw out the phase constant of exp(1j*2*pi*fc*tau) in front. The\n%result is thus:\n%sum_{i=0}^{N_B-1}exp(1j*2*pi*fc*a*i*TB)*sum_{k=0}^{Ns-1} conj(x(k-tauHat))*y(i,k) \n%Thus, the integral has turned into a discrete sum over the samples in each\n%block (the arguments of x and y access the discrete elements). There is no\n%block marking on x, because it is assumed to be the same for all blocks.\n%Looking at the form of the sum, it can be shown (for example, see Chapter\n%5.7 of [1] for useful identities) that it is equivalent to the circular\n%convolution of flipud(conj(x)) with y. This can be evaluated for all\n%discrete delays tau and block i in parallel using ffts and an ifft. This\n%is what is implemented below via the circConv function. The outer sum in\n%the above can be seen to be NB times the ifft taken across all values of i\n%when we replace a with a=aHat/(fc*TB*NB) where aHat is a discrete Doppler\n%shift from 0 to (NB-1). Thus, the ifft function, as used below, evaluated\n%all of the Doppler shifts in parallel for the matched filter, scaled by\n%1/NB.\n%\n%Thus, as described above, we are evaluating \n%(1/NB)*sum_{i=0}^{N_B-1}exp(1j*2*pi*aHat*i/NB)*sum_{k=0}^{Ns-1} conj(x(k-tauHat,i))*y(i,k) \n%for discrete values of aHat and tauHat. However, it would be nice if the\n%output could be related to the amplitude A. Well, if we assume that tauHat\n%and aHat perfectly match the original signal AND the original signal was\n%generated using the various narrowband simplications mentioned, then we\n%have to multiply the result by 1/(x'*x). This is what is done below.\n%However, opne must realize that the various approximations means that the\n%amplitude estimates can still be biased. This is demonstrated in the\n%example below.\n%\n%Often, the sidelobes of the signal in Doppler might be high. Thus, the\n%input wDoppler can be used to apply tapering across each bin before the\n%final ifft of the algorithm.\n%\n%The final thing to note is that the above method describes only processing\n%for positive Doppler values. Due to the aliasing of large values to\n%negative values with circular convolutions and FFTs, we use fftshift to\n%get positive and negative values in the unambiguous Doppler region.\n%\n%Note that TB*c gives the maximum unambiguous range, where c is the speed\n%of propagation in the medium, for example c=Constants.speedOfLight.\n%Note that c/(2*fc*TB) is the magnitude of the maximum unambiguous range\n%rate. One can get those as\n% range=c*delay;\n% rangeRate=Doppler*(c/fc);\n%\n%EXAMPLE:\n%Our signal is a up-chirp. Here, we create the time-delayed Doppler shifted\n%signal at baseband. The target signal is generated in two ways: Once\n%including all of the phase shifts associated with range migration, and\n%once with the ideal signal processing model that is used to derive the\n%range-Doppler map using Fourier transforms to make it fast. We choose the\n%target location to be EXACTLY on a delay-Doppler bin. It will be seen\n%that the complex amplitude obtained using the ideal model matches the\n%complex amplitude used in generating the signal (no noise is added).\n%However, the complex amplitude obtained when using the more realistic\n%model for the signal, including all range migration, is biased. This\n%highlights how the lack of migration compensation biases complex amplitude\n%determination. The range-Doppler plot of the realistic signal is\n%displayed.\n% fc=1e9;%1GHz carrier frequency.\n% B=2e6;%2Mhz bandwidth.\n% %Baseband start and end frequencies.\n% fStart=-B/2;\n% fEnd=B/2;\n% %Sampling rate is two times the Nyquist rate.\n% T0=1/(2*2*fEnd);%Sampling period in seconds.\n% T=2e-5;%Chirp duration in seconds.\n% \n% PRF=2000;%Pulse repetition frequency (Hertz)\n% TB=1/PRF;%The pulse repetition period.\n% %The number of samples per PRI. The above parameters were chosen so that\n% %this is an integer. Fix just deals with finite precision errors.\n% Ns=fix(TB/T0);\n% \n% %Generate the reference signal. This is an up-chirp.\n% x=LFMChirp(T,fStart,fEnd,T0);\n% x=x(:);\n% \n% %We will use 64 pulse repetition intervals.\n% NB=64;\n% \n% %True target parameters\n% c=Constants.speedOfLight;\n% rTrue=512*c*T0;%Target placed on\n% tau=rTrue/c;%The true delay (s).\n% \n% %The true range rate (m/s).\n% rrTrue=6/NB*(c/(fc*TB));\n% a=rrTrue/c;\n% \n% %Allocate space for the received signal. The first dimensions is \"fast\n% %time\"; the second dimension if \"slow time\".\n% yReal=zeros(Ns,NB);\n% yIdeal=zeros(Ns,NB);\n% \n% %Create the received signal, properly delayed and Doppler shifted for\n% %each PRI. The same waveform is used in each PRI.\n% t=0:T0:((Ns-1)*T0);%Sample times\n% for i=0:(NB-1)\n% %The subtraction of i*TB deals with the start time of this pulse if\n% %it is not time zero.\n% tCur=t-a*t-tau-i*TB;\n% yReal(:,i+1)=512*exp(-1j*2*pi*fc*(tau+a*t)).*LFMChirp(T,fStart,fEnd,tCur);\n% \n% tCur=t-tau-i*TB;\n% yIdeal(:,i+1)=512*exp(-1j*2*pi*fc*(tau+a*i*TB)).*LFMChirp(T,fStart,fEnd,tCur);\n% \n% t=t+TB;%Increment to the next time step.\n% end\n% \n% M1=1;\n% M2=1;\n% %If desired, one could use a window in the Doppler domain. For example,\n% %by using wDoppler=windowFunSym(NB,'Blackman',1); Here, we choose to use\n% %no window (same as a rectangular window).\n% wDoppler=[];\n% valsReal=delayDopplerPlotNBPulseDop(x,yReal,M1,M2,wDoppler,T0);\n% [valsIdeal,Doppler,delay]=delayDopplerPlotNBPulseDop(x,yIdeal,M1,M2,wDoppler,T0);\n% \n% %Note that the amplitude of the ideal signal matches the true amplitude\n% %used, but that of the real signal (with range migration) is biased.\n% [magReal,idxReal]=max(abs(valsReal(:)));\n% [magIdeal,idxIdeal]=max(abs(valsIdeal(:)));\n% amplitudeMagReal=magReal\n% amplitudeMagIdeal=magIdeal\n% \n% range=c*delay;\n% rangeRate=Doppler*(c/fc);\n% \n% %We will make sure that the maximum point on the plots matches the true\n% %inputs, since the true inputs were made to align with range-Doppler cells.\n% [idxR,idxRR]=ind2sub(size(valsReal),idxReal);\n% rDiffReal=range(idxR)-rTrue\n% rrDiffReal=rangeRate(idxRR)-rrTrue\n% \n% [idxR,idxRR]=ind2sub(size(valsIdeal),idxIdeal);\n% rDiffIdeal=range(idxR)-rTrue\n% rrDiffIdeal=rangeRate(idxRR)-rrTrue\n% \n% figure(1)\n% clf\n% imagesc([rangeRate(1),rangeRate(end)],[range(1), range(end)]/1e3,10*log10(abs(valsReal)));\n% set(gca,'YDir','normal')\n% caxis([-30 27])\n% colormap(jet(256))\n% h1=xlabel('Range Rate (m/s)');\n% h2=ylabel('Range (km)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] S. K. Mitra, Digital Signal Processing: A Computer-Based Approach,\n% 3rd ed. Boston: McGraw Hill, 2006.\n%\n%November 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(M1))\n M1=1;\nend\n\nif(nargin<4||isempty(M2))\n M2=1; \nend\n\nNB=size(y,2);\nNs=size(y,1);\n\n%The extra circshift aligns the zero-Doppler point to the position assumed\n%in the delay output.\nrangePlots=circshift(circConv(flipud([conj(x);zeros(Ns-length(x),1)]),y,Ns),1);\n\nif(nargin>4&&~isempty(wDoppler))\n %Perform windowing to lower Doppler sidelobes.\n rangePlots=bsxfun(@times,wDoppler(:).',rangePlots);\nend\n\ndelayDopPlot=ifftshift(ifft(rangePlots,NB*M2,2),2);\n\n%Remove the scaling at the matched points so that we can get the true\n%complex amplitude back.\ndelayDopPlot=M1*M2*delayDopPlot/(x'*x);\n\nif(nargout>1)\n %T0 must be provided for these outputs.\n \n delay=(0:(T0/M1):((T0/M1)*(M1*Ns-1))).';\n %The pulse repetition interval.\n TB=Ns*T0;\n\n numNeg=(NB*M2-1)-ceil((NB*M2-1)/2)+1;\n Doppler=([(-numNeg):1:-1,0:(floor((NB*M2-1)/2)-1)].'/(NB*M2))*(1/TB);\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Signal_Processing/delayDopplerPlotNBPulseDop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7582478891561526}} {"text": "%DEMO_AUDIODENOISE Audio denoising using thresholding\n%\n% This demos shows how to do audio denoising using thresholding\n% of WMDCT transform.\n%\n% The signal is transformed using an orthonormal WMDCT transform\n% followed by a thresholding. Then the signal is reconstructed\n% and compared with the original.\n%\n% .. figure::\n%\n% Denoising\n%\n% The figure shows the original signal, the noisy signal and denoised\n% signals using hard and soft threshholding applied to the WMDCT of the\n% noise signal.\n%\n\n% Load audio signal\n% Use the 'glockenspiel' signal.\nsig=gspi;\n\nSigLength = 2^16;\nsig = sig(1:SigLength);\n\n% Initializations\nNbFreqBands = 1024;\nsigma = 0.5;\nRelative_Threshold = 0.1;\ntau = Relative_Threshold*sigma;\n\n% Generate window\ngamma = wilorth(NbFreqBands,SigLength);\n\n% add noise to the signal\nsigma = sigma * std(sig);\nnsig = sig + sigma * randn(size(sig));\n\n% Compute wmdct coefficients\nc = wmdct(nsig,gamma,NbFreqBands);\n\n% Hard Thresholding\nchard=thresh(c,tau);\n\n% Reconstruct\nhrec = real(iwmdct(chard,gamma));\n\n% Soft thresholding\ncsoft=thresh(c,tau,'soft');\n\n% Reconstruct\nsrec = real(iwmdct(csoft,gamma));\n\n% Plot\nfigure(1);\nsubplot(4,1,1); plot(sig); legend('Original');\nsubplot(4,1,2); plot(nsig); legend('Noisy');\nsubplot(4,1,3); plot(hrec); legend('Hard threshold');\nsubplot(4,1,4); plot(srec); legend('Soft threshold');\n\n% Results\nInputSNR = 20 *log10(std(sig)/std(nsig-sig));\nOutputSNR_h = 20 *log10(std(sig)/std(hrec-sig));\nOutputSNR_s = 20 *log10(std(sig)/std(srec-sig));\n\nfprintf(' RESULTS:\\n');\nfprintf(' Input SNR: %f dB.\\n',InputSNR);\nfprintf(' Output SNR (hard): %f dB.\\n',OutputSNR_h);\nfprintf(' Output SNR (soft): %f dB.\\n',OutputSNR_s);\nfprintf(' Signals are stored in variables sig, nsig, hrec, srec\\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_audiodenoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7582478836591227}} {"text": "function pde = HodgeLaplacianEdata1\n%% HODGELAPLACIANEDATA1\n%\n% u = [cos(x), -sin(y)];\n% sigma = -div u = sin(x) + cos(y);\n% f = -grad div u + curl rot u = - Lap u;\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\npde.f = @f;\npde.u = @exactu;\npde.sigma = @exactsigma;\npde.gu = @exactu;\npde.gsigma = @exactsigma;\npde.gun = @gun;\npde.grotu = 0;\n\n function s = f(p)\n s = exactu(p);\n end\n\n function u = exactu(p)\n x = p(:,1); y = p(:,2);\n u = [cos(x), -sin(y)];\n end\n\n function s = exactsigma(p)\n x = p(:,1); y = p(:,2);\n s = sin(x) + cos(y); \n end\n\n function s = gun(p) % for unit square [0,1]^2\n s = zeros(size(p,1),1);\n x = p(:,1); y = p(:,2);\n u = exactu(p);\n leftbd = (abs(x)P2->P3 turns Counter-Clockwise (i.e., the point P3\n% is located \"on the left\" of the line P1-P2)\n% -1 if the path turns Clockwise (i.e., the point P3 lies \"on the right\"\n% of the line P1-P2) \n% 0 if the point P3 is located on the line segment [P1 P2].\n%\n% This function can be used in more complicated algorithms: detection of\n% line segment intersections, convex hulls, point in triangle...\n%\n% CCW = isCounterClockwise(P1, P2, P3, EPS);\n% Specifies the threshold used for detecting colinearity of the 3 points.\n% Default value is 1e-12 (absolute).\n%\n% Example\n% isCounterClockwise([0 0], [10 0], [10 10])\n% ans = \n% 1\n% isCounterClockwise([0 0], [0 10], [10 10])\n% ans = \n% -1\n% isCounterClockwise([0 0], [10 0], [5 0])\n% ans = \n% 0\n%\n% See also \n% points2d, isPointOnLine, isPointInTriangle, polygonArea\n%\n% References\n% Algorithm adapated from Sedgewick's book.\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2010-04-09\n% Copyright 2010-2022 INRAE - Cepia Software Platform\n\n% get threshold value\neps = 1e-12;\nif ~isempty(varargin)\n eps = varargin{1};\nend\n\n% ensure all data have same size\nnp = max([size(p1, 1) size(p2, 1) size(p3,1)]);\nif np > 1\n if size(p1,1) == 1\n p1 = repmat(p1, np, 1);\n end\n if size(p2,1) == 1\n p2 = repmat(p2, np, 1);\n end\n if size(p3,1) == 1\n p3 = repmat(p3, np, 1);\n end \nend\n\n% init with 0\nres = zeros(np, 1);\n\n% extract vector coordinates\nx0 = p1(:, 1);\ny0 = p1(:, 2);\ndx1 = p2(:, 1) - x0;\ndy1 = p2(:, 2) - y0;\ndx2 = p3(:, 1) - x0;\ndy2 = p3(:, 2) - y0;\n\n% check non colinear cases\nres(dx1 .* dy2 > dy1 .* dx2) = 1;\nres(dx1 .* dy2 < dy1 .* dx2) = -1;\n\n% case of colinear points\nind = abs(dx1 .* dy2 - dy1 .* dx2) < eps;\nres(ind( (dx1(ind) .* dx2(ind) < 0) | (dy1(ind) .* dy2(ind) < 0) )) = -1;\nres(ind( hypot(dx1(ind), dy1(ind)) < hypot(dx2(ind), dy2(ind)) )) = 1;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/isCounterClockwise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.758177073907009}} {"text": "function mean = hypergeometric_mean ( n, m, l )\n\n%*****************************************************************************80\n%\n%% HYPERGEOMETRIC_MEAN returns the mean of the Hypergeometric PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of balls selected.\n% 0 <= N <= L.\n%\n% Input, integer M, the number of white balls in the population.\n% 0 <= M <= L.\n%\n% Input, integer L, the number of balls to select from.\n% 0 <= L.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = n * m / l;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/hypergeometric_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7581770680817654}} {"text": "%====================================================%\n%===========ECEN 5793: DIP===========================%\n%===========PROJECT 1================================%\n%====================================================%\nfunction A3 = imageresize(B3,p,m)\n% Zoom or shrink a image\n% Input:image B3: gray-image or RGB image\n% p: ratio, zooming (p>1), shrink(p<1)\n% m: mode; =0:(default) nearest neighbor interpolation \n% =1: Bilinear interpolation\n% =2: Bicubic interpolation\n% Output: image A3\n% @Trung Duong, trungd@okstate.edu\n% Jan 25, 2009\n%====================================================%\n% Input checking and default values\nerror(nargchk(2, 3, nargin, 'struct'));\nif nargin < 3, m = 0; end\n\ndimB = length(size(B3));\nif dimB== 2 % GRAY-IMAGE INPUT:\n A3 = gray_resize(B3,p,m); \nelseif dimB== 3 % COLOR RGB-IMAGE INPUT:\n AR = gray_resize(B3(:,:,1),p,m);\n AG = gray_resize(B3(:,:,2),p,m);\n AB = gray_resize(B3(:,:,3),p,m);\n A3 = zeros([size(AR) 3]);\n A3(:,:,1) = AR;\n A3(:,:,2) = AG;\n A3(:,:,3) = AB;\nelse\n error('Improper input image');\nend\n \n%**************************************************%\n%==================================================%\n% Sub-Function: Resize a gray-image\n% Same input argument with imageresize()\nfunction A = gray_resize(B,p,m)\n% Initialize new-grid and output\n[N,M] = size(B);\nxp = 1:1/p:N+1/p; yp = 1:1/p:M+1/p;\nA = zeros(length(xp),length(yp));\n% Symmetric Padding\nnpad = 3;\nB = sym_pad(B,npad);\nswitch m\n case 0 % Nearest neighbor interpolation\n U = round(xp); V = round(yp);\n U(find(U<1)) = 1; V(find(V<1)) = 1; \n U(find(U>N)) = N; V(find(V>M)) = M; \n A = B(U+npad,V+npad);\n case 1 % Bilinear interpolation\n % Floor of (xp,yp)\n xf = floor(xp); yf = floor(yp);\n % Distance to top-left neighbors \n [XF,YF] = ndgrid(xf,yf);\n [XP,YP] = ndgrid(xp,yp); \n u = XP - XF; v = YP - YF; \n % Change xf, yf for new padding image\n xf = xf + npad; yf = yf + npad;\n % Interpolation\n A = (1-u).*(1-v).*B(xf,yf) + ...\n (1-u).*v .*B(xf,yf+1) + ...\n u .*(1-v) .*B(xf+1,yf) + ...\n u .*v .*B(xf+1,yf+1); \n case 2\n % Floor of (xp,yp)\n xf = floor(xp);yf = floor(yp);\n % Distance to top-left neighbors \n [XF,YF] = ndgrid(xf,yf);\n [XP,YP] = ndgrid(xp,yp);\n u = XP - XF; v = YP - YF; \n % Change xf, yf for new padding image\n xf = xf + npad; yf = yf + npad;\n % Interpolation: 16 neighbors\n for i = -1:2\n for j = -1:2\n if i==-1, sgi = -1; else sgi = 1; end\n if j==-1, sgj = -1; else sgj = 1; end \n A = A + mex_hat(sgi*(i-u)).*mex_hat(sgj*(j-v)).*B(xf+i,yf+j);\n end\n end \n otherwise\n error('Undefined Interpolation method');\nend\n%**************************************************%\n%==================================================%\n% Sub-Function: Mexican-hat kernel\nfunction hx = mex_hat(x)\n hx = zeros(size(x));\n x = abs(x);\n ind1 = find(x<=1); ind2 = find(x>1 & x<=2);\n\n hx(ind1) = 1 - 2*x(ind1).^2 + x(ind1).^3;\n hx(ind2) = 4 - 8*x(ind2) + 5*x(ind2).^2 - x(ind2).^3;\n% END of sub-function\n%==================================================%\n% Sub-Function: symmetric padding, by default 2 pixels\n% Input: gray image\nfunction Bp = sym_pad(B,n)\n Bp = zeros(size(B)+2*n);\n Bp(n+1:end-n,n+1:end-n) = B;\n % Padding symmetrically 4 boundaries\n Bp(n:-1:1,n+1:end-n) = B(1:n,:);\n Bp(n+1:end-n,n:-1:1) = B(:,1:n);\n Bp(end-n+1:end,n+1:end-n) = B(end:-1:end-n+1,:);\n Bp(n+1:end-n,end-n+1:end) = B(:,end:-1:end-n+1);\n% END of sub-function\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/23967-simple-image-resize/imageresize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7581770658082605}} {"text": "function x2 = dfrnt ( xx, npl )\n\n%*****************************************************************************80\n%\n%% DFRNT determines the derivative of a Chebyshev series.\n%\n% Discussion:\n%\n% This routine computes the Chebyshev series of the derivative of a \n% function whose Chebyshev series is given.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Roger Broucke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Roger Broucke,\n% Algorithm 446:\n% Ten Subroutines for the Manipulation of Chebyshev Series,\n% Communications of the ACM,\n% October 1973, Volume 16, Number 4, pages 254-256.\n%\n% Parameters:\n%\n% Input, real XX(NPL), the given Chebyshev series.\n%\n% Input, integer NPL, the number of terms in the \n% Chebyshev series.\n%\n% Output, real X2(NPL), the Chebyshev series for the\n% derivative.\n%\n x2 = zeros ( npl, 1 );\n\n n = npl - 1;\n xxn = xx(npl-1);\n x2(npl-1) = 2.0 * xx(npl) * n;\n x2(npl) = 0.0;\n\n for k = 3 : npl\n l = npl - k + 1;\n xxl = xx(l);\n x2(l) = x2(l+2) + 2.0 * xxn * l;\n xxn = xxl;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms446/dfrnt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.7580890754836556}} {"text": "%% demo.m\n%\n% Shows a couple of sample registrations using \n% ICP - Iterative Closest Point\n%\n% Jakob Wilm and Martin Kjer, Technical University of Denmark, 2012\n\naddpath('../../Utils');\n\nm = 80; % width of grid\nn = m^2; % number of points\n\n[X,Y] = meshgrid(linspace(-2,2,m), linspace(-2,2,m));\nX = reshape(X,1,[]);\nY = reshape(Y,1,[]);\nZ = sin(X).*cos(Y);\n\n\n% Create the data point-matrix\nD = [X; Y; Z];\n\n% Translation values (a.u.):\nTx = 0.5;\nTy = -0.3;\nTz = 0.2;\n\n% Translation vector\nT = [Tx; Ty; Tz];\n\n% Rotation values (rad.):\nrx = 0.3;\nry = -0.2;\nrz = 0.05;\n\nRx = [1 0 0;\n 0 cos(rx) -sin(rx);\n 0 sin(rx) cos(rx)];\n \nRy = [cos(ry) 0 sin(ry);\n 0 1 0;\n -sin(ry) 0 cos(ry)];\n \nRz = [cos(rz) -sin(rz) 0;\n sin(rz) cos(rz) 0;\n 0 0 1];\n\n% Rotation matrix\nR = Rx*Ry*Rz;\n\n% Transform data-matrix plus noise into model-matrix \nM = R * D + repmat(T, 1, n);\n\n% Add noise to model and data\nrng(2912673);\nM = M + 0.01*randn(3,n);\nD = D + 0.01*randn(3,n);\n\n%% Run ICP (standard settings)\n[Ricp Ticp ER t] = icp(M, D, 15);\n\n% Transform data-matrix using ICP result\nDicp = Ricp * D + repmat(Ticp, 1, n);\n\n% Plot model points blue and transformed points red\nfigure;\nsubplot(2,2,1);\nplot3(M(1,:),M(2,:),M(3,:),'bo',D(1,:),D(2,:),D(3,:),'r.');\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('Red: z=sin(x)*cos(y), blue: transformed point cloud');\n\n% Plot the results\nsubplot(2,2,2);\nplot3(M(1,:),M(2,:),M(3,:),'bo',Dicp(1,:),Dicp(2,:),Dicp(3,:),'r.');\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('ICP result');\n\n% Plot RMS curve\nsubplot(2,2,[3 4]);\nplot(0:15,ER,'--x');\nxlabel('iteration#');\nylabel('d_{RMS}');\nlegend('bruteForce matching');\ntitle(['Total elapsed time: ' num2str(t(end),2) ' s']);\n\n%% Run ICP (fast kDtree matching and extrapolation)\n[Ricp Ticp ER t] = icp(M, D, 15, 'Matching', 'kDtree', 'Extrapolation', true);\n\n% Transform data-matrix using ICP result\nDicp = Ricp * D + repmat(Ticp, 1, n);\n\n% Plot model points blue and transformed points red\nfigure;\nsubplot(2,2,1);\nplot3(M(1,:),M(2,:),M(3,:),'bo',D(1,:),D(2,:),D(3,:),'r.');\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('Red: z=sin(x)*cos(y), blue: transformed point cloud');\n\n% Plot the results\nsubplot(2,2,2);\nplot3(M(1,:),M(2,:),M(3,:),'bo',Dicp(1,:),Dicp(2,:),Dicp(3,:),'r.');\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('ICP result');\n\n% Plot RMS curve\nsubplot(2,2,[3 4]);\nplot(0:15,ER,'--x');\nxlabel('iteration#');\nylabel('d_{RMS}');\nlegend('kDtree matching and extrapolation');\ntitle(['Total elapsed time: ' num2str(t(end),2) ' s']);\n\n%% Run ICP (partial data)\n\n% Partial model point cloud\nMp = M(:,Y>=0);\n\n% Boundary of partial model point cloud\nb = (abs(X(Y>=0)) == 2) | (Y(Y>=0) == min(Y(Y>=0))) | (Y(Y>=0) == max(Y(Y>=0)));\nbound = find(b);\n\n% Partial data point cloud\nDp = D(:,X>=0);\n\n[Ricp Ticp ER t] = icp(Mp, Dp, 50, 'EdgeRejection', true, 'Boundary', bound, 'Matching', 'kDtree');\n\n% Transform data-matrix using ICP result\nDicp = Ricp * Dp + repmat(Ticp, 1, size(Dp,2));\n\n% Plot model points blue and transformed points red\nfigure;\nsubplot(2,2,1);\nplot3(Mp(1,not(b)),Mp(2,not(b)),Mp(3,not(b)),'bo',...\n Mp(1,b),Mp(2,b),Mp(3,b),'go',...\n Dp(1,:),Dp(2,:),Dp(3,:),'r.')\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('Red: z=sin(x)*cos(y), blue: transformed point cloud');\n\n% Plot the results\nsubplot(2,2,2);\nplot3(Mp(1,not(b)),Mp(2,not(b)),Mp(3,not(b)),'bo',...\n Mp(1,b),Mp(2,b),Mp(3,b),'go',...\n Dicp(1,:),Dicp(2,:),Dicp(3,:),'r.');\naxis equal;\nxlabel('x'); ylabel('y'); zlabel('z');\ntitle('ICP result');\n\n% Plot RMS curve\nsubplot(2,2,[3 4]);\nplot(0:50,ER,'--x');\nxlabel('iteration#');\nylabel('d_{RMS}');\nlegend('partial overlap');\ntitle(['Total elapsed time: ' num2str(t(end),2) ' s']);", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/utils/icp/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7580890674154278}} {"text": "function value = r8_log_10 ( x )\n\n%*****************************************************************************80\n%\n%% R8_LOG_10 returns the logarithm base 10 of |X|.\n%\n% Discussion:\n%\n% value = Log10 ( |X| )\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, real X, the number whose base 2 logarithm is desired.\n% X should not be 0.\n%\n% Output, real VALUE, the logarithm base 10 of the absolute\n% value of X. It should be true that |X| = 10**R8_LOG_10.\n%\n if ( x == 0.0 )\n value = -inf;\n else\n value = log10 ( abs ( 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/subpak/r8_log_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7580890610787626}} {"text": "function plane = fit_depth_plane(x_hom, depth)\n%FIT_DEPTH_PLANE Least squares fitting of a plane in the 3D scene projected on\n%the image from a set of input points.\n%\n% INPUTS:\n%\n% -|x_hom|: |P|-by-3 matrix holding homogeneous image-plane coordinates of\n% input points.\n%\n% -|depth|: |P|-by-1 vector holding depth values of input points.\n%\n% OUTPUTS:\n%\n% -|plane|: 3-by-1 vector holding the parameters of the fitted plane, so that\n% for each point [x, y, d] it holds d = [x, y, 1] * plane.\n\nx_hom_T = x_hom.';\nplane = (x_hom_T * x_hom) \\ (x_hom_T * depth);\n\nend\n\n", "meta": {"author": "sakaridis", "repo": "fog_simulation-SFSU_synthetic", "sha": "8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3", "save_path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic", "path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic/fog_simulation-SFSU_synthetic-8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3/source/Depth_processing/fit_depth_plane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7580786221265187}} {"text": "function [X meaneffective sigmaeffective] = TruncatedGaussian(sigma, range, varargin)\n% function X = TruncatedGaussian(sigma, range)\n% X = TruncatedGaussian(sigma, range, n)\n%\n% Purpose: generate a pseudo-random vector X of size n, X are drawn from\n% the truncated Gaussian distribution in a RANGE braket; and satisfies\n% std(X)=sigma.\n% RANGE is of the form [left,right] defining the braket where X belongs.\n% For a scalar input RANGE, the braket is [-RANGE,RANGE].\n%\n% X = TruncatedGaussian(..., 'double') or\n% X = TruncatedGaussian(..., 'single') return an array X of of the\n% specified class.\n%\n% If input SIGMA is negative, X will be forced to have the same \"shape\" of\n% distribution function than the unbounded Gaussian with standard deviation\n% -SIGMA: N(0,-SIGMA). It is similar to calling RANDN and throw away values\n% ouside RANGE. In this case, the standard deviation of the truncated\n% Gaussian will be different than -SIGMA. The *effective* mean and\n% the effective standard deviation can be obtained by calling:\n% [X meaneffective sigmaeffective] = TruncatedGaussian(...)\n%\n% Example:\n% \n% sigma=2;\n% range=[-3 5]\n% \n% [X meaneff sigmaeff] = TruncatedGaussian(sigma, range, [1 1e6]);\n% \n% stdX=std(X);\n% fprintf('mean(X)=%g, estimated=%g\\n',meaneff, mean(X))\n% fprintf('sigma=%g, effective=%g, estimated=%g\\n', sigma, sigmaeff, stdX)\n% hist(X,64)\n%\n% Author: Bruno Luong \n% Last update: 19/April/2009\n\n% We keep track this variables so as to avoid calling fzero if\n% TruncatedGaussian is called succesively with the same sigma and range\npersistent PREVSIGMA PREVRANGE PREVSIGMAC\n\n% shape preserving?\nshapeflag = (sigma<0);\n\n% Force inputs to be double class\nrange = double(range);\nif isscalar(range)\n % make sure it's positive\n range=abs(range);\n range=[-range range];\nelse\n range=sort(range); % right order\nend\nsigma = abs(double(sigma));\n\nn=varargin;\n\nif shapeflag\n % Prevent the same pdf as with the normal distribution N(0,sigma)\n sigmac = sigma;\nelse\n if diff(range)^2<12*sigma^2 % This imposes a limit of sigma wrt range\n warning('TruncatedGaussian:RangeSigmaIncompatible', ...\n 'TruncatedGaussian: range and sigma are incompatible\\n');\n sigmac = Inf;\n elseif isequal([sigma range], [PREVSIGMA PREVRANGE]) % See line #80\n sigmac = PREVSIGMAC; % Do not need to call fzero\n else\n % Search for \"sigmac\" such that the truncated Gaussian having\n % sigmac in the formula of its pdf gives a standard deviation\n % equal to sigma\n [sigmac res flag] = fzero(@scz,sigma,[],...\n sigma^2,range(1),range(2));\n sigmac = abs(sigmac); % Force it to be positive\n if flag<0 % Someting is wrong\n error('TruncatedGaussian:fzerofailled', ...\n 'Could not estimate sigmac\\n');\n end\n % Backup the solution\n [PREVSIGMA PREVRANGE PREVSIGMAC] = deal(sigma,range,sigmac);\n end\nend\n\n% Compute effective standard deviation\nmeaneffective=meantrunc(range(1), range(2), sigmac);\nsigmaeffective=stdtrunc(range(1), range(2), sigmac);\n\n% Inverse of the cdf functions\nif isinf(sigmac)\n % Uniform distribution to maximize the standard deviation within the\n % range. It is like a Gaussian with infinity standard deviation\n if any(strcmpi(n,'single'))\n range = single(range);\n end\n cdfinv = @(y) range(1)+y*diff(range);\nelse\n c = sqrt(2)*sigmac;\n e = erf(range/c);\n if any(strcmpi(n,'single'))\n % cdfinv will be single class\n c = single(c);\n e = single(e);\n end\n cdfinv = @(y) c*erfinv(e(1)+diff(e)*y);\nend\n\n% Generate random variable\nX = cdfinv(rand(n{:}));\n% Clip to prevent some nasty numerical issues with of erfinv function\n% when argument gets close to +/-1\nX = max(min(X,range(2)),range(1));\n\nreturn\n\nend % TruncatedGaussian\n\nfunction m=meantrunc(lower, upper, s)\n% Compute the mean of a trunctated gaussian distribution\nif isinf(s)\n m = (upper+lower)/2;\nelse\n a = (lower/sqrt(2))./s;\n b = (upper/sqrt(2))./s;\n corr = sqrt(2/pi)*(-exp(-b.^2)+exp(-a.^2))./(erf(b)-erf(a));\n m = s.*corr;\nend\nend % vartrunc\n\nfunction v=vartrunc(lower, upper, s)\n% Compute the variance of a trunctated gaussian distribution\nif isinf(s)\n v = (upper-lower)^2/12;\nelse\n a = (lower/sqrt(2))./s;\n b = (upper/sqrt(2))./s;\n if isinf(a)\n ea=0;\n else\n ea = a.*exp(-a.^2);\n end\n if isinf(b)\n eb = 0;\n else\n eb = b.*exp(-b.^2);\n end\n corr = 1 - (2/sqrt(pi))*(eb-ea)./(erf(b)-erf(a));\n v = s.^2.*corr;\nend\nend % vartrunc\n\nfunction stdt=stdtrunc(lower, upper, s)\n% Standard deviation of a trunctated gaussian distribution\nstdt = sqrt(vartrunc(lower, upper, s)-meantrunc(lower, upper, s).^2);\nend % stdtrunc\n\nfunction res=scz(sc, targetsigma2, lower, upper)\n% Gateway for fzero, aim the standard deviation to a target value\nres = vartrunc(lower, upper, sc) - targetsigma2 - ...\n meantrunc(lower, upper, sc).^2;\nend % scz\n\n% End of file TruncatedGaussian.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/lagextraction/data/synth/TruncatedGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.758044425346648}} {"text": "function node_xyz = sphere_grid_q16_node_xyz ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% SPHERE_GRID_Q16_NODE_XYZ produces node coordinates for a Q16 sphere grid.\n%\n% Discussion:\n%\n% The number of nodes to be generated is\n%\n% NODE_NUM = 9 * NELEMX * NELEMY - 3 * NELEMX + 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 September 2006\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.\n%\n% Output, real NODE_XYZ(3,NODE_NUM), the node coordinates.\n%\n node = 0;\n\n for j = 3 * nelemy + 1 : -1 : 1\n\n phi = ( j - 1 ) * pi / ( 3 * nelemy );\n\n if ( j == 1 )\n\n node = node + 1;\n node_xyz(1,node) = 0.0;\n node_xyz(2,node) = 0.0;\n node_xyz(3,node) = 1.0;\n\n elseif ( j < 3 * nelemy + 1 )\n\n for i = 1 : 3 * nelemx\n\n theta = ( i - 1 ) * 2.0 * pi / ( 3 * nelemx );\n\n node = node + 1; \n node_xyz(1,node) = cos ( theta ) * sin ( phi );\n node_xyz(2,node) = sin ( theta ) * sin ( phi );\n node_xyz(3,node) = cos ( phi );\n\n end\n\n elseif ( j == 3 * nelemy + 1 )\n\n node = node + 1;\n node_xyz(1,node) = 0.0;\n node_xyz(2,node) = 0.0;\n node_xyz(3,node) = -1.0;\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/sphere_grid_q16_node_xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7580444204784982}} {"text": "% Figure 3.32 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n% script to generate Fig. 3.32\n% Pole-zero effects\n%\nclose all;\nclear all;\nDen1=[1 0.2 1.01];\nDen2=[1 1.0];\nDen11=conv(Den1,Den2);\nalpha=0.1;\nbeta=1.0;\nNum1=(1.01*1.0/(alpha^2+beta^2))*([1 2*alpha alpha^2+beta^2]);\n\nt=0:.1:20;\nsys=tf(Num1,Den11);\n[y1]=step(sys,t)\n\nDen1=[1 0.2 1.01];\nDen2=[1 1.0];\nDen22=conv(Den1,Den2);\n% alpha=1;\nalpha1=0.25;\nbeta=1.0;\nNum2=(1.01*1.0/(alpha1^2+beta^2))*([1 2*alpha1 alpha1^2+beta^2]);\n\nt=0:.1:20;\nsys2=tf(Num2,Den22);\n[y2]=step(sys2,t)\n\nDen1=[1 0.2 1.01];\nDen2=[1 1.0];\nDen33=conv(Den1,Den2);\nalpha2=0.5;\nbeta=1.0;\nNum3=(1.01*1.0/(alpha2^2+beta^2))*([1 2*alpha2 alpha2^2+beta^2]);\n\nt=0:.1:20;\nsys2=tf(Num3,Den33);\n[y3]=step(sys2,t)\nplot(t,y1,t,y2,t,y3);\nxlabel('Time (sec)');\nylabel('Unit step response');\ntext(2, 1.36, '\\alpha = 0.5');\ntext(2,1.14,'\\alpha = 0.25');\ntext(2,0.8,'\\alpha = 0.1');\ntitle('Fig. 3.32: Step responses');\n%%%%%%%%%%%%%%%%%%%%%\n\n%grid\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig3_32.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7580444186201627}} {"text": "function [ c1, c2, c3, r1, r2, r3 ] = year_to_scaliger_common ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_TO_SCALIGER_COMMON converts a Common year to its Scaliger indices.\n%\n% Discussion:\n%\n% The year 4713 BCE was chosen by Joseph Scaliger for the start of\n% his Julian Ephemeris Date system, because three cycles coincided\n% in that year, the 28 year Julian calendar cycle, the 19 year Metonic\n% cycle, and the 15 year Roman Indiction cycle. Thus, the year\n% 4713 BCE has Scaliger index (1,1,1). Each subsequent year has a distinct\n% set of Scaliger indices until 7980 years later, when the year\n% 3266 CE will again have the Scaliger index (1,1,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, the Common year.\n%\n% Output, integer C1, C2, C3, the number of completed\n% Julian, Metonic and Indiction cycles.\n%\n% Output, integer R1, R2, R3, the Julian, Metonic and\n% Indiction cycle numbers that make up the Scaliger index.\n%\n if ( y == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'YEAR_TO_SCALIGER_COMMON - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input Y = 0.\\n' );\n error ( 'YEAR_TO_SCALIGER_COMMON - Fatal error!' );\n end\n%\n% Adjust for missing year 0.\n%\n if ( y < 0 )\n y2 = y + 1;\n else\n y2 = y;\n end\n%\n% Now shift so 4713 BC becomes the year 1.\n%\n y2 = y2 + 4713;\n\n c1 = floor ( ( y2 - 1 ) / 28 );\n c2 = floor ( ( y2 - 1 ) / 19 );\n c3 = floor ( ( y2 - 1 ) / 15 );\n\n r1 = i4_wrap ( y2, 1, 28 );\n r2 = i4_wrap ( y2, 1, 19 );\n r3 = i4_wrap ( y2, 1, 15 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calpak/year_to_scaliger_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7580136842541514}} {"text": "function [ n_data_new, x, fx ] = gud_values ( n_data )\n\n%*****************************************************************************80\n%\n%% GUD_VALUES returns some values of the Gudermannian function.\n%\n% Definition:\n%\n% The Gudermannian function relates the hyperbolic and trigonomentric\n% functions. For any argument X, there is a corresponding value\n% GAMMA so that\n%\n% SINH(X) = TAN(GAMMA).\n%\n% This value GAMMA(X) is called the Gudermannian of X and symbolized\n% GD(X). The inverse Gudermannian function is given as input a value\n% GAMMA and computes the corresponding value X.\n%\n% GD(X) = 2 * arctan ( exp ( X ) ) - PI / 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 May 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% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, integer N_DATA, indicates the index of the previous test data\n% returned, or is 0 if this is the first call. For repeated calls,\n% set the input value of N_DATA to the output value of N_DATA_NEW\n% from the previous call.\n%\n% Output, integer N_DATA_NEW, the index of the test data.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 13;\n fx_vec = [ ...\n -1.301760336E+00, -0.8657694832E+00, 0.0000000000E+00, ...\n 0.09983374879E+00, 0.1986798470E+00, 0.4803810791E+00, ...\n 0.8657694832E+00, 1.131728345E+00, 1.301760336E+00, ...\n 1.406993569E+00, 1.471304341E+00, 1.510419908E+00, ...\n 1.534169144E+00 ];\n x_vec = [ ...\n -2.0E+00, -1.0E+00, 0.0E+00, ...\n 0.1E+00, 0.2E+00, 0.5E+00, ...\n 1.0E+00, 1.5E+00, 2.0E+00, ...\n 2.5E+00, 3.0E+00, 3.5E+00, ...\n 4.0E+00 ];\n\n n_data_new = n_data;\n\n if ( n_data_new < 0 )\n n_data_new = 0;\n end\n\n n_data_new = n_data_new + 1;\n\n if ( n_max < n_data_new )\n n_data_new = 0;\n x = 0.0E+00;\n fx = 0.0E+00;\n else\n x = x_vec(n_data_new);\n fx = fx_vec(n_data_new);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/gud_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7580136737285197}} {"text": "function [param]=zn3tak(input)\n% [param]=zn3pd(input)\n% Takahashi's controller for processes of 3rd order.\n% This function computes parameters of the controller (r0, q0, q1, q2, p1, p2).\n% Output of the controller is calculated follows:\n%\n% r0 q0 + q1*z^-1 + q2*z^-2 \n% U(z^-1) = ----------------------- * W(z^-1) - ------------------------ * Y(z^-1)\n% 1 + p1*z^-1 + p2*z^-2 1 + p1*z^-1 + p2*z^-2\n%\n% where p1=-1, p2=0\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2 + b3*z^-3\n% Gs(z^-1) = ---------------------------------\n% 1 + a1*z^-1 + a2*z^-2 + a3*z^-3\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... a3\n% input(6) ... b3\n% input(7) ... sample time T0\n% Output: param ... controller parameters \n% param(1) ... r0\n% param(2) ... q0\n% param(3) ... q1\n% param(4) ... q2 (0)\n% param(5) ... p1 (0)\n% param(6) ... p2 (0)\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\na3 = input(5);\nb3 = input(6);\nT0 = input(7);\n\n% compute ultimate gain and frequency\n[Kpu, Tu] = ultim([b1 b2 b3],[a1 a2 a3],T0);\n\nKp = 0.6*Kpu*(1-T0/Tu);\nTi = Kp*Tu/(1.2*Kpu);\nTd = 3*Kpu*Tu/(40*Kp);\n\nr0 = Kp*T0/Ti;\nq0 = Kp*(1+T0/Ti+Td/T0);\nq1 = -Kp*(1+2*Td/T0);\nq2 = Kp*(Td/T0);\np1 = -1;\np2 = 0;\n\nparam=[r0; q0; q1; q2; p1; 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/8381-stcsl-standard-version/zn3tak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7580135448141851}} {"text": "function value = i4_bit_reverse ( i, n )\n\n%*****************************************************************************80\n%\n%% I4_BIT_REVERSE reverses the bits in an I4.\n%\n% Discussion:\n%\n% An I4 is an integer value.\n%\n% Example:\n%\n% I N 2^N I4_BIT_REVERSE ( I, N )\n% ---- -------- -----------------------\n% 0 0 1 0\n% 1 0 1 1\n%\n% 0 3 8 0\n% 1 3 8 4\n% 2 3 8 2\n% 3 3 8 6\n% 4 3 8 1\n% 5 3 8 5\n% 6 3 8 3\n% 7 3 8 7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the integer to be bit reversed.\n% I should be nonnegative. Normally I < 2^N.\n%\n% Input, integer N, indicates the number of bits to\n% be reverse (N+1) or the base with respect to which the integer is to\n% be reversed (2^N). N should be nonnegative.\n%\n% Output, integer VALUE, the bit reversed value.\n%\n i = round ( i );\n n = round ( n );\n\n if ( i < 0 )\n\n value = -1;\n\n elseif ( n < 0 )\n\n value = -1;\n\n else\n\n b = 2^n;\n j = mod ( i, b );\n\n value = 0;\n\n while ( 1 )\n\n if ( b == 1 )\n\n value = value + j;\n j = 0;\n break\n\n else\n\n if ( mod ( j, 2 ) == 1 )\n value = value + floor ( b / 2 );\n j = j - 1;\n end\n\n j = floor ( j / 2 );\n b = floor ( b / 2 );\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/i4lib/i4_bit_reverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7579687113121706}} {"text": "function [p,s]=v_permutes(n)\n%V_PERMUTES All N! permutations of 1:N + signatures [P,S]=(N)\n% The output P is a matrix of size (N!,N) where each row\n% contains a permutation of the numbers 1:N. The rows are in \n% lexically sorted order.\n%\n% To permute the elements of an arbitrary vector V use\n% V(PERMUTES(LENGTH(V))).\n\n% PERMUTES(N) is the same as SORTROWS(PERMS(1:N)) but much faster.\n\n% Thanks to Peter J Acklam for several improvements.\n\n% Copyright (c) 1998 Mike Brookes, mike.brookes@ic.ac.uk\n% Version: $Id: v_permutes.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\np=1;\nm=1;\nif n>1\n for a=2:n\n q=zeros(a*m,a);\n r=2:a+1;\n ix=1:m;\n for b=1:a\n q(ix,1)=b;\n q(ix,2:a)=r(p);\n r(b)=b;\n ix=ix+m;\n end\n m=m*a;\n p=q;\n end\nend\nif nargout>1 s=1-2*rem(fix((1:m)'/2),2); end\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_permutes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7579687110294945}} {"text": "function y = USFT_simple(x,shift,boxlen,center,w)\n% USFT_simple -- 1d unequispaced Fourier transform\n% Usage:\n% y = USFT_simple(x,shift,boxlen,center,w)\n% Inputs:\n% x\t vector of length n\n% shift vector of shifts\n% boxlen half-length of the window associated with shift\n% center boolean variable\n% w window of size 2*boxlen\n% Outputs:\n% y vector le length 2n\n% Description:\n% Evaluates the FT at the points omega_(j,k) = shift(j) + k, \n% -boxlen <= k \n% * \n%\n\n%% Theory\n%\n% NOTE: The explanation below belongs to the book *Learning OpenCV* by\n% Bradski and Kaehler.\n%\n% We have previously seen applicative examples of convolutions. One of the\n% most important convolutions is the computation of derivatives in an image\n% (or an approximation to them). Why may be important the calculus of the\n% derivatives in an image? Let's imagine we want to detect the _edges_ present\n% in the image. For instance:\n%\n% <>\n%\n% You can easily notice that in an _edge_, the pixel intensity _changes_ in a\n% notorious way. A good way to express _changes_ is by using _derivatives_. A\n% high change in gradient indicates a major change in the image.\n%\n% To be more graphical, let's assume we have a 1D-image. An edge is shown by\n% the \"jump\" in intensity in the plot below:\n%\n% <>\n%\n% The edge \"jump\" can be seen more easily if we take the first derivative\n% (actually, here appears as a maximum)\n%\n% <>\n%\n% So, from the explanation above, we can deduce that a method to detect edges\n% in an image can be performed by locating pixel locations where the gradient\n% is higher than its neighbors (or to generalize, higher than a threshold).\n%\n%% Sobel Operator\n%\n% The Sobel Operator is a discrete differentiation operator. It computes an\n% approximation of the gradient of an image intensity function. The Sobel\n% Operator combines Gaussian smoothing and differentiation.\n%\n% Assuming that the image to be operated is $I$, we calculate two derivatives:\n%\n% * *Horizontal changes*: This is computed by convolving $I$ with a kernel\n% $G_{x}$ with odd size. For example for a kernel size of 3, $G_{x}$ would\n% be computed as:\n%\n% $$G_{x} = \\left[{\\matrix{\n% -1 & 0 & +1 \\cr\n% -2 & 0 & +2 \\cr\n% -1 & 0 & +1\n% }}\\right] * I$$\n%\n% * *Vertical changes*: This is computed by convolving $I$ with a kernel\n% $G_{y}$ with odd size. For example for a kernel size of 3, $G_{y}$ would\n% be computed as:\n%\n% $$G_{y} = \\left[{\\matrix{\n% -1 & -2 & -1 \\cr\n% 0 & 0 & 0 \\cr\n% +1 & +2 & +1\n% }}\\right] * I$$\n%\n% At each point of the image we calculate an approximation of the _gradient_\n% in that point by combining both results above:\n%\n% $$G = \\sqrt{ G_{x}^{2} + G_{y}^{2} }$$\n%\n% Although sometimes the following simpler equation is used:\n%\n% $$G = |G_{x}| + |G_{y}|$$\n%\n% Note: When the size of the kernel is |3|, the Sobel kernel shown above may\n% produce noticeable inaccuracies (after all, Sobel is only an approximation\n% of the derivative). OpenCV addresses this inaccuracy for kernels of size 3\n% by using the |cv.Scharr| function. This is as fast but more accurate than\n% the standard Sobel function. It implements the following kernels:\n%\n% $$G_{x} = \\left[{\\matrix{\n% -3 & 0 & +3 \\cr\n% -10 & 0 & +10 \\cr\n% -3 & 0 & +3\n% }}\\right]$$\n%\n% $$G_{y} = \\left[{\\matrix{\n% -3 & -10 & -3 \\cr\n% 0 & 0 & 0 \\cr\n% +3 & +10 & +3\n% }}\\right]$$\n%\n% Note: You can check out more information of this function in the OpenCV\n% reference (|cv.Scharr|). Also, in the sample code below, you will notice\n% that above the code for |cv.Sobel| function there is also code for the\n% |cv.Scharr| function commented. Enabling it should give you an idea of how\n% this function works.\n%\n\n%% Code\n%\n% The program below applies the _Sobel Operator_ and generates as output an\n% image with the detected _edges_ bright on a darker background.\n%\n\n%%\n% load source image\nsrc = cv.imread(fullfile(mexopencv.root(),'test','lena.jpg'), 'Color',true);\n\n%%\n% apply a Gaussian blur to reduce the noise\nsrc = cv.GaussianBlur(src, 'KSize',[3 3]);\n\n%%\n% convert filtered image to grayscale\ngray = cv.cvtColor(src, 'RGB2GRAY');\n\n%%\n% calculate the derivatives in x and y directions\n% (input is 8-bit, we set the output image depth to 16-bit to avoid overflow)\nif true\n gradx = cv.Sobel(gray, 'XOrder',1, 'YOrder',0, 'DDepth','int16');\n grady = cv.Sobel(gray, 'XOrder',0, 'YOrder',1, 'DDepth','int16');\nelse\n gradx = cv.Scharr(gray, 'XOrder',1, 'YOrder',0, 'DDepth','int16');\n grady = cv.Scharr(gray, 'XOrder',0, 'YOrder',1, 'DDepth','int16');\nend\n\n%%\n% take absolute value and convert our partial results back to 8-bit\ngradxabs = cv.convertScaleAbs(gradx);\ngradyabs = cv.convertScaleAbs(grady);\n\n%%\n% approximate the gradient by adding both directional gradients\n% (this is not an exact calculation, but it is good for our purposes)\ngrad = cv.addWeighted(gradxabs,0.5, gradyabs,0.5, 0.0);\n\n%%\n% show result\nimshow(grad)\ntitle('Sobel Demo - Simple Edge Detector')\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/sobel_derivatives_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7579187545771722}} {"text": "function bratubvp\n%BRATUBVP Exercise for Example 1 of the BVP tutorial.\n% The BVP y'' + exp(y) = 0, y(0) = 0 = y(1) is a standard example\n% of a problem with two solutions. It is easy enough to solve, but\n% some experimentation with the guess may be necessary to get both.\n\n% Copyright 2002, The MathWorks, Inc.\n\noptions = bvpset('stats','on');\nsolinit = bvpinit(linspace(0,1,5),[0.1 0]);\nsol1 = bvp4c(@bratuode,@bratubc,solinit,options);\n\nfprintf('\\n');\n\n% Change the initial guess to converge to a different solution. \nsolinit = bvpinit(linspace(0,1,5),[3 0]);\nsol2 = bvp4c(@bratuode,@bratubc,solinit,options);\n\nfigure\nplot(sol1.x,sol1.y(1,:),sol2.x,sol2.y(1,:))\ntitle('Bratu''s equation has two solutions when \\lambda = 1.')\nxlabel('x')\nylabel('y')\n\n% --------------------------------------------------------------------------\n\nfunction dydx = bratuode(x,y)\n%BRATUODE ODE function for the exercise of Example 1 of the BVP tutorial.\ndydx = [ y(2)\n -exp(y(1))];\n\n% --------------------------------------------------------------------------\n\nfunction res = bratubc(ya,yb)\n%BRATUBC Boundary conditions for the exercise of Example 1 of the BVP tutorial.\nres = [ya(1)\n yb(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/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples_65/bratubvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.757856212527243}} {"text": "%VL_NNBNORM CNN batch normalisation.\n% Y = VL_NNBNORM(X,G,B) applies batch normalization to the input\n% X. Batch normalization 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% sigma2(k) = mean_ijt (X(i,j,k,t) - mu(k))^2,\n% sigma(k) = sqrt(sigma2(k) + EPSILON)\n%\n% are respectively the per-channel mean, variance, and standard\n% deviation of each feature channel in the data X. The parameters\n% G(k) and B(k) are multiplicative and additive constants use to\n% scale each data channel.\n%\n% Means and variances are accumulated across all the data items\n% (images) stored in the 4D tensor X (from which the name batch\n% normalization is derived). The constant EPSILON is used to \n% regularize the computation of sigma(k) and to avoid division by \n% zero.\n%\n% [DZDX,DZDG,DZDB] = VL_NNBNORM(X,G,B,DZDY) computes the derviatives\n% of the block projected onto DZDY. DZDX, DZDG, DZDB and DZDY have\n% the same dimensions as X, G, B, and Y respectivey.\n%\n% Optionally, [Y,MOMENTS] = VL_NNBNORM(...) and\n% [DZDX,DZDG,DZDB,MOMENTS] = VL_NNBNORM(...,DZDY) return the values\n% of the vectors mu and sigma in the formulas above. Here, MOMENTS\n% is a DEPTH x 2 array [MU, SIGMA].\n%\n% VL_NNBNROM(..., 'Option', value) takes the following options:\n%\n% `Epsilon`:: 1e-4\n% Specifies the constant EPSILON in the formuals above.\n%\n% `Moments`:: unspecified\n% Specifies an array MOMENTS with the values of mu and sigma to\n% use instead of computing them according to the equations\n% above. This is useful to disable batch normalization during\n% testing.\n%\n% See also: VL_NNNORMALIZE().\n\n% Copyright (C) 2015 Sébastien Ehrhardt, 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", "meta": {"author": "jiangqy", "repo": "DCMH-CVPR2017", "sha": "67d0e84c0425fdac3fad30d67d5a2beb5e345cea", "save_path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017", "path": "github-repos/MATLAB/jiangqy-DCMH-CVPR2017/DCMH-CVPR2017-67d0e84c0425fdac3fad30d67d5a2beb5e345cea/DCMH_matlab/DCMH_matlab/matconvnet/matlab/vl_nnbnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7577533508334271}} {"text": "function [I, J] = ind2sub4up(IND)\n%IND2SUB4UP Subscripts from linear index for upper triangular matrix (only\n%elements above diagonal)\n% IND2SUB4UP determines the equivalent subscript values corresponding to\n% a given single index into a 2D upper triangular matrix, excluded all\n% elements over the diagonal.\n%\n% [I, J] = IND2SUB4UP(IND) returns vectors I and J containing equivalent\n% row and column subscripts corresponding to the index vector IND.\n%\n% Let ind be a vector of indexes for entries of some upper triangular\n% matrix. The entries are selected vertically so that:\n%\n% ind = 1 is associated to entry (1, 2)\n% ind = 2 is associated to entry (1, 3)\n% ind = 3 is associated to entry (2, 3)\n% ind = 4 is associated to entry (1, 4)\n% ...\n% ind = N * (N - 1) / 2 is associated to entry (N - 1, N)\n%\n% % ======================================================================\n%\n% EXAMPLE\n%\n% % Note that if\n% A = rand(10);\n% % and\n% b = A(find(triu(A, 1)));\n% % then, given indices\n% IND = [1:45];\n% % for vector b, these are equivalent to subscripts\n% [I, J] = ind2sub4up(IND);\n% % for matrix A. In fact:\n% all(A(sub2ind(size(A), I, J)) == b(IND))\n%\n% % ans =\n% % 1\n%\n% % This is obtained without even knowing about size(A)\n%\n% % ======================================================================\n%\n% See also SUB2IND, IND2SUB, FIND.\n%\n% % ======================================================================\n%\n%-*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-*%\n% %\n% Author: Liber Eleutherios %\n% E-Mail: libereleutherios@gmail.com %\n% Date: 1 May 2010 %\n% %\n%-*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-* -*-*%\n%\n% % ======================================================================\n%\n\n% Check input\nctrl1 = isnumeric(IND) & isreal(IND);\nif ctrl1\n IND = ceil(IND(:));\n ctrl2 = ~any(isnan(IND)) & ~any(isinf(IND)) & all(IND > 0);\n if ~ctrl2\n error('Check indexes: they need to be positive integers!')\n end\nelse\n error('Check indexes: they need to be positive integers!')\nend\n\nJ = round(floor(-.5 + .5 * sqrt(1 + 8 * (IND - 1))) + 2);\nI = round(J .* (3 - J) / 2 + IND - 1);\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/CSCbox/third_party/ind2sub4up.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.757753349874147}} {"text": "function RF = rfGaussian2d(X,Y,sigmaMajor,sigmaMinor,theta, x0,y0)\n% rfGaussian2d - Create a two dimensional Gaussian receptive field\n%\n% RF = rfGaussian2d(X,Y,sigmaMajor,sigmaMinor,theta,x0,y0);\n%\n% X,Y : Sample positions in deg\n% sigmaMajor : standard deviation longest direction\n% sigmaMinor : standard deviation shortest direction\n% [default: sigmaMinor = sigmaMajor]\n% theta : angle of sigmaMajor (radians, 0=vertical)\n% [default = 0];\n% x0 : x-coordinate of center of RF [default = 0];\n% y0 : y-coordinate of center of RF [default = 0];\n%\n%\n% Example:\n% To make one rf:\n% fieldRange = 20; % Deg\n% sampleRate = 0.2; % Deg\n% x = [-fieldRange:sampleRate:fieldRange];\n% y = x;\n% [X,Y] = meshgrid(x,y);\n% sigma = 5; % Deg\n% rf = rfGaussian2d(X,Y,sigma);\n% \n\n% Programming notes:\n% Maybe we should always make sure we use an odd number of samples and\n% have a sample at the origin\n\n% According to profile half of the executing time for the function\n% is spend at notDefined, and this functions is called lots (it\n% is the slowest part in rmMain together with rfMakePrediction), so\n% if it seems that all arguments are given just skip it.\n% ras 08/06: well, we can do what Bob does: not call it at all anyway.\nif nargin ~= 7,\n if ~exist('X', 'var') || isempty(X),\n error('Must define X grid');\n end;\n\n if ~exist('Y', 'var') || isempty(Y),\n error('Must define Y grid');\n end;\n\n if ~exist ('sigmaMajor', 'var') || isempty(sigmaMajor),\n error('Must scale on major axis');\n end;\n\n if ~exist ('sigmaMinor', 'var') || isempty(sigmaMinor),\n sigmaMinor = sigmaMajor;\n end;\n\n if ~exist ('theta', 'var') || isempty(theta), theta = false; end;\n if ~exist ('x0', 'var') || isempty(x0), x0 = 0; end;\n if ~exist ('y0', 'var') || isempty(y0), y0 = 0; end;\nend;\n\n\n% Allow sigma, x,y to be a matrix so that the final output will be\n% size(X,1) by size(x0,2). This way we can make many RFs at the same time.\n% Here I assume that all parameters are given.\nif numel(sigmaMajor)~=1,\n sz1 = numel(X);\n sz2 = numel(sigmaMajor);\n\n X = repmat(X(:),1,sz2);\n Y = repmat(Y(:),1,sz2);\n\n sigmaMajor = repmat(sigmaMajor(:)',sz1,1);\n sigmaMinor = repmat(sigmaMinor(:)',sz1,1);\n\n if any(theta(:)),\n theta = repmat(theta(:)',sz1,1);\n end;\n\n x0 = repmat(x0(:)',sz1,1);\n y0 = repmat(y0(:)',sz1,1);\nend;\n\n% Translate grid so that center is at RF center\nX = X - x0; % positive x0 moves center right\nY = Y - y0; % positive y0 moves center up\n\n\n% Rotate grid around the RF center, positive theta rotates the\n% grid to the right. No need for this if theta is 0.\nif any(theta(:)),\n Xold = X;\n Yold = Y;\n X = Xold .* cos(theta) - Yold .* sin(theta);\n Y = Xold .* sin(theta) + Yold .* cos(theta);\nend;\n\n% make gaussian on current grid\nRF = exp( -.5 * ((Y ./ sigmaMajor).^2 + (X ./ sigmaMinor).^2));\n\n% Normalize the Gaussian.\n% The idea is that if you stimulate the entire RF you will\n% always get the same activation, independent of the RF parameters.\n% RF = RF ./ (sigmaMajor.*2.*pi.*sigmaMinor);\n% Decided not to do this. The fitting will deal with this.\n% Thus amplitude will always be the same.\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/rfGaussian2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7577533443736508}} {"text": "function score = nmi_onmf(true_labels, cluster_labels)\n%NMI Compute normalized mutual information (NMI) using the true and cluster\n% labels and return the value in 'score'.\n%\n% Input : true_labels : N-by-1 vector containing true labels\n% cluster_labels : N-by-1 vector containing cluster labels\n%\n% Output : score : NMI value\n%\n% Reference: Shi Zhong, 2003.\n% http://www.cse.fau.edu/~zhong/software/textclust.zip\n\n% Compute the confusion matrix 'cmat', where\n% col index is for true label (CAT),\n% row index is for cluster label (CLS).\nn = length(true_labels);\ncat = spconvert([(1:n)' true_labels ones(n,1)]);\ncls = spconvert([(1:n)' cluster_labels ones(n,1)]);\ncls = cls';\ncmat = full(cls * cat);\n\nn_i = sum(cmat, 1); % Total number of data for each true label (CAT), n_i\nn_j = sum(cmat, 2); % Total number of data for each cluster label (CLS), n_j\n\n% Calculate n*n_ij / n_i*n_j\n[row, col] = size(cmat);\nproduct = repmat(n_i, [row, 1]) .* repmat(n_j, [1, col]);\nindex = find(product > 0);\nn = sum(cmat(:));\nproduct(index) = (n*cmat(index)) ./ product(index);\n% Sum up n_ij*log()\nindex = find(product > 0);\nproduct(index) = log(product(index));\nproduct = cmat .* product;\nscore = sum(product(:));\n% Divide by sqrt( sum(n_i*log(n_i/n)) * sum(n_j*log(n_j/n)) )\nindex = find(n_i > 0);\nn_i(index) = n_i(index) .* log(n_i(index)/n);\nindex = find(n_j > 0);\nn_j(index) = n_j(index) .* log(n_j(index)/n);\ndenominator = sqrt(sum(n_i) * sum(n_j));\n\n% Check if the denominator is zero\nif denominator == 0\n score = 0;\nelse\n score = score / denominator;\nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/auxiliary/clustering_evaluator/nmi_onmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7577100035588589}} {"text": "% Nonnegative matrix factorization\n% Argyris Zymnis, Joelle Skaf, Stephen Boyd\n%\n% We are given a matrix A in R^{m*n}\n% and are interested in solving the problem:\n%\n% minimize ||A - Y*X||_F\n% subject to Y >= 0, X >= 0\n%\n% where Y in R{m*k} and X in R{k*n}.\n% This script generates a random matrix A and obtains an\n% *approximate* solution to the above problem by first generating\n% a random initial guess for Y and the alternatively minimizing\n% over X and Y for a fixed number of iterations.\n\n% Generate data matrix A\nrstate = rand('state');\nm = 10; n = 10; k = 5;\nA = rand(m,k)*rand(k,n);\n\n% Initialize Y randomly\nY = rand(m,k);\n\n% Perform alternating minimization\nMAX_ITERS = 30;\nresidual = zeros(1,MAX_ITERS);\nfor iter = 1:MAX_ITERS\n cvx_begin quiet\n if mod(iter,2) == 1\n variable X(k,n)\n X >= 0; \n else\n variable Y(m,k)\n Y >= 0;\n end\n minimize(norm(A - Y*X,'fro'));\n cvx_end\n fprintf(1,'Iteration %d, residual norm %g\\n',iter,cvx_optval);\n residual(iter) = cvx_optval;\nend\n\n% Plot residuals\nplot(residual); \nxlabel('Iteration Number');\nylabel('Residual Norm');\n\n% Display results\ndisp( 'Original matrix:' );\ndisp( A );\ndisp( 'Left factor Y:' );\ndisp( Y );\ndisp( 'Right factor X:' );\ndisp( X );\ndisp( 'Residual A - Y * X:' );\ndisp( A - Y * X );\nfprintf( 'Residual after %d iterations: %g\\n', iter, cvx_optval );\n\n\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/nonneg_matrix_fact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.7577100025732137}} {"text": "function [mu, b, se, LR_chi2, convState] = drxlr_logistic_regression(x,y,iterlim,convcrit)\n% regression by logistic model\n% discrete reponse and different types of explanatory variables\n% x: column vector of explanatory variables\n% y: column vector of observations\n% solved by maximum likelihood estimates using iterative weighted\n% least-squared.\n% written by Issam El Naqa Spring 2003\n% Extracted for generalized use 2005, AJH\n% LM: APA 07/13/2006, added convState as output parameter to represent the\n% state of convergence. convState is a 1x3 vector with 1st element being\n% converged Yes or no, second element being number of iterations for\n% convergence and third element being convergence criteria condition\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 .\n\n% Initialize parameters\n%warning('off');\nx = [x ones(size(x,1),1)]; % constant factor\niter = 0;\n[n p] = size(x);\nseps = sqrt(eps);\neta = drxlr_rlogit((y + 0.5)/2); % initialize\nb = zeros(p,1);\nb0 = b+1;\n% Start iterating\nwhile(1)\n iter = iter+1;\n mu = drxlr_invlogit(eta);\n mu = max(0, min(1, mu));\n % Check stopping conditions\n if (~any(abs(b-b0) > convcrit * max(seps, abs(b0))))\n convState = [1 iter-1 max(abs(b-b0))];\n break;\n end\n if (iter>iterlim)\n warning('drxlr_logistic_regression: Number of iterations exceeded without convergence (convergence tolerance = %e', convcrit)\n convState = [2 iter-1 max(abs(b-b0))];\n break; % iteration limit reached, exit!\n end\n deta = drxlr_d_logit(mu);\n z = eta + (y - mu) .* deta;\n vy=drxlr_binomial_variance(mu);\n w = 1 ./ max(eps, (deta .^ 2) .* vy);\n b0 = b;\n [b,R,se] = drxlr_wfit(z, x, w, p);\n eta = x * b;\nend\n\n%%% calculate likelihood ratio test\nLR_chi2=drxlr_get_lrt(y,mu);\nreturn\n", "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_logistic_regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7577099993865278}} {"text": "function d = distanz(x,y,algtype)\n% DISTANZ : calculates the distances between all vectors in x and y.\n%\n% usage:\n% d = distanz(x,y);\n%\n% inputs:\n% x matrix with col vectors\n% y matrix with col vectors (default == x)\n% algtype the type of algorithm that is used (default==3)\n%\n% outputs:\n% d distance matrix, not squared\n%\n% note:\n% part of the code is inspired by dist.m of the nntoolbox, other\n% part adapted from Francis Bach who took it from Roland\n% Bunschoten.\n%\n% sth * 19apr2002\n% Adapted from create.m, originally written by\n% (c) Stefan Harmeling, 2006\n\nif exist('algtype')~=1 || isempty(algtype), algtype = 3; end\nswitch algtype\n case 1 % inspired by dist.m\n if exist('y')~=1 || isempty(y)\n % here comes code just for x\n [rx,cx] = size(x);\n d = zeros(cx,cx);\n nuller = zeros(cx,1);\n for c = 1:cx\n d(c,:) = sum((x-x(:,c+nuller)).^2,1);\n end\n else\n % here comes code for x and y\n [rx,cx] = size(x);\n [ry,cy] = size(y);\n if rx~=ry, error('x and y do not fit'), end\n d = zeros(cx,cy);\n if cx>cy\n nuller = zeros(cx,1);\n for c = 1:cy\n\td(:,c) = sum((x-y(:,c+nuller)).^2,1)';\n end\n else\n nuller = zeros(cy,1);\n for c = 1:cx\n\td(c,:) = sum((x(:,c+nuller)-y).^2,1);\n end\n end\n end\n \n case 2 % same as case 1, but with repmat instead of nuller\n if exist('y')~=1 || isempty(y)\n % here comes code just for x\n [rx,cx] = size(x);\n d = zeros(cx,cx);\n nuller = zeros(cx,1);\n for c = 1:cx\n d(c,:) = sum((x-repmat(x(:,c),[1 cx])).^2,1);\n end\n else\n % here comes code for x and y\n [rx,cx] = size(x);\n [ry,cy] = size(y);\n if rx~=ry, error('x and y do not fit'), end\n d = zeros(cx,cy);\n if cx>cy\n nuller = zeros(cx,1);\n for c = 1:cy\n\td(:,c) = sum((x-repmat(y(:,c),[1 cx])).^2,1)';\n end\n else\n nuller = zeros(cy,1);\n for c = 1:cx\n\td(c,:) = sum((repmat(x(:,c),[1 cy])-y).^2,1);\n end\n end\n end\n \n case 3 % inspired by Roland Bunschoten\n if exist('y')~=1 || isempty(y)\n % here comes code just for x\n cx = size(x,2);\n xx = sum(x.*x,1); xz = x'*x;\n d = abs(repmat(xx',[1 cx]) - 2*xz + repmat(xx,[cx 1]));\n else\n % here comes code for x and y\n [rx,cx] = size(x);\n [ry,cy] = size(y);\n if rx~=ry, error('x and y do not fit'), end\n xx = sum(x.*x,1); yy = sum(y.*y,1); xy = x'*y; \n d = abs(repmat(xx',[1 cy]) + repmat(yy,[cx 1]) - 2*xy);\n end\nend\n\nd = sqrt(d);\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/old/sgwt_toolbox/demo/distanz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7576977185677096}} {"text": "function y = barycentricInterpolate(Y,Idx,W)\n% y = barycentricInterpolate(Y,Idx,W)\n%\n% This function interpolates a point y, based on the data in Y and the\n% weights (W) on the verticies Y(Idx)\n%\n% INPUTS:\n% Y = [N, 1] data set.\n% W = [d+1, n] weight to apply to each index\n% Idx = [d+1, n] linear index corresponding to each weight\n%\n% OUTPUTS:\n% y = [n,d] = function value at query points\n%\n% NOTES:\n% --> y = f(x), where x is d-dimensional, and y is scalar\n% --> Y = Y(x1,x2,...,xd)\n% --> n = size(Y);\n% --> y(X(:,i)) = W(i,:)*Y(Idx(:,i));\n%\n% See Also: barycentricWeights\n\nn = size(Idx,2);\ny = zeros(n,1);\n\nfor query=1:n\n y(query) = dot(W(:,query),Y(Idx(:,query)));\nend\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/MDP_Pendulum/barycentricInterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7576977135390652}} {"text": "function unique_num = r8col_tol_unique_count ( m, n, a, tol )\n\n%*****************************************************************************80\n%\n%% R8COL_TOL_UNIQUE_COUNT counts tolerably unique entries in an R8COL.\n%\n% Discussion:\n%\n% Because the array is unsorted, this algorithm is O(N^2).\n%\n% If the tolerance is large enough, then the concept of uniqueness\n% can become ambiguous. If we have a tolerance of 1.5, then in the\n% list ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ) is it fair to say we have only\n% one unique entry? That would be because 1 may be regarded as unique,\n% and then 2 is too close to 1 to be unique, and 3 is too close to 2 to\n% be unique and so on.\n%\n% This seems wrongheaded. So I prefer the idea that an item is not\n% unique under a tolerance only if it is close to something that IS unique.\n% Thus, the unique items are guaranteed to cover the space if we include\n% a disk of radius TOL around each one.\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% Parameters:\n%\n% Input, integer M, the number of rows.\n%\n% Input, integer N, the number of columns.\n%\n% Input, real A(M,N), the unsorted array.\n%\n% Input, real TOL, a tolerance for equality.\n%\n% Output, integer UNIQUE_NUM, the number of unique columns of A.\n%\n undx = 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%\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 break\n end\n end\n\n if ( unique )\n k = k + 1;\n undx(k) = indx(i);\n end\n\n end\n\n unique_num = k;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8col_tol_unique_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8774767970940974, "lm_q1q2_score": 0.7576061168953159}} {"text": "function length = circle01_length ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE01_LENGTH: length of the circumference of the unit circle in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 11 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real LENGTH, the length.\n%\n r = 1.0;\n length = 2.0 * pi * r;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_integrals/circle01_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7576061058297933}} {"text": "function [ss, dist_map] = makeSphericalSection(radius, height, width, plot_section, binary)\n%MAKESPHERICALSECTION Create a binary map of a sphere segment within a 3D grid.\n%\n% DESCRIPTION:\n% makeSphericalSection creates a binary map of a section of a\n% spherical surface within a three-dimensional matrix. The sphere is\n% created using an extension of the midpoint circle algorithm. A\n% single grid point is taken as the sphere center so the total\n% diameter will always be an odd number of grid points. The sphere is\n% then truncated based on the values for height and width (a diagram\n% of the input sizes is given below). The face of the spherical\n% section faces in the positive x-direction and the optional width\n% parameter truncates the size in the y-direction. \n%\n% If the optional input parameter \"binary\" is set to false (the\n% default), the section map is returned as a double precision matrix.\n% If it is set to true, the map is returned as a logical matrix. The\n% average distance between each grid point in the spherical section\n% and its contiguous neighbours can also be returned. This is given\n% as a ratio compared to the average neighbour distance for a flat\n% surface. \n%\n% SYNTAX:\n% ss = makeSphericalSection(radius, height)\n% ss = makeSphericalSection(radius, height, width)\n% ss = makeSphericalSection(radius, height, width, plot_section)\n% ss = makeSphericalSection(radius, height, [], plot_section)\n% ss = makeSphericalSection(radius, height, width, plot_section, binary)\n% ss = makeSphericalSection(radius, height, [], [] binary)\n%\n% [ss, dist_map] = makeSphericalSection(radius, height)\n% [ss, dist_map] = makeSphericalSection(radius, height, width)\n% [ss, dist_map] = makeSphericalSection(radius, height, [], plot_section)\n% [ss, dist_map] = makeSphericalSection(radius, height, width, plot_section)\n% [ss, dist_map] = makeSphericalSection(radius, height, width, plot_section, binary)\n% [ss, dist_map] = makeSphericalSection(radius, height, [], [] binary)\n%\n% INPUTS:\n% radius - radius of curvature [grid points]\n% height - transducer height [grid points]\n%\n% OPTIONAL INPUTS:\n% width - section width (must be specified as an odd\n% number) [grid points] \n% plot_section - Boolean controlling whether the spherical section\n% is plotted using voxelPlot (default = false) \n% binary - Boolean controlling whether the spherical section\n% is returned as a double precision matrix (false)\n% or a logical matrix (true) (default = false)\n%\n% OUTPUTS:\n% ss - binary matrix containing spherical section\n% dist_map - ratio of average neighbour distance for each grid\n% point within the spherical section compared to a\n% flat surface \n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 3rd February 2012\n% last update - 20th 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 makeBall, makeSphere\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n%#ok<*UNRCH>\n\n% option to use the spherical sections or square sections of the sphere\n% returned by makeSphere (true by default)\nuse_spherical_sections = true;\n\n% force inputs to be integers\nradius = round(radius);\nheight = round(height);\n\n% check for width input\nif nargin < 3 || (nargin == 4 && isempty(width))\n \n % set width truncation flag to false\n use_width = false;\n \nelse\n \n % set width truncation flag to true\n use_width = true;\n \n % force input to an integer\n width = round(width);\n \n % check that it's an odd number\n if ~rem(width, 2)\n error('width must be an odd number');\n end\n \nend\n\n% check for plot input\nif nargin < 4 || isempty(plot_section)\n plot_section = false;\nend \n\n% check for data type input\nif nargin < 5 || isempty(binary)\n binary = false;\nend \n\n% calculate minimum grid dimensions to fit entire sphere\nNx = 2*radius + 1;\n\n% create sphere\nss = makeSphere(Nx, Nx, Nx, radius, [], binary);\n\n% truncate to given height\nif use_spherical_sections\n ss = ss(1:height, :, :);\nelse\n ss = permute(ss(:, 1:height, :), [2, 3, 1]);\nend\n\n% flatten transducer and store the maximum and indices\nmx = squeeze(max(ss, [], 1));\n\n% calculate the total length/width of the transducer\nlength = sum(mx(ceil(end/2), :), 2);\n\n% truncate transducer grid based on length (removes empty rows and columns)\noffset = (Nx - length)/2;\nss = ss(:, 1 + offset:end - offset, 1 + offset:end - offset);\n\n% also truncate to given width if defined by user\nif use_width\n \n % check the value is appropriate\n if width > length\n error('input for width must be less than or equal to transducer length');\n end\n \n % calculate offset\n offset = (length - width)/2;\n \n % truncate transducer grid\n ss = ss(:, 1 + offset:end - offset, :); \n \nend\n \n% compute average distance between each grid point and it's contiguous\n% neighbours if dist_map output is defined\nif nargout == 2 \n\n % calculate x-index of each grid point in the spherical section, create\n % mask and remove singleton dimensions \n [mx, mx_ind] = max(ss, [], 1);\n mask = squeeze(mx ~= 0);\n mx_ind = squeeze(mx_ind).*mask; \n \n % double check there there is only one value of spherical section in\n % each matrix column\n if sum(mx(:)) ~= sum(ss(:))\n error('mean neighbour distance cannot be calculated uniquely due to overlapping points in the x-direction');\n end \n \n % calculate average distance to grid point neighbours in the flat case\n x_dist = repmat([1 0 1], 3, 1);\n y_dist = x_dist.';\n flat_dist = sqrt(x_dist.^2 + y_dist.^2);\n flat_dist = mean(flat_dist(:));\n \n % compute distance map \n dist_map = zeros(size(mx_ind));\n sz = size(mx_ind);\n for m = 1:sz(1)\n for n = 1:sz(2)\n\n % clear map\n local_heights = zeros(3, 3);\n\n % extract the height (x-distance) of the 8 neighbouring grid\n % points\n if m == 1 && n == 1\n local_heights(2:3, 2:3) = mx_ind(m:m + 1, n:n + 1);\n elseif m == sz(1) && n == sz(2)\n local_heights(1:2, 1:2) = mx_ind(m - 1:m, n - 1:n);\n elseif m == 1 && n == sz(2)\n local_heights(2:3, 1:2) = mx_ind(m:m + 1, n - 1:n);\n elseif m == sz(1) && n == 1\n local_heights(1:2, 2:3) = mx_ind(m - 1:m, n:n + 1);\n elseif m == 1\n local_heights(2:3, :) = mx_ind(m:m + 1, n - 1:n + 1);\n elseif m == sz(1)\n local_heights(1:2, :) = mx_ind(m - 1:m, n - 1:n + 1);\n elseif n == 1\n local_heights(:, 2:3) = mx_ind(m - 1:m + 1, n:n + 1);\n elseif n == sz(2)\n local_heights(:, 1:2) = mx_ind(m - 1:m + 1, n - 1:n);\n else\n local_heights = mx_ind(m - 1:m + 1, n - 1:n + 1);\n end\n\n % compute average variation from center\n local_heights_var = abs(local_heights - local_heights(2, 2)); \n\n % threshold no neighbours\n local_heights_var(local_heights == 0) = 0;\n\n % calculate total distance from centre\n dist = sqrt(x_dist.^2 + y_dist.^2 + local_heights_var.^2);\n\n % average and store as a ratio\n dist_map(m, n) = 1 + (mean(dist(:)) - flat_dist)./flat_dist;\n\n end \n end\n\n % threshold out the non-transducer grid points\n dist_map(mask ~= 1) = 0;\n \n % flattened plot and distance values\n if plot_section \n figure;\n subplot(2, 1, 1);\n imagesc(mx_ind);\n axis image;\n colorbar;\n title('Height of Transducer Face');\n subplot(2, 1, 2);\n dist_map_plot = dist_map;\n dist_map_plot(dist_map_plot ~= 0) = dist_map_plot(dist_map_plot ~= 0) -1;\n imagesc(100*dist_map_plot);\n axis image;\n colorbar;\n title('Percentage Increase in Average Neighbour Distance Compared to a Flat Surface');\n end\n\nend\n\n% plot if required \nif plot_section \n\n voxelPlot(double(ss));\n view(150, 20);\n \n% % create surface plot\n% figure;\n% sz = size(ss);\n% [x, y] = meshgrid(1:sz(3),1:sz(2));\n% surface_ind = find(mx ~= 0); \n% plot3(x(surface_ind), y(surface_ind), mx_ind(mx ~= 0), 'k.');\n% axis image;\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/makeSphericalSection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7575953112072945}} {"text": "function nearest = find_closest3 ( m, nr, r, ns, s )\n\n%*****************************************************************************80\n%\n%% FIND_CLOSEST3 finds the nearest R point to each S point.\n%\n% Discussion:\n%\n% We are given R, a set of NR points in M dimensions.\n%\n% We are given S, a set of NS points in M dimensions.\n%\n% For each S(I) in S, we seek the index J of the point R(J)\n% which is nearest to S(I) over all points in R.\n%\n% Modified in accordance with suggestions by Gene Cliff, 08 July 2010.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer NR, the number of cell generators.\n%\n% Input, real R(M,NR), the cell generators.\n%\n% Input, integer NS, the number of sample points.\n%\n% Input, real S(M,NS), the points to be checked.\n%\n% Output, integer NEAREST(NS), the index of the cell generator nearest\n% to the sample point.\n%\n ones_k = ones ( 1, nr );\n nearest = NaN ( 1, ns );\n\n for i = 1 : ns\n d1 = r - s(:,i) * ones_k;\n d2 = sum ( d1 .* d1 );\n [ min_val, min_loc ] = min ( d2 );\n nearest(i) = min_loc;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_nearest/find_closest3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553435, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7575606751212064}} {"text": "function [ x, seed ] = sphere01_sample ( n, seed )\n\n%*****************************************************************************80\n%\n%% SPHERE01_SAMPLE picks random points on the unit sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of samples.\n%\n% Input/output, integer SEED, a seed for the random \n% number generator.\n%\n% Output, real X(3,N), the sample points.\n%\n x = zeros ( 3, n );\n\n for j = 1 : n\n%\n% Pick a uniformly random VDOT, which must be between -1 and 1.\n% This represents the dot product of the random vector with the Z unit vector.\n%\n% Note: this works because the surface area of the sphere between\n% Z and Z + dZ is independent of Z. So choosing Z uniformly chooses\n% a patch of area uniformly.\n%\n [ vdot, seed ] = r8_uniform_01 ( seed );\n vdot = 2.0 * vdot - 1.0;\n\n phi = r8_acos ( vdot );\n%\n% Pick a uniformly random rotation between 0 and 2 Pi around the\n% axis of the Z vector.\n%\n [ theta, seed ] = r8_uniform_01 ( seed );\n theta = 2.0 * pi * theta;\n\n x(1,j) = cos ( theta ) * sin ( phi );\n x(2,j) = sin ( theta ) * sin ( phi );\n x(3,j) = cos ( phi );\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/sphere_triangle_quad/sphere01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7575606652151401}} {"text": "function [R] = ipsrf(varargin)\n%IPSRF Interval Potential Scale Reduction Factor\n%\n% [R] = IPSRF(X) or\n% [R] = IPSRF(x1,x2,...,xs)\n% returns \"Potential Scale Reduction Factor\" (PSRF) for\n% collection of MCMC-simulations. X is a NxDxM matrix\n% which contains M MCMC simulations of length N, each with\n% dimension D. MCMC-simulations can be given as separate\n% arguments x1,x2,... which should have the same length.\n%\n% Returns \n% R PSRF in a row vector of length D\n%\n% The idea of the PSRF is that if R is not near 1 (below 1.1 for\n% example) one may conclude that the tested samples were not from\n% the same distribution (chain might not have been converged\n% yet). Instead of normality assumption, 80% empirical intervals\n% are used to compute R.\n%\n% If only one simulation is given, the factor is calculated\n% between first and last third of the chain. Note that use of\n% only one chain will produce over-optimistic result.\n%\n% Method is from:\n% Brooks, S.P. and Gelman, A. (1998) General methods for\n% monitoring convergence of iterative simulations. Journal of\n% Computational and Graphical Statistics. 7, 434-455. \n%\n% See also\n% CIPSRF, PSRF\n\n% Copyright (C) 1999 Simo S�rkk�\n% Copyright (C) 2004 Aki Vehtari\n%\n% This software is distributed under the GNU General Public \n% Licence (version 3 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\n% In case of one argument split to two halves (first and last thirds)\nonechain=0;\nif nargin==1\n X = varargin{1};\n if size(X,3)==1\n n = floor(size(X,1)/3);\n x = zeros([n size(X,2) 2]);\n x(:,:,1) = X(1:n,:);\n x(:,:,2) = X((end-n+1):end,:);\n X = x;\n onechain=1;\n end\nelseif nargin==0\n error('Cannot calculate PSRF of scalar');\nelse\n X = zeros([size(varargin{1}) nargin]);\n for i=1:nargin\n X(:,:,i) = varargin{i};\n end\nend\n\n[N,D,M]=size(X);\n\nif N<1\n error('Too few samples');\nend\n\nW = zeros(1,D);\nV = zeros(1,D);\nfor d=1:D\n x=X(:,d,:);\n W(1,d)=mean(diff(prctile(x,[10 90])));\n V(1,d)=diff(prctile(x(:),[10 90]));\nend\nR = V./W;\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/ipsrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7575606570712689}} {"text": "function M=minMatOverDim(C,minIdx)\n%%MINMATOVERDIM Given a multidimensional matrix C, this function returns\n% matrix M that is obtained by minimizing C over the given\n% dimension and removing the given dimension. This is equivalent\n% to using a call to min(C,[],minIdx) in Matlab. However, here,\n% we do it without using any matrix/ vector commands so that it\n% can mirror how one might implement such a function in C.\n%\n%INPUTS: C A real n1Xn2Xn3..XnS S-dimensional hypermatrix.\n% minIdx The real index from 1 to S over which the minimization should be\n% performed.\n%\n%OUTPUTS: M An n1X...n(minIdx-1)X1Xn(minIdx+1)X...nS matrix holding the\n% minimum values over the specified dimension.\n%\n%The algorithm consists of two types of steps. First, a step in the linear\n%indexation of C to go from one value of an index in spot minIdx is\n%prod(nVals(1:(minIdx-1))), where nVals=size(C). Thus, we can go from one\n%element to the next for the minimization. For a 3D matrix, the step to go\n%from C(i1,1,i2) to C(i1+1,1,i2) increments by 1. However, to go from \n%C(n1,1,i2) to C(1,1,i2+1) is a step of prod(nVals(1:minIdx)). The same\n%type of thing applies to a matrix with more dimensions, since all\n%dimensions before the one in question and after can be collapsed into 1\n%dimension. Thus, this function puts the above rules together to go\n%minimize the matrix.\n%\n%EXAMPLE:\n%Here, we just show that the results are equivalent to using the min\n%command with a resize.\n% C=randn(13,18,11,6,9);\n% minIdx=3;\n% M=minMatOverDim(C,minIdx);\n% MAlt=min(C,[],minIdx);\n% all(M(:)==MAlt(:))\n%The result is 1, indicating that the two values are equal.\n%\n%March 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnVals=size(C);\nS=numel(nVals);\n\nif(minIdx<1)\n error('Invalid value of minIdx given.')\nend\n\nif(minIdx>S)\n M=C;\n return;\nend\n\nMDims=nVals;\nMDims(minIdx)=1;\nM=zeros(MDims);\n\ntotalNumElsM=prod(MDims);\n\n%Note that prod([])=1\nincrMinIdx=prod(nVals(1:(minIdx-1)));\n\nincrBigStep=incrMinIdx*nVals(minIdx);\n\nCStartIdx=0;\ncurMCol=0;\nfor curEl=0:(totalNumElsM-1)\n curIdx=CStartIdx;\n minVal=C(curIdx+1);\n\n curIdx=curIdx+incrMinIdx;\n for i=2:nVals(minIdx)\n curVal=C(curIdx+1);\n \n if(curVal 0 | sum(any(triu(A, 2))) > 0 \n fprintf('\\n Error: A 不是三对角矩阵!\\n'); x = []; return; \nend \n\n% 判断是否对角占优\nif (abs(b(1)) <= abs(c(1)) | abs(c(1)) == 0 | find(abs(b(2:n-1)) < abs(a(2:n-1)) + abs(c(2:n-1))) > 0 | abs(b(n)) <= abs(a(n))) | abs(a(n)) == 0\n fprintf('\\n Error: A 不是对角占优矩阵!\\n'); x = []; return; \nend \n\nalpha = zeros(n, 1);\nbeda = zeros(n-1, 1);\ngamma = a; % gamma直接等于a,无需计算\n\nalpha(1) = b(1);\nfor i = 1 : n - 1\n beda(i) = c(i) / alpha(i);\n alpha(i + 1) = b(i + 1) - a(i + 1) * beda(i);\nend\n\n% 求解Ly=b 和 Ux=y\ny(1) = f(1) / b(1);\nfor i=2:n\n y(i)=(f(i) - a(i)*y(i-1)) / alpha(i);\nend\nx(n) = y(n);\nfor i = n-1 : -1 : 1\n x(i)=y(i) - beda(i) * x(i+1);\nend\n\n\n% END\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第六章 线性方程组的直接法/my_forward_backward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7573819343015542}} {"text": " function X = dtft1(x, omega, n_shift)\n%function X = dtft1(x, omega, n_shift)\n%| Compute DTFT of 1D signal x at frequency locations wx\n%| In\n%|\tx\t[N,ncol]\tsignal values\n%|\tomega\t[M,1]\t\tfrequency locations\n%|\tn_shift\t[1,1]\t\tuse [0:(N-1)]-n_shift indices\n%| Out\n%|\tX\t[M,ncol]\tDTFT values\n%|\n%| This needs enough memory to store M * N size matrices\n%| Copyright 2000-1-9, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(x, 'test'), dtft1_test, return, end\nif nargin < 2, ir_usage(), end\n\nN = size(x,1);\nif ~isvar('n_shift') || isempty(n_shift), n_shift = 0; end\nnn = [0:(N-1)] - n_shift;\n\nX = exp(-1i*omega*nn) * x; % compute 1D DTFT\n\n\nfunction dtft1_test()\nN = 4;\nx = [[1:N]', [1 1 2 2]'];\t% two test signal\nomega = 2*pi*[0:(N-1)]'/N;\t% test with uniform frequency locations\nXd = dtft1(x, omega);\nXf = fft(x);\n%disp([Xd Xf])\nprintm('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/dtft1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7573819265792567}} {"text": "function p = MS_fnn(y,de,tau,th,kth);\n% function nfnn = MS_fnn(y,de,tau,th,kth)\n%\n% determine the number of false nearest neighbours for the time\n% series y embedded in dimension de with lag tau.\n%\n% for each pair of values (de,tau) the data y is embeded and the\n% nearest neighbour to each point (excluding the immediate\n% neighbourhood of n points) is determined. If the ratio of the\n% distance of the next (kth) points and these points is greater than\n% th then they are counted as false nearest neighbours.\n%\n% default:\n% th=5\n% kth=1\n%\n% p(i,j) is the proportion of false nearest neighbours for de(i)\n% and tau(j).\n%\n% Michael Small\n% michael.small@uwa.edu.au, http://school.maths.uwa.edu.au/~small/\n% 3/3/2005\n% For further details, please see M. Small. Applied Nonlinear Time Series\n% Analysis: Applications in Physics, Physiology and Finance. Nonlinear Science\n% Series A, vol. 52. World Scientific, 2005. (ISBN 981-256-117-X) and the\n% references therein.\n% (minor cosmetic changes made by Ben Fulcher, 2010)\n\nif nargin < 5\n kth = 1;\n disp(['th = ',int2str(kth)]);\nend\nif nargin < 4\n th = 5;\n disp(['th = ',int2str(th)]);\nend\nif nargin < 3\n tau = MS_firstzero(y);\n disp(['tau = ',int2str(tau)]);\nend\nif nargin < 2\n de = [1:10];\n disp(['de = ',int2str(de(1)),':',int2str(de(end))]);\nend\n\np=[];\nfor t=tau,\n px=[];\n for d=de\n %embed the data\n X=MS_embed(y,d,t);\n [dx,nx]=size(X);\n\n %find the nearest neighbours of each point\n ind=MS_nearest(X(:,1:(nx-kth)),tau); %whooh hooo!\n\n\n %distance between each point and its nearest neighbour\n d0=MS_rms(X(:,(1:(nx-kth)))'-X(:,ind)');\n %... and after one time step\n d1=MS_rms(X(:,(kth+1):nx)'-X(:,ind+1)');\n\n %exclude any coincident points\n d1(d0==0)=[];\n d0(d0==0)=[];\n\n %calculate the proportion fnn\n ifnn=sum((d1./d0)>th)/length(d0);\n\n %disp\n % disp(['tau = ', int2str(t),', de = ',int2str(d),', nfnn = ',num2str(ifnn*100),'%']);\n\n px=[px ifnn];\n end;\n\n p=[p;px];\n\nend;\n\np=p';\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/Michael_Small/MS_fnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7573734348691692}} {"text": "function geometry_test0183 ( )\n\n%*****************************************************************************80\n%\n%% TEST0183 tests CIRCLE_LLR2IMP_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n p_hi = 10.0;\n p_lo = -10.0;\n test_num = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0183\\n' );\n fprintf ( 1, ' CIRCLE_LLR2IMP_2D is given:\\n' );\n fprintf ( 1, ' a line through P1 and P2,\\n' );\n fprintf ( 1, ' a line through Q1 and Q2,\\n' );\n fprintf ( 1, ' and a radius R,\\n' );\n fprintf ( 1, ' and determines the centers C of 4 circles\\n' );\n fprintf ( 1, ' of the given radius, tangent to both lines.\\n' );\n\n seed = 123456789;\n\n for test = 1 : test_num\n\n [ p1(1:2,1), seed ] = r8vec_uniform ( 2, p_lo, p_hi, seed );\n [ p2(1:2,1), seed ] = r8vec_uniform ( 2, p_lo, p_hi, seed );\n [ q1(1:2,1), seed ] = r8vec_uniform ( 2, p_lo, p_hi, seed );\n [ q2(1:2,1), seed ] = r8vec_uniform ( 2, p_lo, p_hi, seed );\n\n r_lo = 1.0;\n r_hi = 5.0;\n [ r, seed ] = r8_uniform ( r_lo, r_hi, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Radius R = %f\\n', r );\n\n fprintf ( 1, ' Point #P1: %f %f\\n', p1(1:2,1) );\n fprintf ( 1, ' Point #P2: %f %f\\n', p2(1:2,1) );\n fprintf ( 1, ' Point #Q1: %f %f\\n', q1(1:2,1) );\n fprintf ( 1, ' Point #Q2: %f %f\\n', q2(1:2,1) );\n\n pc = circle_llr2imp_2d ( p1, p2, q1, q2, r );\n\n fprintf ( 1, ' Center #1: %f %f\\n', pc(1:2,1) );\n fprintf ( 1, ' Center #2: %f %f\\n', pc(1:2,2) );\n fprintf ( 1, ' Center #1: %f %f\\n', pc(1:2,3) );\n fprintf ( 1, ' Center #2: %f %f\\n', pc(1:2,4) );\n\n d1 = line_exp_point_dist_2d ( p1, p2, pc(1:2,1) );\n d2 = line_exp_point_dist_2d ( p1, p2, pc(1:2,2) );\n d3 = line_exp_point_dist_2d ( p1, p2, pc(1:2,3) );\n d4 = line_exp_point_dist_2d ( p1, p2, pc(1:2,4) );\n\n fprintf ( 1, ' %f %f %f %f\\n', d1, d2, d3, d4 );\n\n d1 = line_exp_point_dist_2d ( q1, q2, pc(1:2,1) );\n d2 = line_exp_point_dist_2d ( q1, q2, pc(1:2,2) );\n d3 = line_exp_point_dist_2d ( q1, q2, pc(1:2,3) );\n d4 = line_exp_point_dist_2d ( q1, q2, pc(1:2,4) );\n\n fprintf ( 1, ' %f %f %f %f\\n', d1, d2, d3, d4 );\n\n end\n\n return\nend\n", "meta": {"author": "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_test0183.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7573734344640944}} {"text": "function [X, info] = dominant_invariant_subspace_complex(A, p)\n% Returns a unitary basis of the dominant invariant p-subspace of A.\n%\n% function X = dominant_invariant_subspace_complex(A, p)\n%\n% Input: A complex, Hermitian matrix A of size nxn and an integer p < n.\n% Output: A complex, unitary matrix X of size nxp such that trace(X'*A*X)\n% is maximized. That is, the columns of X form a unitary basis\n% of a dominant subspace of dimension p of A.\n%\n% The optimization is performed on the complex Grassmann manifold, since\n% only the space spanned by the columns of X matters.\n%\n% See dominant_invariant_subspace for more details in the real case.\n%\n% See also: dominant_invariant_subspace grassmanncomplexfactory\n\n% This file is part of Manopt and is copyrighted. See the license file.\n%\n% Main author: Nicolas Boumal, June 30, 2015\n% Contributors:\n%\n% Change log:\n% \n% Xiaowen Jiang Aug. 31, 2021\n% Added AD to compute the egrad and the ehess \n\n\n % Generate some random data to test the function\n if ~exist('A', 'var') || isempty(A)\n A = randn(128) + 1i*randn(128);\n A = (A+A')/2;\n end\n if ~exist('p', 'var') || isempty(p)\n p = 3;\n end\n \n % Make sure the input matrix is Hermitian\n n = size(A, 1);\n assert(size(A, 2) == n, 'A must be square.');\n assert(norm(A-A', 'fro') < n*eps, 'A must be Hermitian.');\n\tassert(p<=n, 'p must be smaller than n.');\n \n % Define the cost and its derivatives on the complex Grassmann manifold\n Gr = grassmanncomplexfactory(n, p);\n problem.M = Gr;\n problem.cost = @(X) -real(trace(X'*A*X));\n problem.egrad = @(X) -2*A*X;\n problem.ehess = @(X, H) -2*A*H;\n \n % An alternative way to compute the egrad and the ehess is to use \n % automatic differentiation provided in the deep learning toolbox\n % (slower). AD does not support complex numbers if the Matlab version\n % is R2021a or earlier. The cost function should be defined differently\n % In this case. See complex_example_AD.m and manoptADhelp.m for more\n % information.\n % problem.cost = @cost_complex;\n % function f = cost_complex(X)\n % AX = cprod(A,X);\n % Xtransp = ctransp(X);\n % product = cprod(Xtransp,AX);\n % f = -creal(ctrace(product));\n % end\n % call manoptAD to automatically obtain the egrad and the ehess\n % problem = manoptAD(problem);\n \n % If the version of Matlab installed is R2021b or later, specify the \n % cost function in the normal way and call manoptAD. Notice that\n % the function trace is not supported for AD so far. Replace it with \n % ctrace described in the file manoptADhelp.m\n % problem.cost = @(X) -real(ctrace(X'*A*X));\n % problem = manoptAD(problem);\n\n % Execute some checks on the derivatives for early debugging.\n % These can be commented out.\n % checkgradient(problem);\n % pause;\n % checkhessian(problem);\n % pause;\n \n % Issue a call to a solver. A random initial guess will be chosen and\n % default options are selected except for the ones we specify here.\n options.Delta_bar = 8*sqrt(p);\n [X, costX, info, options] = trustregions(problem, [], options); %#ok\n \n fprintf('Options used:\\n');\n disp(options);\n \n % For our information, Manopt can also compute the spectrum of the\n % Riemannian Hessian on the tangent space at (any) X. Computing the\n % spectrum at the solution gives us some idea of the conditioning of\n % the problem. If we were to implement a preconditioner for the\n % Hessian, this would also inform us on its performance.\n %\n % Notice that (typically) all eigenvalues of the Hessian at the\n % solution are positive, i.e., we find an isolated minimizer. If we\n % replace the Grassmann manifold by the Stiefel manifold, hence still\n % optimizing over orthonormal matrices but ignoring the invariance\n % cost(XQ) = cost(X) for all Q orthogonal, then we see\n % dim O(p) = p(p-1)/2 zero eigenvalues in the Hessian spectrum, making\n % the optimizer not isolated anymore.\n if Gr.dim() < 512\n evs = hessianspectrum(problem, X);\n stairs(sort(evs));\n title(['Eigenvalues of the Hessian of the cost function ' ...\n 'at the solution']);\n xlabel('Eigenvalue number (sorted)');\n ylabel('Value of the eigenvalue');\n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/examples/dominant_invariant_subspace_complex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7573734278227059}} {"text": "function [q] = MeshQuality(EToV,VX,VY)\n%\n% Purpose: Assess the triangle mesh quality using a mesh quality indicators.\n% q=2r/R, where r is the inradius and R is the circumradius of a\n% triangle.\n%\n% Function is useful for detecting degenerate triangles.\n%\n% EToV : Element-To-Vertice table\n% VX : x-table for vertices\n% VY : y-table for vertices\n%\n% By Allan P. Engsig-Karup, apek@imm.dtu.dk.\n\n% Compute side lengths of triangles\nlx = VX(EToV(:,[1 2 3])) - VX(EToV(:,[3 1 2]));\nly = VY(EToV(:,[1 2 3])) - VY(EToV(:,[3 1 2]));\nl = sqrt(lx.^2+ly.^2);\na = l(:,1); b = l(:,2); c = l(:,3);\nq = (b+c-a).*(c+a-b).*(a+b-c)./(a.*b.*c);\n\nN = 100; \nx = linspace(0,1,N+1);\ndx = x(2)-x(1);\nsubdivision = x(1:N)+dx/2;\ncount = zeros(1,N);\nK = size(EToV,1);\nfor i = 1 : length(subdivision)\n count(i) = length(find(q>subdivision(i)-dx/2 & q<=subdivision(i)+dx/2))/K*100;\nend\nfigure\nbar(subdivision,count,1)\nminlimit = find(q<0.7);\nif isempty(minlimit)\n axis([0.7 1 -1 max(count)*1.05])\nelse\n axis([min(q) 1 -1 max(count)*1.05])\n hold on\n plot([0.7 0.7],[0 100],'r--')\nend\nxlabel('Mesh quality')\nylabel('Percentage of elements')\ncolormap(cool)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24946-unstructured-triangle-mesh-quality-assesment/MeshQuality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.757373427417631}} {"text": "function [ n_data, x, fx ] = fresnel_sin_values ( n_data )\n\n%*****************************************************************************80\n%\n%% FRESNEL_SIN_VALUES returns some values of the Fresnel sine integral function.\n%\n% Discussion:\n%\n% The Fresnel sine integral is defined by\n%\n% S(X) = integral ( 0 <= T <= X ) sin ( pi * T^2 / 2 ) / T dT\n%\n% In Mathematica, the function can be evaluated by:\n%\n% FresnelS[x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 16;\n\n fx_vec = [ ...\n 0.0000000000000000E+00, ...\n 0.4187609161656762E-02, ...\n 0.3335943266061318E-01, ...\n 0.1105402073593870E+00, ...\n 0.2493413930539178E+00, ...\n 0.4382591473903548E+00, ...\n 0.6234009185462497E+00, ...\n 0.7135250773634121E+00, ...\n 0.6388876835093809E+00, ...\n 0.4509387692675831E+00, ...\n 0.3434156783636982E+00, ...\n 0.4557046121246569E+00, ...\n 0.6196899649456836E+00, ...\n 0.5499893231527195E+00, ...\n 0.3915284435431718E+00, ...\n 0.4963129989673750E+00 ];\n\n x_vec = [ ...\n 0.0E+00, ...\n 0.2E+00, ...\n 0.4E+00, ...\n 0.6E+00, ...\n 0.8E+00, ...\n 1.0E+00, ...\n 1.2E+00, ...\n 1.4E+00, ...\n 1.6E+00, ...\n 1.8E+00, ...\n 2.0E+00, ...\n 2.2E+00, ...\n 2.4E+00, ...\n 2.6E+00, ...\n 2.8E+00, ...\n 3.0E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/fresnel_sin_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7573734161602281}} {"text": "function ph=phase4(cp,mode)\n% PHASE4 4 Quadrant arctangent.\n% PHASE4 provides a 4 quadrant arctangent of a complex number such\n% that -360 < PH <= 0. It also takes care of wrapping when\n% necessary.\n\n% Author: Craig Borghesani\n% Date: 8/17/94\n% Revised: 10/24/94\n% Copyright (c) 1999, Prentice-Hall\n\nph = atan2(imag(cp),real(cp));\n\nif nargin == 1, % normal phase computation for frequency response plots\n\n ph = ph - 2*pi*(ph>1e-5);\n\nelse % unwrap phase values for gain (phase) plot\n\n [r,c] = size(ph);\n for k = 1:c,\n dph = diff(ph(:,k));\n loc_brk = find(abs(dph)>pi);\n if length(loc_brk),\n brks = loc_brk;\n if dph(loc_brk(1)) > 0, brks = [0;brks]; end\n if dph(loc_brk(length(loc_brk))) < 0, brks = [brks;length(ph)]; end\n for k2 = 1:2:length(brks),\n ph((brks(k2)+1):(brks(k2+1)),k) = ph((brks(k2)+1):(brks(k2+1)),k) + 2*pi;\n end\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/38866-controls-tutor/contutor5/phase4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7573293205551914}} {"text": "function A = construct_incidence_matrix(measurements)\n%function A = construct_incidence_matrix(measurements)\n%\n% This function computes and returns the oriented incidence matrix of the\n% underlying directed graph of measurements:\n%\n% A_{ie} = -1, if edge e *leaves* node i,\n% +1, if edge e *enters* node i,\n% 0, otherwise.\n%\n% (see eq. (7) in the paper).\n\n% Copyright (C) 2016 by David M. Rosen\n\nN = max(max(measurements.edges)); % Number of nodes in the pose graph\nM = size(measurements.edges, 1); % Number of edges in the pose graph\n\nout_nodes = measurements.edges(:, 1)'; %out_nodes(e) = i if edge e leaves node i\nin_nodes = measurements.edges(:, 2)'; %out_nodes(e) = j if edge e enters node i\n\nnode_indices = [out_nodes, in_nodes];\nedge_indices = [ [1:M], [1:M] ];\nvals = [-ones(1, M), ones(1, M)];\n\nA = sparse(node_indices, edge_indices, vals, N, M);\n\n\nend\n\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/lib/construct_incidence_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7573293112229309}} {"text": "function zInterp=biquadraticInterp(xyPts,x0,y0,deltaX,deltaY,zGrid)\n%%BIQUADRATICINTERP Biquadratic interpolation is interpolation of a\n% function that depends on two independent variables, by first\n% performing quadratic interpolation across one dimension, and then\n% performing quadratic interpolation across the next dimension. This\n% function assumes that in x and y generating the values in zGrid is\n% uniform.\n%\n%INPUTS: xyPts A 2XnumPts set of [x;y] pairs at which the value of z should\n% be interpolated.\n% x0, y0 These are values of the independent variables corresponding\n% to the entry in zGrid(1,1).\n% deltaX, deltaY The uniform spacings between the independent variables for\n% gridded elements in zGrid. Thus, zGrid(i,j) holds the z\n% value associated with x=x0+deltaX*(i-1) and\n% y=y0+deltaY*(i-1).\n% zGrid A numXXnumY matrix of values of the independent variable\n% for different values of the dependent variables. The first\n% index selects the x value and the second index the y value.\n% numX>=3 and numY>=3.\n%\n%OUTPUTS: zInterp A 1XnumPts vector of interpolated values.\n%\n%Biquadratic interpolation is described in [1]. However, this function does\n%not use the implementation that is given at the end of [1].\n%\n%EXAMPLE:\n%A 2D function is evaluated and plotted. Then, the function is evaluated at\n%a much smaller number of points and those are used to interpolate and plot\n%the function again. The basis points are ploted in black. The\n%small discontinuities between interpolation regions can be seen.\n% numXPts=400;\n% numYPts=401;\n% plotXPts=linspace(-1,1,numXPts);\n% plotYPts=linspace(-1,1,numYPts);\n% z=@(xy)sum(sin(1-(16/15)*xy).^2-(1/50)*sin(4-(64/15)*xy)-sin(1-(16/15)*xy),1);\n% [Y,X]=meshgrid(plotYPts,plotXPts);\n% xy=[X(:).';Y(:).'];\n% Z=reshape(z(xy),[numXPts,numYPts]);\n% \n% figure(1)\n% clf\n% hold on\n% surface(X,Y,Z,'edgeColor','None')\n% \n% %Get a small number of points to use for interpolation and mark the\n% %points on the plot.\n% numXBasis=10;\n% numYBasis=11;\n% x0=-1;\n% y0=-1;\n% xBasis=linspace(x0,1,numXBasis);\n% yBasis=linspace(y0,1,numYBasis);\n% deltaX=xBasis(2)-xBasis(1);\n% deltaY=yBasis(2)-yBasis(1);\n% [YB,XB]=meshgrid(yBasis,xBasis);\n% xyB=[XB(:).';YB(:).'];\n% ZGrid=reshape(z(xyB),[numXBasis,numYBasis]);\n% scatter3(XB(:),YB(:),ZGrid(:),200,'.k')\n% view(25,50)\n% \n% %Now, interpolate the surface using the above basis points.\n% ZInterp=biquadraticInterp(xy,x0,y0,deltaX,deltaY,ZGrid);\n% ZInterp=reshape(ZInterp,[numXPts,numYPts]);\n% \n% %Plot the biquadratically interpolated surface and the control points.\n% figure(2)\n% clf\n% hold on\n% surface(X,Y,ZInterp,'edgeColor','None')\n% scatter3(XB(:),YB(:),ZGrid(:),200,'.k')\n% view(25,50)\n%\n%REFERENCES:\n%[1] D. Smith, \"NOAA technical memorandum NOS NGS 84: Biquadratic\n% interpolation,\" National Oceanic and Atmospheric Administration,\n% National Geodetic Survey, Silver Spring, MD, Tech. Rep., Sep. 2020.\n%\n%July 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumPts=size(xyPts,2);\nzInterp=zeros(1,numPts);\n\nnumX=size(zGrid,1);\nnumY=size(zGrid,2);\n\nfor curPt=1:numPts\n xCur=xyPts(1,curPt);\n yCur=xyPts(2,curPt);\n \n idxX=round((xCur-x0)/deltaX)+1;\n idxY=round((yCur-y0)/deltaY)+1;\n \n %The points cannot be endpoints.\n idxX=idxX+(idxX==1)-(idxX==numX);\n idxY=idxY+(idxY==1)-(idxY==numY);\n \n %First, interpolate across X for each Y.\n x0Cur=x0+deltaX*(idxX-2);\n y0Cur=y0+deltaY*(idxY-2);\n \n zInterp1=quadraticInterpUnif3Pt(xCur,x0Cur,deltaX,zGrid(idxX-1,idxY-1),zGrid(idxX,idxY-1),zGrid(idxX+1,idxY-1));\n zInterp2=quadraticInterpUnif3Pt(xCur,x0Cur,deltaX,zGrid(idxX-1,idxY),zGrid(idxX,idxY),zGrid(idxX+1,idxY));\n zInterp3=quadraticInterpUnif3Pt(xCur,x0Cur,deltaX,zGrid(idxX-1,idxY+1),zGrid(idxX,idxY+1),zGrid(idxX+1,idxY+1));\n \n zInterp(curPt)=quadraticInterpUnif3Pt(yCur,y0Cur,deltaY,zInterp1,zInterp2,zInterp3);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Interpolation/Quadratic_Interpolation/biquadraticInterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7573206773165496}} {"text": "function [y] = l1median_VaZh_z(X, maxiter, tol, zerotol, medIn )\n%To calculate the L1_median of X with the l1median_VaZh method\n%INput:\n% X ---the number of the records is the number of rows\n% maxiter ---the max number of iteration\n% tol ---the tolerance of iteration \n% zerotol ---the tolerance of vector to zero\n% medIn ---a row vector representing initial median of X\n%output:\n% y ---the median of X\n\n %To discuss the parameters\n if (nargin > 5)\n error ('Too many input arguments.') ;\n elseif (nargin < 5)\n medIn = median(X);\n if(nargin < 4)\n zerotol = 1e-15 ;\n if (nargin < 3)\n tol = 1e-9 ;\n if (nargin < 2)\n maxiter = 200 ;\n if (nargin < 1)\n error ('Data matrix X is missing.') ;\n end\n end\n end\n end\n end\n \n [rn,vn] = size(X);\n iterdis = 1;\n iter = 0;\n y = medIn;\n \n %Begin the iteration\n while (iterdis > 0) && (iter < maxiter)\n Tnum=zeros(1,vn);\n R = zeros(1,vn);\n Tden=0;\n yita = 0;\n for i=1:rn\n dist = norm(X(i,:)-y);\n if dist >= zerotol\n Tnum = Tnum + X(i,:)/dist;\n Tden=Tden + 1/dist;\n R = R + (X(i,:)-y)/dist;\n else\n yita = 1;\n end\n end\n\n if Tden == 0\n T=0;\n else\n T=Tnum/Tden;\n end\n\n if norm(R) == 0\n r = 0;\n else\n r = min(1,yita/norm(R));\n end\n\n Ty = (1-r)*T + r*y;\n\n iterdis = norm((Ty-y),1) - tol*norm(y,1);\n iter = iter + 1;\n y=Ty;\n \n end\n\n \n %End the iteration\n \n \n \n \n", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/Strategy/l1median_VaZh_z.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7573206756092519}} {"text": "function [f] = poch(z,n)\n%Pochhammer function (z)n = z(z+1)(z+2)...(z+n-1)\n%\n%usage: f = poch(z,n)\n%\n%tested on version 5.3.1\n%\n% z and n may be complex but must be equal in size.\n%\n%see also: Gamma, Fact\n\n%Paul Godfrey\n%pgodfrey@conexant.com\n%8-24-00\n\nf = gamma(z+n)./gamma(z);\n\np=find(z==0 & n==0);\nif ~isempty(p)\n f(p)=0;\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/978-special-functions-math-library/poch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7573206736045854}} {"text": "function result=cpcr(x,y,varargin)\n\n%CPCR performs a classical principal components regression.\n% First, classical PCA is applied to the predictor variables x (see cpca.m) and \n% k components are retained. Then a multiple linear regression method (see mlr.m)\n% is performed of the response variable y on the k principal components. \n%\n% I/O: result=cpcr(x,y,'k',2);\n%\n% Required input arguments:\n% x : Data matrix of the explanatory variables\n% (n observations in rows, p variables in columns)\n% y : Data matrix of the response variables\n% (n observations in rows, q variables in columns)\n%\n% Optional input argument: \n% k : Number of principal components to compute. If k is missing, \n% a scree plot is drawn which allows to select\n% the number of principal components.\n% plots : If equal to one (default), a menu is shown which allows to draw several plots,\n% such as a score outlier map and a regression outlier map. \n% If 'plots' is equal to zero, all plots are suppressed.\n% See also makeplot.m\n% \n% The output is a structure containing \n%\n% result.slope : Classical slope\n% result.int : Classical intercept\n% result.fitted : Classcial prediction vector\n% result.res : Classical residuals\n% result.sigma : Estimated variance-covariance matrix of the residuals \n% result.rsquared : R-squared value\n% result.k : Number of components used in the regression\n% result.sd : Classical score distances\n% result.od : Classical orthogonal distances\n% result.resd : Residual distances (when there are several response variables).\n% If univariate regression is performed, it contains the standardized residuals.\n% result.cutoff : Cutoff values for the score, orthogonal and residual distances.\n% result.flag : The observations whose orthogonal distance is larger than result.cutoff.od\n% (orthogonal outliers => result.flag.od) and/or whose residual distance is \n% larger than result.cutoff.resd (bad leverage points/vertical outliers => result.flag.resd)\n% can be considered as outliers and receive a flag equal to zero (=> result.flag.all).\n% The regular observations, including the good leverage points, receive a flag 1.\n% result.class : 'CPCR'\n% result.cpca : Full output of the classical PCA part (see cpca.m)\n%\n% This function is part of LIBRA: the Matlab Library for Robust Analysis,\n% available at: \n% http://wis.kuleuven.be/stat/robust.html\n%\n% Written by S. Verboven\n% Last Update: 05/04/2003 \n\ndefault=struct('plots',1,'k',0);\nlist=fieldnames(default);\noptions=default;\nIN=length(list);\ni=1; \ncounter=1;\nif nargin>2\n %\n % placing inputfields in array of strings\n %\n for j=1:nargin-2\n if rem(j,2)~=0\n chklist{i}=varargin{j};\n i=i+1;\n end\n end \n % Checking which default parameters have to be changed\n % and keep them in the structure 'options'.\n while counter<=IN \n index=strmatch(list(counter,:),chklist,'exact');\n if ~isempty(index) % in case of similarity\n for j=1:nargin-2 % searching the index of the accompanying field\n if rem(j,2)~=0 % fieldnames are placed on odd index\n if strcmp(chklist{index},varargin{j})\n I=j;\n end\n end\n end\n options=setfield(options,chklist{index},varargin{I+1});\n index=[];\n end\n counter=counter+1;\n end\nend\n\n\n%classical PCA\nif options.k==0\n out.cpca=cpca(x,'plots',0);\nelse\n out.cpca=cpca(x,'plots',0,'k',options.k);\nend\n%model with intercept \nT=[out.cpca.T(:,1:out.cpca.k) ones(size(out.cpca.T,1),1)];\n%Multivariate linear regression\nout.a=inv(T'*T)*T'*y;\nout.fitted=T*out.a;\nlen=size(out.a,1);\np=size(T,2);\nq=size(y,2);\ngeg=[T,y];\n[n,m]=size(geg);\nS=cov(geg);\nSx=S(1:p-1,1:p-1);\nSxy=S(1:p-1,p+1:m);\nSyx=Sxy';\nSy=S(p+1:m,p+1:m);\nSe=Sy-out.a(1:p-1,1:q)'*Sx*out.a(1:p-1,1:q); %variance of errors\n%regression coefficients slope and intercept ([\\beta \\alpha])\nout.coeffs=[out.cpca.P(:,1:out.cpca.k)*out.a(1:len-1,:); out.a(len,:)-out.cpca.M*out.cpca.P(:,1:out.cpca.k)*out.a(1:len-1,:)]; %%coefficients in the original space;\nout.slope=out.cpca.P(:,1:out.cpca.k)*out.a(1:len-1,:);\nout.int=out.a(len,:)-out.cpca.M*out.cpca.P(:,1:out.cpca.k)*out.a(1:len-1,:);\nout.res=y-out.fitted;\nout.sigma=Se;\nif q==1\n out.stdres=out.res./sqrt(diag(out.sigma));\nend\nout.k=out.cpca.k;\nSTTm=sum((y-repmat(mean(y),length(y),1)).^2);\nSSE=sum(out.res.^2);\nout.rsquared=1-SSE/STTm;\nout.class='CPCR';\n\n%calculating residual distances\nif q>1\n if (-log(det(Se)/(m-1)))>50\n out.resd='singularity';\n else\n cen=zeros(q,1);\n out.resd=sqrt(libra_mahalanobis(out.res,cen','cov',Se))';\n end\nelse % q==1\n out.resd=out.stdres; %standardized residuals \nend\nout.cutoff=out.cpca.cutoff;\nout.cutoff.resd=sqrt(chi2inv(0.975,size(y,2)));\n%computing flags\nout.flag.od=out.cpca.flag.od;\nout.flag.sd=out.cpca.flag.sd;\nout.flag.resd=abs(out.resd)<=out.cutoff.resd;\nout.flag.all=(out.flag.od & out.flag.resd);\n\nresult=struct( 'slope',{out.slope}, 'int',{out.int},'fitted',{out.fitted},'res',{out.res},...\n 'cov',{out.sigma},'rsquared',{out.rsquared},...\n 'k',{out.k},'sd', {out.cpca.sd},'od',{out.cpca.od},'resd',{out.resd},...\n 'cutoff',{out.cutoff},'flag',{out.flag},'class',{out.class},...\n 'cpca',{out.cpca});\n\ntry\n if options.plots\n makeplot(result)\n end\ncatch %output must be given even if plots are interrupted \n %> delete(gcf) to get rid of the menu \n end\n ", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/LIBRA/cpcr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7573075775256817}} {"text": "%% Distributed Marginal Value-at-Risk Simulation\n% This example uses the Parallel Computing Toolbox(TM) to perform a Monte\n% Carlo simulation of a number of stocks in a portfolio. At a given\n% confidence level, we predict the value at risk (VaR) of the portfolio as\n% well as the marginal value at risk (mVaR) of each of the stocks in the\n% portfolio. We also provide confidence intervals for our estimates.\n%\n% Copyright 2007-2012 The MathWorks, Inc. \n% Adapted and simplified in 2013 by Michael Weidman, Quantitative Support\n% Services, Ltd.\n\n%% 1. Open a pool of MATLAB workers and load input data\n\nif matlabpool('size') == 0\n matlabpool open\nend\n\nload pctdemo_data_mvar\n\n%% 2. Define Parameters\n\nnSims = 1e5;\nrelativeWeights = [1 1 2 2 1 3 2]/12;\ntime = 50;%(10:1:50)';\nconfLevel = 95;\n\nnTimes = length(time);\nnAssets = size(stock,2);\n\n%% 3. Estimate asset moments\n\nreturns = (stock(2:end,:) - stock(1:end-1,:)) ./ stock(1:end-1,:);\nexpReturns = mean(returns);\nexpCovariances = cov(returns);\n\n%% 4. Simulate asset prices\n\ntic\n\nsimPrices = zeros(nTimes, nAssets, nSims); \nportPrices = zeros(nTimes, 1, nSims);\nprice0 = stock(end,:);\nportPrice0 = price0 * relativeWeights';\n\nparfor iSim = 1:nSims\n simPrices( :,:,iSim) = simulatePrices(expReturns, expCovariances, ...\n price0, time);\n portPrices(:,:,iSim) = sum(bsxfun(@times, simPrices(:,:,iSim), ...\n relativeWeights), 2);\nend\n\ntoc\n\n%% 5. Calculate mVaR and VaR\n\nsimRelativeLosses = bsxfun(@rdivide, ...\n bsxfun(@minus, price0, simPrices), price0);\nsimRelativePortLosses = bsxfun(@minus, portPrice0, portPrices) ...\n ./ portPrice0;\n\nmVaR = prctile(simRelativeLosses , confLevel, 3);\nVaR = prctile(simRelativePortLosses, confLevel, 3);\n\n%% 6. Plot the Results\n\nplotMVAR(VaR, mVaR, time, names);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43577-speeding-up-algorithms-when-parallel-computing-and-gpus-do-and-dont-accelerate/MVAR/MVAR_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7572955140233226}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n% N- point IDFTs of a 4-point sequence \n\n\n\nX=[10 -2+2j -2 -2-2j];\n\n% 4-point IDFT \nifft(X)\n\n% 4-point IDFT \nidft(X)\n\n% 6-point IDFT \nifft(X,6)\n\n% 6-point IDFT \nX(6)=0\nifft(X)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/7/c79c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7572519916099717}} {"text": "function point_num = sphere_icos_point_num ( factor )\n\n%*****************************************************************************80\n%\n%% SPHERE_ICOS_POINT_NUM sizes an icosahedral grid on a sphere.\n%\n% Discussion:\n%\n% With FACTOR = 1, the grid has 20 triangular faces, 30 edges, and 12 nodes.\n%\n% With FACTOR = 2, each triangle of the icosahedron is subdivided into\n% 2x2 subtriangles, resulting in 80 faces, 120 edges, and \n% 42 = 12 + 20 * 3 * (1)/2 + 20 * 0 ) nodes.\n%\n% With FACTOR = 3, each triangle of the icosahedron is subdivided into\n% 3x3 subtriangles, resulting in 180 faces, 270 edges, and \n% 92 ( = 12 + 20 * 3 * (2)/2 + 20 * 1 ) nodes.\n%\n% In general, each triangle is subdivided into FACTOR*FACTOR subtriangles,\n% resulting in 20 * FACTOR * FACTOR faces, 30 * FACTOR * FACTOR edges, and\n% 12 \n% + 20 * 3 * (FACTOR-1) / 2 \n% + 20 * (FACTOR-2) * (FACTOR-1) / 2 nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer FACTOR, the subdivision factor, which must\n% be at least 1.\n%\n% Output, integer POINT_NUM, the number of nodes.\n%\n point_num = 12 ...\n + 10 * 3 * ( factor - 1 ) ...\n + 10 * ( factor - 2 ) * ( factor - 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/sphere_grid/sphere_icos_point_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7572519877894844}} {"text": "function xfat = r8vec_expand_linear ( n, x, fat )\n\n%*****************************************************************************80\n%\n%% R8VEC_EXPAND_LINEAR linearly interpolates new data into a vector.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 October 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of input data values.\n%\n% Input, real X(N), the original data.\n%\n% Input, integer FAT, the number of data values to interpolate\n% between each pair of original data values.\n%\n% Output, real XFAT((N-1)*(FAT+1)+1), the \"fattened\" data.\n%\n k = 0;\n\n for i = 1 : n-1\n\n k = k + 1;\n xfat(k) = x(i);\n\n for j = 1 : fat\n k = k + 1;\n xfat(k) = ( ( fat - j + 1 ) * x(i) ...\n + ( j ) * x(i+1) ) ...\n / ( fat + 1 );\n end\n\n end\n\n k = k + 1;\n xfat(k) = x(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/interp/r8vec_expand_linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7571893255021324}} {"text": "function t = tvec_even_bracket2 ( nt, theta1, theta2 )\n\n%*****************************************************************************80\n%\n%% TVEC_EVEN_BRACKET2 computes an evenly spaced set of angles between THETA1 and THETA2.\n%\n% Example:\n%\n% NT = 5\n% THETA1 = 30\n% THETA2 = 90\n%\n% T = ( 40, 50, 60, 70, 80 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NT, the number of values to compute.\n%\n% Input, real THETA1, THETA2, the limiting angles.\n%\n% Output, real TVEC(NT), the evenly spaced angles.\n%\n for i = 1 : nt\n t(i) = ( ( nt + 1 - i ) * theta1 ...\n + ( i ) * theta2 ) ...\n / ( nt + 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/stroud/tvec_even_bracket2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7571893194926421}} {"text": "function [ code, itree, more ] = tree_parent_next ( nnode, more )\n\n%*****************************************************************************80\n%\n%% TREE_PARENT_NEXT generates, one at a time, all labeled trees.\n%\n% Discussion:\n%\n% The routine also returns the corresponding Pruefer codes.\n%\n% There are N^(N-2) labeled trees on N nodes (Cayley's formula).\n%\n% The number of trees in which node I has degree D(I) is the\n% multinomial coefficient: ( N-2; D(1)-1, D(2)-1, ..., D(N)-1 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 June 2013\n%\n% Parameters:\n%\n% Input, integer NNODE, the number of nodes to be used in \n% the trees.\n%\n% Output, integer CODE(NNODE). The first NNODE-2 entries \n% of CODE contain the Pruefer code for the given labeled tree.\n%\n% Output, integer ITREE(NNODE). The first NNODE-1 entries \n% of ITREE describe the edges that go between the nodes. Each pair\n% (I, ITREE(I)) represents an edge. Thus if ITREE(5) = 3,\n% there is an edge from node 3 to node 5.\n%\n% Input/output, logical MORE. On the first call only, the\n% user is required to set MORE = .FALSE. Then call the routine, and\n% it will return information about the first tree\n% as well as setting MORE to the value .TRUE.\n% Keep calling to get another tree until MORE is .FALSE.\n% on return, at which point there are no more trees.\n%\n persistent iarray;\n\n if ( ~ more )\n iarray = [];\n end\n\n [ iarray, more ] = vec_next ( nnode-2, nnode, iarray, more );\n \n code(1:nnode-2) = iarray(1:nnode-2) + 1;\n \n itree = pruefer_to_tree_2 ( nnode, code );\n \n return\nend\n", "meta": {"author": "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_parent_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7571893087329089}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n %% ONEVSALL trains multiple logistic regression classifiers and returns all\n %the classifiers in a matrix all_theta, where the i-th row of all_theta \n %corresponds to the classifier for label i\n % [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n % logisitc regression classifiers and returns each of these classifiers\n % in a matrix all_theta, where the i-th row of all_theta corresponds \n % to the classifier for label i\n\n % Some useful variables\n n = size(X, 1);\n d = size(X, 2);\n \n % You need to return the following variables correctly \n all_theta = zeros(num_labels, d + 1);\n\n % Add ones to the X data matrix\n X = [ones(n, 1) X];\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: You should complete the following code to train num_labels\n % logistic regression classifiers with regularization\n % parameter lambda. \n %\n % Hint: theta(:) will return a column vector.\n %\n % Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n % whether the ground truth is true/false for this class.\n %\n % Note: For this assignment, we recommend using fmincg to optimize the cost\n % function. It is okay to use a for-loop (for c = 1:num_labels) to\n % loop over the different classes.\n %\n % fmincg works similarly to fminunc, but is more efficient when we\n % are dealing with large number of parameters.\n %\n % Example Code for fmincg:\n %\n % % Set Initial theta\n % initial_theta = zeros(n + 1, 1);\n % \n % % Set options for fminunc\n % options = optimset('GradObj', 'on', 'MaxIter', 50);\n % \n % % Run fmincg to obtain the optimal theta\n % % This function will return theta and the cost \n % [theta] = ...\n % fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n % initial_theta, options);\n %\n \n % for optimization of theta\n options = optimset('GradObj', 'on', 'MaxIter', 50);\n \n % for each class label\n for k = 1 : num_labels\n \n % initialize theta, and minimize value for cost function\n init_theta = zeros(d + 1, 1);\n theta = fmincg(@(t)(lrCostFunction(t, X, (y == k), lambda)), ...\n init_theta, options);\n all_theta(k, :) = theta';\n end\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/1-multiclass/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7571736453789828}} {"text": "% MAHAL2CONF - Translates a Mahalanobis distance into a confidence\n% interval. Consider a multivariate Gaussian\n% distribution of the form\n%\n% p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C)))\n%\n% where MD(x, m, P) is the Mahalanobis distance from x\n% to m under P:\n%\n% MD(x, m, P) = (x - m) * P * (x - m)'\n%\n% A particular Mahalanobis distance k identifies an\n% ellipsoid centered at the mean of the distribution.\n% The confidence interval associated with this ellipsoid\n% is the probability mass enclosed by it.\n%\n% If X is an d dimensional Gaussian-distributed vector,\n% then the Mahalanobis distance of X is distributed\n% according to the Chi-squared distribution with d\n% degrees of freedom. Thus, the confidence interval is\n% determined by integrating the chi squared distribution\n% up to the Mahalanobis distance of the measurement.\n%\n% Usage:\n% \n% c = mahal2conf(m, d);\n%\n% Inputs:\n%\n% m - the Mahalanobis radius of the ellipsoid\n% d - the number of dimensions of the Gaussian distribution\n%\n% Outputs:\n%\n% c - the confidence interval, i.e., the fraction of\n% probability mass enclosed by the ellipsoid with the\n% supplied Mahalanobis distance\n%\n% See also: CONF2MAHAL\n\n% Copyright (C) 2002 Mark A. Paskin\n%\n% This program is free software; you can redistribute it 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, 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%\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\n% USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction c = mahal2conf(m, d)\n\nc = chi2cdf(m, d);", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/KPMtools/mahal2conf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7571554422255099}} {"text": "function [varargout] = cubic_cubic_integrated_distance( ...\n x, ...\n y, ...\n g_C, ...\n h_C, ...\n P, ...\n g_D, ...\n h_D, ...\n Q)\n %\n % [E] = cubic_cubic_integrated_distance( x, y, g_C, h_C, P, g_D, h_D, Q)\n % [H,F,c] = cubic_cubic_integrated_distance( x, y, g_C, h_C, P, g_D, h_D)\n %\n % E = ½ ∫ₓʸ ‖ C( g_C u + h_C ) - D( g_D u + h_D ) ‖² du\n %\n % where C's control points are in rows of P and D's control points are in rows\n % of Q.\n %\n % E = 0.5*trace(Q.'*H*Q) + trace(Q.'*F) + c;\n % \n % That is, \n % Q★ = argmin_Q E(Q) \n % Q★ = H⁻¹ F\n % \n % Where\n %\n % C(T) = (1-T)³ Pᵢ⁰ + 3(1-T)²T Pᵢ¹ + 3(1-T)T² Pᵢ² + T³ Pᵢ³\n % D(T) = (1-T)³ Qᵢ⁰ + 3(1-T)²T Qᵢ¹ + 3(1-T)T² Qᵢ² + T³ Qᵢ³\n %\n % Inputs:\n % x starting value of integral 0≤x<1\n % y ending value of integral x=0);\n assert(x<1);\n assert(y>=x);\n assert(y<=1);\n end\n dim = size(P,2);\n\n % https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature\n % n is number of points\n % 2n-1 order polynomial is integrated exactly\n % ↓\n % n = 4\n\n % https://people.sc.fsu.edu/~jburkardt/datasets/quadrature_rules/quadrature_rules.html\n % n=4 Gauss-Legendre quadrature on [-1,1]\n w = [\n 0.347854845137453857373063949222\n 0.652145154862546142626936050778\n 0.652145154862546142626936050778\n 0.347854845137453857373063949222\n ];\n a = [\n -0.861136311594052575223946488893\n -0.339981043584856264802665759103\n 0.339981043584856264802665759103\n 0.861136311594052575223946488893\n ];\n % Move to [x,y] range.\n u = (0.5*a + 0.5)*(y-x)+x;\n % Adjust weights.\n w = ((y-x)/(1- -1))*w;\n\n % Evaluate C at quadrature points\n C = cubic_eval( P, g_C*u + h_C);\n\n\n % Map quadrature points to D's direct paramter space\n T = g_D * u + h_D;\n\n if nargout<=1\n % Compute energy directly. This is faster. Better be the same as below.\n % \n % It's ever so slightly different (between 1e-16 and 1e-20)\n E = 0.5*sum(w.*(C - cubic_eval( Q, T)).^2,'all');\n varargout{1} = E;\n return;\n end\n \n % Stack bezier basis matrices for each evaluation point\n M = [(1-T).^3 3*T.*(1-T).^2 3*T.^2.*(1-T) T.^3];\n\n W = diag(w);\n\n H = M.'*W*M;\n assert(all(size(H) == [4 4]));\n F = -M.'*W*C;\n assert(size(F,1) == 4);\n assert(size(F,2) == dim);\n\n c = 0.5*trace(C.'*W*C);\n\n if isempty(Q)\n warning(\"Cant compute energy on empty Q\");\n E = [];\n else\n % Actually compute energy\n E = 0.5*trace(Q.'*H*Q) + trace(Q.'*F) + c;\n end\n\n varargout{1} = H;\n varargout{2} = F;\n varargout{3} = c;\n varargout{4} = E;\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/cubic_cubic_integrated_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7571554370210909}} {"text": "function A = sllinreg(X, Y, varargin)\n%SLLINREG Performs Multivariate Linear Regression and Ridge Regression\n%\n% $ Syntax $\n% - A = sllinreg(X, Y, ...)\n%\n% $ Arguments $\n% - X: The matrix of x samples\n% - Y: The matrix of y samples\n% - A: The solved transform matrix\n%\n% $ Description $\n% - A = sllinreg(X, Y, varargin) solves the linear regression problem to\n% get the linear transforms A: (y = Ax + e). The solution is given by \n% the following optimization problem:\n% A = argmin_{A} sum_i ||y_i - A x_i||^2 + sum_k lambda_k ||a_k||^2\n% Here, Y is a dy x n matrix with the i-th column giving y_i; \n% X is a dx x n matrix with the i-th column giving x_i\n% A is a dy x dx transform matrix\n% a_k is the k-row vector of A, which corresponds to the k-th \n% component of y\n% lambda_k is the regularization weight in ridge regression\n% According to mathematical analysis, the solution is given as\n% A = (Y * X^T) * (X * X^T + diag(lambda))^{-1}\n% You can specify the following properties to control the regression:\n% \\*\n% \\t Table Linear Regression Properties\n% \\h name & description\n% 'lambdas' & The regularization coefficients in ridge \n% linear regression. If all components share\n% the same value, then lambdas can be a scalar.\n% If different values are for different \n% dimensions, then lambdas can be a dy x 1 \n% column vector. (default = 0)\n% 'weights' & The sample weights, can be either [] or\n% an 1 x n row vector.\n% 'invparams' & The parameters for invoking slinvcov to \n% compute inverse matrix, in the form of\n% {method, ...}. default = [], means directly\n% using inv to do inverse.\n% \\*\n%\n% $ Remarks $\n% - To solve the linear problem like y = Ax + b, you have two ways:\n% (1) centralize x and y respectively, and invoke sllinreg, then set\n% b = my - A * mx\n% (2) invoke sllinrega, which is specially designed for such an\n% augmented problem.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 15, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n raise_lackinput('sllinreg', 2);\nend\n\nif ~isnumeric(X) || ~isnumeric(Y) || ndims(X) ~= 2 || ndims(Y) ~= 2\n error('sltoolbox:invalidarg', ...\n 'The X and Y should be both 2D numeric matrices');\nend\n\n[dx, n] = size(X);\n[dy, ny] = size(Y);\nif n ~= ny\n error('sltoolbox:sizmismatch', ...\n 'X and Y contain different numbers of samples');\nend\n\nopts.lambdas = 0;\nopts.rv = 1e-3;\nopts.weights = [];\nopts.invparams = [];\nopts = slparseprops(opts, varargin{:});\n\nlambdas = opts.lambdas;\nif ~isscalar(lambdas) && ~isequal(size(lambdas), [dy, 1])\n error('lambdas should be either a scalar or a dy x 1 column vector');\nend\n\nw = opts.weights;\nif ~isempty(w)\n if ~isequal(size(w), [1, n])\n error('The sample weights should be a 1 x n row vector');\n end\nend\n\n\n%% main\n\nif isempty(w)\n Xt = X';\nelse\n Xt = slmulvec(X, w, 2)';\nend\n\nM2 = X * Xt; \nif ~isequal(lambdas, 0)\n inds = (1:dx)' * (dx+1) - dx;\n M2(inds) = M2(inds) + lambdas;\nend\n\nif isempty(opts.invparams)\n invM2 = inv(M2);\nelse\n invM2 = slinvcov(M2, opts.invparams{:});\nend\nclear M2;\n\nM1 = Y * Xt;\n\nA = M1 * invM2;\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/regression/sllinreg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7571554354745431}} {"text": "function [y, sigma, p] = linRegPred(model, X, t)\n% Compute linear regression model reponse y = w'*X+w0 and likelihood\n% Input:\n% model: trained model structure\n% X: d x n testing data\n% t (optional): 1 x n testing response\n% Output:\n% y: 1 x n prediction\n% sigma: variance\n% p: 1 x n likelihood of t\n% Written by Mo Chen (sth4nth@gmail.com).\nw = model.w;\nw0 = model.w0;\ny = w'*X+w0;\n%% probability prediction\nif nargout > 1\n beta = model.beta;\n if isfield(model,'U')\n U = model.U; % 3.54\n Xo = bsxfun(@minus,X,model.xbar);\n XU = U'\\Xo;\n sigma = sqrt((1+dot(XU,XU,1))/beta); % 3.59\n else\n sigma = sqrt(1/beta)*ones(1,size(X,2));\n end\nend\n\nif nargin == 3 && nargout == 3\n p = exp(-0.5*(((t-y)./sigma).^2+log(2*pi))-log(sigma));\nend\n\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter03/linRegPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7571554214078328}} {"text": "% Implement a simple version of \"Geodesics in Heat\" by Crane et al. 2013\n\nclc; clear all; close all;\n[V,F] = readOBJ('../data/spot.obj');\n[V,F,S] = loop(V,F,2); % upsample the mesh to see the speed difference\nuse_prefactorization = true; % set it to \"true\" or \"false\" to see speed difference\n\n% precompute matrices\nA = massmatrix(V,F);\nLc = cotmatrix(V,F);\nt = avgedge(V,F)^2;\nLHS = A - t*Lc;\nG = grad(V,F); % #F*dim by #V\nD = div(V,F); % #V by #F*dim\n\n% prefactorization\npreLHS = decomposition(LHS);\npreLc = decomposition(Lc);\n\n%% change heat source\nheatSrcIdx = 1;\n\ntic;\n\n% step 1\ndelta = zeros(size(V,1),1);\ndelta(heatSrcIdx) = 1;\nif use_prefactorization\n u = preLHS \\ delta;\nelse \n u = LHS \\ delta;\nend\n\n% step 2\ngradu = G*u;\ngradu = reshape(gradu, size(F,1), 3);\ngradu_normalized = gradu ./ normrow(gradu);\nX = -gradu_normalized;\n\n% step 3\ndivX = D * reshape(X, size(F,1)*3, 1);\nif use_prefactorization\n phi = preLc \\ divX;\nelse\n phi = Lc \\ divX;\nend\nphi = phi - phi(heatSrcIdx);\n\ntoc;\n\n%% visualization\ntsurf(F,V, 'CData', phi); \naxis equal;\nCM = cbrewer('Reds', 500);\nCM = CM(size(CM,1):-1:1,:);\ncolormap(CM);\ncolorbar\nshading interp\ndrawnow \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/101_decomposition/exercise/demo_decomposition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7569967057982401}} {"text": "function [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\n\n return\nend\n", "meta": {"author": "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/sgqf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7569403764502278}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\nJ = 1/(2*m)*sum((X*theta-y).^2)+lambda/(2*m)*(sum(theta.^2)-theta(1).^2);\n \ngrad = 1/m*X'*(X*theta-y)+lambda/m*theta;\ngrad(1) = grad(1) -lambda/m*theta(1);\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\n\n\n\n\n\n\n\n\n\n\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "Ayatans", "repo": "Machine-Learning-homework", "sha": "4550cfc0426c9da8072dff165130fff40d138c10", "save_path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework", "path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework/Machine-Learning-homework-4550cfc0426c9da8072dff165130fff40d138c10/machine-learning-ex5/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367526, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7569395919078435}} {"text": "function value = u_integral ( e )\n\n%*****************************************************************************80\n%\n%% U_INTEGRAL: integral ( -1 <= x <= +1 ) x^e sqrt ( 1 - x^2 ) dx.\n%\n% Discussion:\n%\n% E U_INTEGRAL\n% -- -------------- \n% 0 pi / 2 \n% 2 pi / 8\n% 4 pi / 16\n% 6 5 * pi / 128\n% 8 7 * pi / 256\n% 10 21 * pi / 1024\n% 12 33 * pi / 2048\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, integer E, the exponent of X.\n% 0 <= E.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( mod ( e, 2 ) == 1 )\n\n value = 0.0;\n\n else\n\n arg1 = 0.5 * ( 1 + e );\n arg2 = 2.0 + 0.5 * e;\n value = 0.5 * sqrt ( pi ) * gamma ( arg1 ) / gamma ( arg2 );\n\n end\n\n return\nend\n", "meta": {"author": "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/u_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7569395820994944}} {"text": "function v=scatterquad2(x,y,z)\n% SCATTERQUAD2 - calculates the volume under a surface defined by scattered points\n%\n% Usage:\n% v = scatterquad2(x,y,z)\n%\n% Inputs:\n% X,Y,Z are vectors of equal size specifying the coordinates of the points\n% defining the surface. Z can also be a scalar or a function handle accepting\n% two inputs.\n%\n% Outputs:\n% V is the volume under the surface defined by linear interpolation of Z on\n% the Delaunay triangulation of the points (X(i),Y(i)), assuming that z=0\n% outside the convex hull of the points (X(i),Y(i)).\n%\n% Method:\n% The linear interpolation is a linear combination of basis functions of the\n% form z=t if (x,y) is in triangle T such that \n% (x,y)=r*(u1,v1)+s*(u2,v2)+t*(u3,v3) where r+s+t=1 (all non-negative) and\n% (u,v) are the vertices of T, or z=0 otherwise. The integral of z is\n% (1/3)*Area(T) where the area of T is determined by the cross product of two\n% edge vectors.\n%\n% Examples:\n% load seamount\n% scatterquad2(x,y,z-min(z)) % returns 190.7996\n% inR = (x>=211.1 & x<=211.4 & y>=-48.35 & y<=-48);\n% scatterquad2(x,y,(z-min(z)).*inR) % returns 142.3083\n% scatterquad2(x,y,1) % returns 0.2696\n%\n% For functions that can be evaluated at arbitrary points, use DBLQUAD or\n% QUAD2D. For regular grids, use TRAPZ twice.\n\nif nargin<3\n error('scatterquad2:nargin','Expect 3 input arguments');\nelseif ~isnumeric(x) || ~isnumeric(y)\n error('scatterquad2:xytype','Inputs X and Y must be numeric');\nelseif ~isequal(numel(x),numel(y))\n error('scatterquad2:xysize','Inputs X and Y must have same number of elements');\nelseif numel(x)<3\n error('scatterquad2:xsize','Inputs X and Y must have at least 3 elements');\nelseif ~isnumeric(z)\n if isa(z,'function_handle')\n try\n z=z(x,y);\n if ~isnumeric(z)\n error('scatterquad2:zftype','Input Z failed to return a numeric array');\n end;\n catch ME\n error('scatterquad2:zfeval','Input Z failed to evaluate at (X,Y)');\n end;\n else\n error('scatterquad2:ztype','Input Z must be numeric or a function handle');\n end;\nend;\n\nif ~isequal(numel(z),numel(x))\n if numel(z)==1\n z=repmat(z,numel(x),1);\n else\n error('scatterquad2:zsize','Input Z must be scalar or the same size as X and Y');\n end;\nend;\n\nDT=DelaunayTri(x,y);\ni=DT(:,1);\nj=DT(:,2);\nk=DT(:,3);\nA=abs((x(j)-x(i)).*(y(k)-y(i))-(y(j)-y(i)).*(x(k)-x(i)))/2; % area of triangles\nv=sum((z(i)+z(j)+z(k)).*A)/3;\n\nend % main function scatterquad2(...)\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31805-scatterquad2/scatterquad2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7569395762675064}} {"text": "function [ p, Fstat, df1, df2 ] = ftest(n,np1,np2,chi1,chi2)\n% [ p ] = ftest(n,np1,np2,chi1,chi2)\n% function to test whether addition of model parameters to \n% fit data is warranted by level of misfit improvement\n%\n% Inputs \n% n = # of data\n% np1, np2 = number of free parameters for each fit.\n% chi1 & chi2 = sum of squares of misfits for two models.\n% must be positive values\n% normalization of chis by n not required\n% (normalization divides out in Fstatistic)\n%\n% Outputs\n% p = probability (between 0 - 1) that improvement to fit from \n% addition of parameters is due to chance. I.e.,\n% 0 means certainty that extra parameters are warranted\n% 1 means improvement undoubtedly attributable to chance\n% If desired, will also return F-statistic (Fstat) and\n% degrees of freedom (df1, df2) for f-distribution\n%\n% Written by James Conder, Southern Illinois University, Oct. 2010\n% Citation:\n% Anderson, K.B. & Conder, J.A., Discussion of Multicyclic Hubbert \n% Modeling as a Method for Forecasting Future Petroleum Production, \n% Energy & Fuels, dx.doi.org/10.1021/ef1012648, 2011\n%\n% Update June, 2011\n% Check added for df1=1 (giving -Inf). Use MatrixLabs approximation\n% for f when df1=1. Accuracy ok, but some small differences against\n% fcdf\n%\n% Update May 31, 2012\n% Allow Fstat, df1, & df2 as outputs.\n% Use fcdf from matlab statistics toolbox if available (fast)\n% Some cosmetic clean up \n%\n% Comments & questions should be directed to conder@siu.edu\n%----------------------\n\n\n%%% check ordering. np2 should be > np1 and chi2 should be < chi1\n% i.e., second model should have more parameters and better fit\nif np2 == np1\n disp('number of model parameters are the same in both cases!')\n p = 1;\n return\nelseif np2 < np1 % np1 should be less than np2. If not, just swap.\n nptemp = np1; np1 = np2; np2 = nptemp;\n chitemp = chi1; chi1 = chi2; chi2 = chitemp;\nend\n\nif chi2 >= chi1\n disp('misfit higher for model with more parameters!')\n p = 1;\n return\nend\n\n%%% number of degrees of freedom for f-distribution\ndf1 = np2 - np1;\t\t% number of degrees of freedom\ndf2 = n - np2 - 1;\n\n%%% F-statistic\nFstat = df2*(chi1 - chi2)/(df1*chi2);\n\n\n%%% find p by determination of cumulative f-distribution at Fstat\n% first check if fcdf from matlab statistics toolbox is present (fast).\n% if not, numerically integrate f-distribution.\n% cdff is equivalent to result from fcdf in Matlab statistics package.\n\nif exist('fcdf.m','file') == 2 % check for availability of fcdf from statistics toolbox\n p = 1 - fcdf(Fstat,df1,df2);\nelse\n if df1 ~= 1 % numerically integrate f-distribution\t\t\n ifpt = 1000001; % large number of slices for accurate numerical integration\n dx = Fstat/(ifpt-1);\n x = 0:dx:1.2*Fstat;\n\n fnumgam = gammaln((df1+df2)/2);\t\t% gamma func factors can be very large, use ln\n fdengam = gammaln(df1/2) + gammaln(df2/2);\n fgam = exp(fnumgam - fdengam);\n\n fnum = fgam*((df1/df2)^(df1/2)).*(x.^(0.5*df1 -1));\n fden = ((1 + df1*x/df2).^(0.5*(df1+df2)));\n f = fnum./fden;\t% f distribution for df1, df2\n %fF = f(ifpt);\t\t% f at Fstat\n\n cdff = cumsum(f)*dx;\t% numerical integration of f distribution\n p = 1 - cdff(ifpt);\n else % when df1=1 use F-dist approximation from MatrixLabs to avoid -Inf\n if Fstat <= 0.5 % Compute using inverse for small F-values\n s = df2;\n t = df1;\n z = 1/Fstat;\n else\n s = df1;\n t = df2;\n z = Fstat;\n end\n j = 2/(9*s);\n k = 2/(9*t); \n\n % Use approximation formulas\n y = abs((1 - k)*z^(1/3) - 1 + j)/sqrt(k*z^(2/3) + j);\n if t < 4\n y = y*(1 + 0.08*y^4/t^3);\n end \n\n a1 = 0.196854;\n a2 = 0.115194;\n a3 = 0.000344;\n a4 = 0.019527;\n p = 0.5/(1 + y*(a1 + y*(a2 + y*(a3 + y*a4))))^4;\n\n % Adjust if inverse was computed\n if Fstat <= 0.5\n p = 1 - p;\n end \n end\nend\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41775-f-test/ftest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7569034470651562}} {"text": "function K = besselk_correlation ( s, t )\n\n%*****************************************************************************80\n%\n%% BESSELK_CORRELATION evaluates the Bessel K correlation function.\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, real S(*), T(*), pairs of argument values.\n%\n% Output, real K(*), the correlation function values\n%\n K = ones ( size ( s ) );\n\n i = find ( s ~= t );\n K(i) = abs ( s(i) - t(i) ) .* besselk ( 1, abs ( s(i) - t(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/correlation_chebfun/besselk_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213880824791, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7569034426962541}} {"text": "function [A,B,h,k,phi]=polyEllipsForm2ScalRotTrans(coeffs)\n%%POLYELLIPSFORM2SCALROTTRANS Given a 2D ellipse represented as a quadratic\n% polynomial such that f(x,y)=0 is points on the ellipse, this function\n% obtains the parameterization for a parameteric representation of the\n% points in terms of scale factors (A, and B), a rotation angle (phi) and\n% translation coordinates (h, and k). Thus, if t is a parameteric\n% parameter that runs from 0 to 2*pi, x and y coordinates of points on\n% the ellipse are given by\n% x=A*cos(phi)*cos(t)-B*sin(phi)*sin(t)+h;\n% y=A*sin(phi)*cos(t)+B*cos(phi)*sin(t)+k;\n%\n%INPUTS: coeffs A 3X3 matrix of the coefficients for the bivariate\n% quadratic polynomial. These are arranged such\n% that coeffs(a1,a2) corresponds to the coefficient\n% of an x1^(a1-1)*x2^(a2-1) term. This is the format used in\n% polyValMultiDim.\n%\n%OUTPUTS: A, B The scalar positive scale factors.\n% h, k The scalar offsets in the x and y coordinates.\n% phi The scalar rotation angle in radians.\n%\n%The relations here come from inverting Equation 5 in [1]. Using the\n%notation of [1], we note that we can write BB=(1/A2-1/B2)*sin(2*phi)\n%and also AA-CC==(1/A^2-1/B^2)*cos(2*phi), so we use an inverse transgent to\n%find phi. After that, the other terms are found by substituting and\n%solving each of the equations. In the final equation for FF, we repalce\n%the 1 with a c that we solve for. That is a scale factor (since one can\n%multiply coeffs by any constant without changing the result). Given the\n%scale factor, we then replace A with A/sqrt(c) and B with B/sqrt(c) to\n%undo the scaling.\n%\n%EXAMPLE:\n%To show that this produces correct results, we plot an ellipse using the\n%drawEllipse function, which uses a different parameterization. We then\n%convert that parameterization into polynomial coefficients using\n%quadEllipsForm2Poly. Those coefficients are then transformed into the\n%parameters for the scaled, rotated, and translated parametric form of\n%this function. Being in parametric form, we plot the ellipse over the\n%other one. One can see that they are the same.\n% A=inv([4, -1.5;\n% -1.5,1]);\n% x0=[2;3]*10;\n% c=2.5;\n% %Plot the original ellipse\n% figure(1)\n% clf\n% drawEllipse(x0,A,c,'-k','linewidth',4)\n% hold on\n% %Convert the ellipse into polynomial form.\n% coeffs=quadEllipsForm2Poly(A,x0,c)/1000;\n% %Convert the polynomial form into the scaled, rotated, translated form.\n% [A,B,h,k,phi]=polyEllipsForm2ScalRotTrans(coeffs);\n% %This is a parameteric form, so plot the points on the ellipse:\n% numPoints=500;\n% t=linspace(0,2*pi,numPoints);\n% x=A*cos(phi)*cos(t)-B*sin(phi)*sin(t)+h;\n% y=A*sin(phi)*cos(t)+B*cos(phi)*sin(t)+k;\n% plot(x,y,'-y','linewidth',1)\n% legend('Original Ellipse','Parametric Ellipse')\n% xlabel('x')\n% ylabel('y')\n%\n%REFERENCES:\n%[1] G. B. Hughes and M. Chraibi, \"Calculating ellipse overlap areas,\"\n% Computing and Visualization in Science, vol. 15, no. 5, pp. 291-301,\n% Oct. 2012.\n%\n%January 2023 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nAA=coeffs(3,1);\nBB=coeffs(2,2);\nCC=coeffs(1,3);\nDD=coeffs(2,1);\nEE=coeffs(1,2);\nFF=coeffs(1,1);\n\nphi=atan2(BB,AA-CC)/2;\nsinPhi=sin(phi);\ncosPhi=cos(phi);\n%Using a double angle identity:\ncos2Phi=cosPhi^2-sinPhi^2;\n\nA2=2*cos2Phi/(AA-CC+(AA+CC)*cos2Phi);\nB2=2*cos2Phi/(CC-AA+(AA+CC)*cos2Phi);\n\nh=(1/2)*(-A2*DD+(B2-A2)*cosPhi*EE*sinPhi+(A2-B2)*DD*sinPhi^2);\nk=(1/2)*(-B2*EE+(B2-A2)*cosPhi*DD*sinPhi-(A2-B2)*EE*sinPhi^2);\n\nc=(h*cosPhi+k*sinPhi)^2/A2+(h*sinPhi-k*cosPhi)^2/B2-FF;\n\n%Adjust the scaling of everything.\nA2=A2*c;\nB2=B2*c;\n\nA=sqrt(A2);\nB=sqrt(B2);\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/Ellipse_Form_Conversions/polyEllipsForm2ScalRotTrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7568690145912591}} {"text": "function y = amexpo1s(N,t0,T);\n%AMEXPO1S Generate one-sided exponential amplitude modulation.\n%\tY = AMEXPO1S(N,T0,T) generates a one-sided exponential\n%\tamplitude modulation centered on a time T0, and with a \n%\tspread proportional to T.\n%\tThis modulation is scaled such that Y(T0)=1.\n% \n%\tN : number of points.\n%\tT0 : arrival time of the exponential\t(default : N/2).\n%\tT : time spreading\t\t\t(default : 2*sqrt(N)).\n%\tY : signal.\n%\n%\tExamples:\n%\t z=amexpo1s(160);plot(z);\n%\t z=amexpo1s(160,20,40);plot(z);\n%\n%\tSee also AMEXPO2S, AMGAUSS, AMRECT, AMTRIANG.\n\n% \tF. Auger, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error ( 'The number of parameters must be at least 1.' );\nelseif (nargin == 1),\n t0=N/2; T=2*sqrt(N);\nelseif (nargin ==2),\n T=2*sqrt(N);\nend;\n\nif (N<=0),\n error('N must be greater or equal to 1.');\nelse\n tmt0=(1:N)'-t0;\n y = exp(-sqrt(pi)*tmt0/T).*(tmt0>=0.0);\nend;\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/amexpo1s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7567936651026906}} {"text": "% the following program calculates the \n% Colebrool-White friction factors at various\n% roughess heights for Reynolds numbers\n% between 5000 and 500000\n% ---------------------------------------------------------------\n% The MATLAB function was created by Tibor Balint, December 1998\n% TBoreal Research Corporation, Toronto, Ont. Canada \n% (tibor@netcom.ca) and also, University of Warwick, UK\n% ---------------------------------------------------------------\n\nclear\nRe=linspace(5000,500000,200); % set the Reynolds numbers\nDh=0.008; % set the hydraulic diameter in meters\n\nrough=0.00000075; % set the 1st EQUIVALENT ROUGHNESS HEIGHT in m\n\nfor i=1:200\n miller(i)=0.25/(log10(rough/(3.7*0.009)+5.74/Re(i)^0.9))^2;\n fcw(i)=ffcw(Re(i), Dh, rough);\nend\n\nrough=0.000001; % EQUIVALENT ROUGHNESS HEIGHT \nfor i=1:200\n% miller1(i)=0.25/(log10(rough/(3.7*0.009)+5.74/Re(i)^0.9))^2;\n fcw1(i)=ffcw(Re(i), Dh, rough);\nend\n\nrough=0.00000125; % EQUIVALENT ROUGHNESS HEIGHT \nfor i=1:200\n% miller2(i)=0.25/(log10(rough/(3.7*0.009)+5.74/Re(i)^0.9))^2;\n fcw2(i)=ffcw(Re(i), Dh, rough);\nend\n\nrough=0.0000015; % EQUIVALENT ROUGHNESS HEIGHT \nfor i=1:200\n% miller3(i)=0.25/(log10(rough/(3.7*0.009)+5.74/Re(i)^0.9))^2;\n fcw3(i)=ffcw(Re(i), Dh, rough);\nend\n\nrough=0.00000175; % EQUIVALENT ROUGHNESS HEIGHT \nfor i=1:200\n% miller4(i)=0.25/(log10(rough/(3.7*0.009)+5.74/Re(i)^0.9))^2;\n fcw4(i)=ffcw(Re(i), Dh, rough);\nend\n\n%plot the figures\nfigure(1)\norient landscape;\nsubplot(2,1,1);\nplot(Re,fcw,'b',Re,miller,'r--')\nlegend('f_{cw}','f_{miller}');\ngrid on;\naxis tight;\nxlabel('Reynolds number');\nylabel('Friction factor');\ntitle ('Hydraulic Diameter (D_h=8 mm), Eq. Roughness Height (\\epsilon = 0.75 \\mum)');\n\nsubplot(2,1,2);\nplot(Re,fcw,'b',Re,fcw1,'r',Re,fcw2,'g',Re,fcw3,'m',Re,fcw4,'k')\nlegend('\\epsilon=0.75 \\mum','\\epsilon=1.00 \\mum','\\epsilon=1.25 \\mum','\\epsilon=1.50 \\mum','\\epsilon=1.75 \\mum');\ngrid on;\naxis tight;\nxlabel('Reynolds number');\nylabel('Friction factor');\ntitle ('Colebrook-White Friction Factor (f_{cw})');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/237-pressuredrop/pressure_drop/frictiontest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7567840172595528}} {"text": "function y = tanhminus1(x)\n%TANHMINUS1 Hyperbolic tangent minus one.\n%\n% TANHMINUS1(X) is TANH(X)-1 calculated in a way that is numerically better\n% when X is large and positive.\n%\n% This example illustrates the difference\n%\n% x = 17.5:0.01:20.5;\n% plot(x, tanh(x)-1, 'y-', x, tanhminus1(x), 'r-');\n\n% Author: Peter J. Acklam\n% Time-stamp: 2003-10-13 15:04:13 +0200\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n % check number of input arguments\n error(nargchk(1, 1, nargin));\n\n y = -2 ./ (1 + exp(2 * x));\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/tanhminus1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7567244368250355}} {"text": "function mean = normal_ms_mean ( mu, sigma )\n\n%*****************************************************************************80\n%\n%% NORMAL_MS_MEAN returns the mean of the Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real MU, SIGMA, the parameters of the PDF.\n% 0.0 < SIGMA.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = mu;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/truncated_normal/normal_ms_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7567244251098908}} {"text": "function mean = pareto_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% PARETO_MEAN returns the mean of the Pareto PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < A,\n% 0.0 < B.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n if ( b <= 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARETO_MEAN - Fatal error!\\n' );\n fprintf ( 1, ' For B <= 1, the mean does not exist.\\n' );\n mean = 0.0;\n return\n end\n\n mean = b * a / ( b - 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/prob/pareto_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7567244249828842}} {"text": "function x = r8vec_cheby1space ( n, a, b )\n\n%*****************************************************************************80\n%\n%% R8VEC_CHEBY1SPACE creates a vector of Type 1 Chebyshev spaced values in [A,B].\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 August 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A, B, the first and last entries.\n%\n% Output, real X(N,1), a vector of Chebyshev spaced data.\n%\n x = zeros ( n, 1 );\n\n if ( n == 1 )\n\n x(1) = ( a + b ) / 2.0;\n\n else\n\n for i = 1 : n\n\n theta = ( 2 * ( n - i ) + 1 ) * pi / ( 2 * n );\n\n c = cos ( theta );\n\n if ( mod ( n, 2 ) == 1 )\n if ( 2 * i - 1 == n )\n c = 0.0;\n end\n end\n\n x(i) = ( ( 1.0 - c ) * a ...\n + ( 1.0 + c ) * b ) ...\n / 2.0;\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_cheby1space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7567244232911483}} {"text": "function f = ecc2flat(e)\n%ECC2FLAT Convert the eccentricity of an ellipsoid to its flattening\n%\n% F = ECC2FLAT(E) returns the flattening given the eccentricity.\n%\n% See also FLAT2ECC.\n\n e2 = e.^2;\n f = e2 ./ (1 + sqrt(1 - e2));\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/ecc2flat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.756649712954067}} {"text": "%MDS_STRESS - Sammon stress between dissimilarity matrices\n%\n% \tE = MDS_STRESS(Q,DS,D)\n%\n% INPUT\n% \tQ\t\t\t\t\tIndicator of the Sammon stress; Q = -2,-1,0,1,2\n% \tDS\t\t\t\tOriginal distance matrix\n% \tD \t\t\t\tApproximated distance matrix\n%\n% OUTPUT\n% \tE \t\t\t\tSammon stress\n%\n% DESCRIPTION\n% Computes the Sammon stress between the original distance matrix Ds\n% and the approximated distance matrix D, expressed as follows:\n%\n% E = 1/(sum_{i eps) values to be included \n\t% for the computation of the stress\n\n\tI = 1:mk; \n\tnanindex = find(isnan(Ds(:)) | isnan(D(:)));\n\tif ~isempty(nanindex),\n\t\tI(nanindex) = [];\n\tend\n\tO = [];\n\tif m == k & (length(intersect(find(D(:) < eps), 1:m+1:(mk))) == m),\n\t\tO = 1:m+1:mk;\n\t\tDs(O) = 1; \n\t\tD (O) = 1;\n mm = m - 1;\n\telse\n\t\tmm = k;\n\tend\n\n if isratio,\n II = setdiff(I,O);\n alpha = sum((Ds(II).^q).*D(II).^2)/sum((Ds(II).^(q+1)).*D(II));\n Ds = alpha*Ds;\n\telse\n\t\talpha = 1; \n\tend\n\t\t\n \n\tc = sum(Ds(I).^(q+2)) - length(O);\n\tif q ~= 0,\n\t\te = sum(Ds(I).^q .* ((Ds(I)-D(I)).^2))/c;\n\telse\n\t\te = sum(((Ds(I)-D(I)).^2))/c;\n\tend\nreturn; \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/mds_stress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7566172552375173}} {"text": "function v = polynomialCurveDerivative(t, varargin)\n%POLYNOMIALCURVEDERIVATIVE Compute derivative vector of a polynomial curve\n%\n% VECT = polynomialCurveLength(T, XCOEF, YCOEF);\n% XCOEF and YCOEF are row vectors of coefficients, in the form:\n% [a0 a1 a2 ... an]\n% VECT is a 1x2 array containing direction of derivative of polynomial\n% curve, computed for position T. If T is a vector, VECT has as many rows\n% as the length of T.\n%\n% VECT = polynomialCurveLength(T, COEFS);\n% COEFS is either a 2xN matrix (one row for the coefficients of each\n% coordinate), or a cell array.\n%\n% Example\n% polynomialCurveDerivative\n%\n% See also\n% polynomialCurves2d, polynomialCurveNormal, polynomialCurvePoint,\n% polynomialCurveCurvature \n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-02-23\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n%% Extract input parameters\n\n% polynomial coefficients for each coordinate\nvar = varargin{1};\nif iscell(var)\n xCoef = var{1};\n yCoef = var{2};\nelseif size(var, 1)==1\n xCoef = varargin{1};\n yCoef = varargin{2};\nelse\n xCoef = var(1,:);\n yCoef = var(2,:);\nend\n \n\n%% compute derivative\n\n% compute derivative of the polynomial\ndx = polynomialDerivate(xCoef);\ndy = polynomialDerivate(yCoef);\n\n% convert to polyval convention\ndx = dx(end:-1:1);\ndy = dy(end:-1:1);\n\n% numerical integration of the Jacobian of parametrized curve\nv = [polyval(dx, t) polyval(dy, t)];\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/polynomialCurves2d/polynomialCurveDerivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7566060420802908}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\nh_theta = X*theta;\nJ = (1/(2*m))*sum((h_theta - y).^2) + (lambda/(2*m))*(theta(2:end)'*theta(2:end));\ngrad = (1/m)*((h_theta - y)'*X)'\ngrad = grad + (lambda/m)*[0;theta(2:end,:)]\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "anirudhjayaraman", "repo": "Machine-Learning", "sha": "084e9c67ac3853f78461f9d0e46c7b41364da481", "save_path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning", "path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning/Machine-Learning-084e9c67ac3853f78461f9d0e46c7b41364da481/Andrew Ng Stanford Coursera/Week 06/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.756581212103334}} {"text": "%\n% lellipe(phi, k, errtol)\n%\n% Inputs:\n%\n% phi Input angle vector size 1xN.\n% k Input parameter vector size 1 or 1xN.\n% errtol Error tolerance for Carlson's algorithms.\n%\n% Matlab function to compute Legendre's (incomplete) elliptic integral \n% E(phi, k). Uses a vectorized implementation of Carlson's Duplication Algorithms \n% for symmetric elliptic integrals as found in \"Computing Elliptic \n% Integrals by Duplication,\" by B. C. Carlson, Numer. Math. 33, 1-16 (1979)\n% and also found in ACM TOMS Algorithm 577. Section 4 in the paper cited\n% here describes how to convert between the symmetric elliptic integrals\n% and Legendre's elliptic integrals.\n%\n% Returns NaN's for any argument values outside input range.\n%\n\nfunction f = lellipe(phi, k, errtol)\n\n% Argument checking for vectorization:\nlphi = length(phi);\nlk = length(k);\nerrflag = logical(0);\nif (lphi ~= lk)\n if (lphi==1)\n phivec = phi * ones(1,lk);\n kvec = k;\n elseif (lk==1)\n kvec = k * ones(1,lphi);\n phivec = phi;\n else\n disp('Incompatible input vector dimensions in lellipf!');\n errflag = logical(1);\n end\nelse\n phivec = phi;\n kvec = k;\nend\n\nif (~errflag)\n snphi = sin(phivec);\n csphi = cos(phivec);\n snphi2 = snphi.^2;\n csphi2 = csphi.^2;\n k2 = kvec.^2;\n y = 1.0 - k2.*snphi2;\n onesvec = ones(1,length(phivec));\n f = snphi .* rf(csphi2, y, onesvec, errtol) - ...\n k2 .* snphi .* snphi2 .* rd(csphi2, y, onesvec, errtol)/3.0;\nelse\n f = NaN;\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/3705-ellipticintegrals-zip/Elliptic_Integrals/lellipe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7565259816347308}} {"text": "function [AF, u, v, w] = arrayFactor(xPos, yPos, zPos, elementWeights, f, c, thetaScanAngles, phiScanAngles, thetaSteerAngle, phiSteerAngle)\n%arrayFactor - Calculate array factor of 1D, 2D or 3D array\n%\n%This matlab function calculates the array factor of a 1D, 2D or 3D array based\n%on the position of the elements/sensors and the weight associated with\n%each sensor. If no angle is given as input, the scanning angle is theta\n%from -90 to 90, and phi from 0 to 360 degrees with 1 degree resolution\n%\n%[AF, u, v, w] = arrayFactor(xPos, yPos, zPos, elementWeights, f, c, thetaScanAngles, phiScanAngles, thetaSteerAngle, phiSteerAngle)\n%\n%IN\n%xPos - 1xP vector of x-positions\n%yPos - 1xP vector of y-positions\n%zPos - 1xP vector of z-positions\n%elementWeights - 1xP vector of element weights\n%f - Wave frequency\n%c - Speed of sound\n%thetaScanAngles - 1xM vector or MxN matrix of theta scanning angles in degrees (optional)\n%phiScanAngles - 1XN vector or MxN matrix of phi scanning angles in degrees (optional)\n%thetaSteerAngle - Theta steering angle in degrees (optional)\n%phiSteerAngle - Phi steering angle in degrees (optional)\n%\n%OUT\n%AF - Calculated array factor\n%u - MxN matrix of u coordinates in UV space [sin(theta)*cos(phi)] \n%v - MxN matrix of v coordinates in UV space [sin(theta)*sin(phi)]\n%w - MxN matrix of w coordinates in UV space [cos(theta)]\n%\n%\n%Created by J?rgen Grythe\n%Last updated 2017-02-27\n\n\nif ~isvector(xPos)\n error('X-positions of array elements must be a 1xP vector where P is number of elements')\nend\n\nif ~isvector(yPos)\n error('Y-positions of array elements must be a 1xP vector where P is number of elements')\nend\n\nif ~isvector(elementWeights)\n error('Weighting of array elements must be a 1xP vector where P is number of elements')\nend\n\nif ~isscalar(f)\n error('The input frequency must be a single value')\nend\n\n\n%theta is the elevation and is the normal incidence angle from -90 to 90\nif ~exist('thetaScanAngles', 'var')\n thetaScanAngles = -pi/2:pi/180:pi/2;\nelse\n thetaScanAngles = thetaScanAngles*pi/180;\nend\n\n%phi is the azimuth, and is the angle in the XY-plane from 0 to 360\nif ~exist('phiScanAngles', 'var')\n phiScanAngles = 0:pi/180:2*pi;\nelse\n phiScanAngles = phiScanAngles*pi/180;\nend\n\n%theta, phi steering angles\nif ~exist('thetaSteerAngle', 'var')\n thetaSteerAngle = 0;\nelse\n thetaSteerAngle = thetaSteerAngle*pi/180;\nend\n\nif ~exist('phiSteerAngle', 'var')\n phiSteerAngle = 0;\nelse\n phiSteerAngle = phiSteerAngle*pi/180;\nend\n\n\n\n\n%Wavenumber\nk = 2*pi*f/c;\n\n%Number of elements/sensors in the array\nP = length(xPos);\n\n%Calculating wave vector in spherical coordinates\nif isvector(thetaScanAngles)\n \n %Size of vectors containing theta and phi angles\n M = length(thetaScanAngles);\n N = length(phiScanAngles);\n \n %Calculate UV coordinates\n u = sin(thetaScanAngles)'*cos(phiScanAngles);\n v = sin(thetaScanAngles)'*sin(phiScanAngles);\n w = repmat(cos(thetaScanAngles)', 1, N);\n \n % Apply steering\n us = u - sin(thetaSteerAngle)*cos(phiSteerAngle);\n vs = v - sin(thetaSteerAngle)*sin(phiSteerAngle);\n ws = w - cos(thetaSteerAngle);\nelse\n \n %Size of matrix containing theta and phi angles\n [M, N] = size(thetaScanAngles);\n \n %Calculate UV coordinates\n u = sin(thetaScanAngles).*cos(phiScanAngles);\n v = sin(thetaScanAngles).*sin(phiScanAngles);\n w = cos(thetaScanAngles);\n \n % Apply steering\n us = u - sin(thetaSteerAngle).*cos(phiSteerAngle);\n vs = v - sin(thetaSteerAngle).*sin(phiSteerAngle);\n ws = w - cos(thetaSteerAngle); \nend\n\n\n%Calculate array factor\nuu = bsxfun(@times, us, reshape(xPos, 1, 1, P));\nvv = bsxfun(@times, vs, reshape(yPos, 1, 1, P));\nww = bsxfun(@times, ws, reshape(zPos, 1, 1, P));\n\ng = repmat(reshape(elementWeights, 1, 1, P), M, N);\n\nAF = sum(g.*exp(1j*k*(uu + vv + ww)), 3);\n\n%Normalising\nAF = abs(AF)./max(max(abs(AF)));\n\n%\n% N\n%AF(theta, phi) = sum [ g_n * exp{jk(u*x_n + v*y_n + w*z_n)} ]\n% n=1\n%\n%u = \n%|sin(theta_0)*cos(phi_0) sin(theta_0)*cos(phi_1) .. sin(theta_0)*cos(phi_N)|\n%|sin(theta_1)*cos(phi_0) sin(theta_1)*cos(phi_1) .. sin(theta_1)*cos(phi_N)|\n%| . . . |\n%|sin(theta_M)*cos(phi_0) sin(theta_M)*cos(phi_1) .. sin(theta_M)*cos(phi_N)|\n\n%v = \n%|sin(theta_0)*sin(phi_0) sin(theta_0)*sin(phi_1) .. sin(theta_0)*sin(phi_N)|\n%|sin(theta_1)*sin(phi_0) sin(theta_1)*sin(phi_1) .. sin(theta_1)*sin(phi_N)|\n%| . . . |\n%|sin(theta_M)*sin(phi_0) sin(theta_M)*sin(phi_1) .. sin(theta_M)*sin(phi_N)|\n\n%w = \n%|cos(theta_0) cos(theta_0) .. cos(theta_0)|\n%|cos(theta_1) cos(theta_1) .. cos(theta_1)|\n%| . . . |\n%|cos(theta_N) cos(theta_N) .. cos(theta_N)|\n\n%uu = \n% --------\n% / /|\n% / xPos / |\n%--------- | M (length theta)\n%| | |\n%| u | /\n%| | / P (# elements)\n%---------/\n% N (length phi)\n\n%g = \n% --------\n% / g_P /|\n% / / |\n%--------- | M\n%|g1 g1| |\n%| g1 | /\n%|g1 g1| / P (# elements)\n%---------/\n% N\n", "meta": {"author": "jorgengrythe", "repo": "beamforming", "sha": "0e0406044a102869f63c6006f952094827b81669", "save_path": "github-repos/MATLAB/jorgengrythe-beamforming", "path": "github-repos/MATLAB/jorgengrythe-beamforming/beamforming-0e0406044a102869f63c6006f952094827b81669/algorithm/arrayFactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7564443988431103}} {"text": "function x=choosenk(n,k)\n%CHOOSENK All choices of K elements taken from 1:N [X]=(N,K)\n% The output X is a matrix of size (N!/(K!*(N-K)!),K) where each row\n% contains a choice of K elements taken from 1:N without duplications.\n% The rows of X are in lexically sorted order.\n%\n% To choose from the elements of an arbitrary vector V use\n% V(CHOOSENK(LENGTH(V),K)).\n\n% CHOOSENK(N,K) is the same as the MATLAB5 function NCHOOSEK(1:N,K) but is\n% much faster for large N and most values of K.\n\n% Copyright (c) 1998 Mike Brookes, mike.brookes@ic.ac.uk\n% Version: $Id: choosenk.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\nkk=min(k,n-k);\nif kk<2\n if kk<1\n if k==n\n x=1:n;\n else\n x=[];\n end\n else\n if k==1\n x=(1:n)';\n else\n x=1:n;\n x=reshape(x(ones(n-1,1),:),n,n-1);\n end\n end \nelse\n n1=n+1;\n m=prod(n1-kk:n)/prod(1:kk);\n x=zeros(m,k);\n f=n1-k;\n x(1:f,k)=(k:n)';\n for a=k-1:-1:1\n d=f;\n h=f;\n x(1:f,a)=a;\n for b=a+1:a+n-k\n d=d*(n1+a-b-k)/(n1-b);\n e=f+1;\n f=e+d-1;\n x(e:f,a)=b;\n x(e:f,a+1:k)=x(h-d+1:h,a+1:k);\n end\n end\nend", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/choosenk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.756444394156989}} {"text": "function [c,delta,cash] = BlackScholesCall(spot,K,r,vol,T)\n% Black-Scholes price of a European call\n% Inputs:\n% spot = spot price of underlying\n% K = strike of the call optioon\n% r = risk free rate as a fraction\n% vol = volatility of the underlying as a fraction\n% T = time to maturity in years\n% Outputs:\n% c = price of European call(s)\n% delta = delta of the call(s)\n% cash = cash held in a replicating portfolio\n%\nd1 = (log(spot./K) + (r + vol.*vol/2).*T)./(vol.*sqrt(T));\nd2 = d1 - vol.*sqrt(T);\ndelta = normcdf(d1);\ncash = -K.*exp(-r.*T).*normcdf(d2);\nc = spot.*delta + cash;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26853-factors-on-demand/FactorsOnDemand/NoGreekHedging/BlackScholesCall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9697854164256365, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7564257445416426}} {"text": "function M = nfchoa_order(nls,conf)\n%NFCHOA_ORDER maximum order of spatial band-limited NFC-HOA\n%\n% Usage: M = nfchoa_order(nls,conf)\n%\n% Input parameters:\n% nls - number of secondary sources\n%\n% Output parameters:\n% M - spherical harmonics order\n% conf - configuration struct (see SFS_config)\n%\n% NFCHOA_ORDER(nls,conf) returns the maximum order of spherical harmonics for\n% the given number of secondary sources in order to avoid spectral repetitions\n% (spatial aliasing) of the dirving signals. The order is\n%\n% / nls/2 - 1, even nls\n% M = <\n% \\ (nls-1)/2 odd nls\n%\n% for a circular array and\n% _____\n% M = \\|nls/2\n%\n% for a spherical array.\n%\n% See also: driving_function_imp_nfchoa, driving_function_mono_nfchoa\n%\n% References:\n% Ahrens (2012) - \"Analytic Methods of Sound Field Synthesis\", Springer,\n% ISBN 978-3-642-25743-8\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 input parameters =======================================\nnargmin = 2;\nnargmax = 2;\nnarginchk(nargmin,nargmax);\nisargpositivescalar(nls);\nisargstruct(conf);\n\n\n%% ===== Configuration ===================================================\nif conf.nfchoa.order\n M = conf.nfchoa.order;\n return;\nend\ndimension = conf.dimension;\n\n\n%% ===== Computation =====================================================\n% Get maximum order of spherical harmonics to avoid spatial aliasing\nif strcmp('2D',dimension) || strcmp('2.5D',dimension)\n % Ahrens (2012), p. 132\n if isodd(nls)\n M = (nls-1)/2;\n else\n M = nls/2 - 1;\n end\nelseif strcmp('3D',dimension)\n % Ahrens (2012), p. 125\n M = floor(sqrt(nls/2));\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_general/nfchoa_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7563594060627381}} {"text": "% Generating a Givens' (2x2) matrix T such that\n% T*v = [d; 0] \n%\n% Input: v -- a vector of dimension 2 \n%\n% Output: T -- Givens' matrix \n% d -- the 2-norm of v \n%\n% syntax >> [T,d] = GivensMatrix(v)\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/GivensMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7563537492731526}} {"text": "function uI = faceinterpolate3(u,node,elem,quadOrder)\n%% FACEINTERPOLATE3 interpolate to face elements RT0.\n%\n% uI = faceinterpolate3(u,node,face) interpolates a given function u\n% into the lowest order RT0. The coefficient is given by the face integral \n% int_f u*n ds. \n%\n% uI = faceinterpolate3(u,node,elem) when |face| is not given, the function\n% will generate the face by |[elem2face,face] = dof3face(elem)| and the\n% ascend order is used |elem = sortelem3(elem)|.\n%\n% uI = faceinterpolate3(u,node,face,6) the last input is the quadrature\n% order; see quadpts. \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% [elem2face,face] = dof3face(elem);\n% uI = faceinterpolate3(pde.Du,node,face);\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% See also edgeinterpolate, edgeinterpolate1, edgeinterpolate2\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n% if ~exist('elemType','var'), elemType = 'RT0'; end\n\n%% Construct Data Structure\nif size(elem,2) == 3 % the input elem is face\n face = elem;\nelse\n elem = sortelem3(elem); \n [~,face] = dof3face(elem); \nend\n\n%% normal vector of each face\nNF = size(face,1);\nv12 = node(face(:,2),:) - node(face(:,1),:);\nv13 = node(face(:,3),:) - node(face(:,1),:);\nnVec = mycross(v12,v13); % |nVec| = 2*area;\n\n%% assemble the right hand side\nif ~exist('quadOrder','var'), quadOrder = 3; end\n[lambda,weight] = quadpts(quadOrder);\nnQuad = size(lambda,1);\nuI = zeros(NF,1);\nfor p = 1:nQuad\n pxyz = lambda(p,1)*node(face(:,1),:) ...\n\t\t + lambda(p,2)*node(face(:,2),:) ...\n\t\t + lambda(p,3)*node(face(:,3),:);\n flux = u(pxyz);\n uI = uI + weight(p)*dot(flux,nVec,2)/2;\nend\n% if strcmp(elemType,'BDM1')\n% end\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/faceinterpolate3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7563537416071701}} {"text": "%% Harmonic Representation of Rotational Functions\n%\n\n%%\n% Similarly as periodic functions may be represented as weighted sums of\n% sines and cosines a rotational function $f\\colon \\mathcal{SO}(3)\\to\\mathbb C$ \n% can be written as a series of the form\n%\n% $$ f({\\bf R}) = \\sum_{n=0}^N \\sum_{k,l = -n}^n \\hat f_n^{k,l} \\, \\mathrm{D}_n^{k,l}({\\bf R}) $$\n%\n% with respect to Fourier coefficients $\\hat f_n^{k,l}$ and the so called\n% $D_n^{k,l}$.\n% \n% There exists various normalizations for the . \n% In MTEX they are $L_2$ normalized, which means\n%\n% $$\\| D_n^{k,l} \\|_2 = 1$$\n%\n% for all $n,k,l$. For more information take a look on \n% and \n% .\n%\n%%\n%\n% We construct an arbitrary ODF which generally is an SO3Fun:\nmtexdata dubna\nodf = calcODF(pf,'resolution',5*degree,'zero_Range')\n%%\n% Now we may transform an arbitrary SO3Fun into its Fourier representation \n% using the command \n\nf = SO3FunHarmonic(odf,'bandwidth',32)\n\n%% Fourier Coefficients\n%\n% Within the class |@SO3FunHarmonic| rotational functions are represented by\n% their complex valued Fourier coefficients which are stored in the field \n% |fun.fhat|. \n% They are stored in a linear order, which means |f.fhat(1)| is the\n% zero order Fourier coefficient, |f.fhat(2:10)| are the first order\n% Fourier coefficients that form a 3x3 matrix and so on.\n% Accordingly, we can extract the second order Fourier coefficients by\n\nreshape(f.fhat(11:35),5,5)\n\n%%\n% As an additional example lets define a harmonic function by its Fourier\n% coefficients $\\hat f_0^{0,0} = 0.5$ and \n% $\\hat f_1 = \\begin{array}{rrr} \n% 1 & 4 & 7 \\\\ \n% 2 & 5 & 8 \\\\ \n% 3 & 6 & 9 \\\\ \n% \\end{array}$\n\nf2 = SO3FunHarmonic([0.5,1:9]')\n\nplot(f2)\n%%\n% The Fourier coefficients $\\hat f_n^{k,l}$ allow us a complete \n% characterization of the rotational function. They are of particular \n% importance for the calculation of mean macroscopic properties e.g. \n% the second order Fourier coefficients characterize thermal expansion, \n% optical refraction index, and electrical conductivity whereas the \n% fourth order Fourier coefficients characterize the elastic properties \n% of the specimen.\n%\n% Moreover, the decay of the Fourier coefficients is directly related to\n% the smoothness of the SO3Fun. The decay of the Fourier coefficients might\n% also hint for the presents of a ghost effect. See\n% .\n\n%%\n% The decay of the Fourier coefficients is shown in the plot\nclose all;\nplotSpektra(f)\n\n\n%% ODFs given by Fourier coefficients\n%\n% In order to define an ODF by it *Fourier coefficients* ${\\bf \\hat{f}}$, \n% they has to be given as a literally ordered, complex valued\n% vector of the form\n%\n% $$ {\\bf \\hat{f}} = [\\hat{f}_0^{0,0},\\hat{f}_1^{-1,-1},\\ldots,\\hat{f}_1^{1,1},\\hat{f}_2^{-2,-2},\\ldots,\\hat{f}_N^{N,N}] $$\n%\n% where $n=0,\\ldots,N$ denotes the order of the Fourier coefficients.\n\ncs = crystalSymmetry('1'); % crystal symmetry\nfhat = [1;reshape(eye(3),[],1);reshape(eye(5),[],1)]; % Fourier coefficients\nodf = SO3FunHarmonic(fhat,cs)\n\nplot(odf,'sections',6,'silent','sigma')\n\n%%\n\nplotPDF(odf,[Miller(1,0,0,cs),Miller(1,1,0,cs)],'antipodal')\n\n%% TODO: Add some non ODF example for an SO3Fun\n%\n%\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/ODFAnalysis/SO3FunHarmonicRepresentation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7563537357774779}} {"text": "function mbasis = basis_matrix_hermite ( )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_HERMITE sets up the Hermite spline basis matrix.\n%\n% Discussion:\n%\n% This basis matrix assumes that the data points are stored as\n% ( P1, P2, P1', P2' ), with P1 and P1' being the data value and \n% the derivative dP/dT at T = 0, while P2 and P2' apply at T = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Foley, van Dam, Feiner, Hughes,\n% Computer Graphics: Principles and Practice,\n% page 484.\n%\n% Parameters:\n%\n% Output, real MBASIS(4,4), the basis matrix.\n%\n mbasis(1,1) = 2.0;\n mbasis(1,2) = -2.0;\n mbasis(1,3) = 1.0;\n mbasis(1,4) = 1.0;\n\n mbasis(2,1) = -3.0;\n mbasis(2,2) = 3.0;\n mbasis(2,3) = -2.0;\n mbasis(2,4) = -1.0;\n\n mbasis(3,1) = 0.0;\n mbasis(3,2) = 0.0;\n mbasis(3,3) = 1.0;\n mbasis(3,4) = 0.0;\n\n mbasis(4,1) = 1.0;\n mbasis(4,2) = 0.0;\n mbasis(4,3) = 0.0;\n mbasis(4,4) = 0.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/basis_matrix_hermite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7563421391671633}} {"text": "function x = L4Pinv(cf,y)\n%L4PINV The inverse of the 4 parameters logistic equation.\n% The Four Parameters Logistic Regression or 4PL nonlinear regression model\n% is commonly used for curve-fitting analysis in bioassays or immunoassays\n% such as ELISAs or dose-response curves. \n%\n% Syntax: x=L4Pinv(cf,y)\n% \n% Inputs: \n% cf is the object containing the 4 parameters of logistic\n% equation computed by L4P function. Alternatively, it can be a\n% 1x4 array.\n%\n% y is the array of the response that you want to iterpolate. \n%\n% Outputs:\n% x is the vector of interpolated data.\n% \n% Example:\n%\n% xs=[0 4.5 10.6 19.7 40 84 210]; ys=[0.0089 0.0419 0.0873 0.2599 0.7074 1.528 2.7739];\n%\n% Calling on MatLab the function: [cf G]=L4P(x,y);\n%\n% you will find the 5 parameters of this curve. \n% \n% Calling on MatLab the function L4Pinv(cf,1.782315);\n% \n% Answer is:\n% ans =\n%\n% 99.9982\n%\n% Alternatively, you can do:\n% \n% P=[0.0010 1.5153 108.0035 3.7841]; L4Pinv(P,1.782315);\n% \n% with the same result.\n%\n% Created by Giuseppe Cardillo\n% giuseppe.cardillo-edta@poste.it\n%\n% See also L4P, L5P, L5Pinv, L3P, L3Pinv\n%\n% To cite this file, this would be an appropriate format:\n% Cardillo G. (2012) Four parameters logistic regression - There and back again\n% \n\n%--------------------Input errors handling section-------------------------\nif nargin < 2\n error('Almost two inputs are required')\nend\nif isobject(cf)\n p=coeffvalues(cf);\nelse\n p=cf;\n if ~isvector(p) || length(p)~=4 || ~all(isfinite(p))\n error('cf must be a fit object or a 1x4 vector of real and finite numbers')\n end\nend\n\n%-------------------------Interpolate--------------------------------------\nx=NaN(size(y)); ok=isfinite(y);\nx(ok)=p(3).*(((p(1)-p(4))./(y(ok)-p(4)))-1).^(1/p(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/38122-four-parameters-logistic-regression-there-and-back-again/L4Pinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7563391159655507}} {"text": "%% check Clebsch Gordan Tensor\n\n\n%% the reference\n\n% some arbitrary rotation\ng = rotation.byEuler(-72*degree,88*degree,134*degree);\n\n% the rotation matrix\nR = matrix(g);\n\n% we want to express the product of two of those rotation matrice\n\nRR_ref = R(:) * R(:).'\n\n\n\n%% Express R by D\n\nD1 = WignerD(g,'order',1);\nD = D1(:) * D1(:).';\n\nEinsteinSum(U,[1 -1],D1,[-1 -2],conj(U),[2 -2])\n\n\n%% expansion into Wigner functions of lower order\n\n% zero order component\nD0 = WignerD(g,'order',0);\nCG0 = ClebschGordanTensor(0);\nC0 = D0*EinsteinSum(CG0,[1 3],CG0,[2 4])\n\n% first order component\nD1 = WignerD(g,'order',1);\nCG1 = ClebschGordanTensor(1);\nC1 = EinsteinSum(CG1,[1 3 -1],D1,[-1 -2],CG1,[2 4 -2])\n\n% second order component\nD2 = WignerD(g,'order',2);\nCG2 = ClebschGordanTensor(2);\nC2 = EinsteinSum(CG2,[1 3 -1],D2,[-1 -2],CG2,[2 4 -2])\n\nC = EinsteinSum(C0 + C1 + C2,[-1 -2 -3 -4],U,[1 -1],conj(U),[2 -2],U,[3 -3],conj(U),[4 -4]);\nreal(reshape(matrix(C),[9 9]))\n\nassert(norm(D - reshape(matrix(C0 + C1 + C2),[9,9]))<=1e-10,'Clebsch Gordan check failed')\n\n\n%%\n\n\n% zero order component\nD0 = WignerD(g,'order',0);\nCG0 = EinsteinSum(ClebschGordanTensor(0),[-1 -2],U,[1 -1],U,[2 -2]);\nCG0c = EinsteinSum(ClebschGordanTensor(0),[-1 -2],conj(U),[1 -1],conj(U),[2 -2]);\nC0 = D0*EinsteinSum(CG0,[1 3],CG0c,[2 4])\n\n% first order component\nD1 = WignerD(g,'order',1);\nCG1 = EinsteinSum(ClebschGordanTensor(1),[-1 -2 3],U,[1 -1],U,[2 -2]);\nCG1c = EinsteinSum(ClebschGordanTensor(1),[-1 -2 3],conj(U),[1 -1],conj(U),[2 -2]);\nC1 = EinsteinSum(CG1,[1 3 -1],D1,[-1 -2],CG1c,[2 4 -2])\n\n% second order component\nD2 = WignerD(g,'order',2);\nCG2 = EinsteinSum(ClebschGordanTensor(2),[-1 -2 3],U,[1 -1],U,[2 -2]);\nCG2c = EinsteinSum(ClebschGordanTensor(2),[-1 -2 3],conj(U),[1 -1],conj(U),[2 -2]);\nC2 = EinsteinSum(CG2,[1 3 -1],D2,[-1 -2],CG2c,[2 4 -2])\n\nC = C0 + C1 + C2;\nTT_ref ./ real(reshape(matrix(C),[9 9]))\n\nassert(norm(TT_ref - reshape(matrix(C),[9,9]))<=1e-10,'Clebsch Gordan check failed')\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_ClebschCordan2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7563390996917769}} {"text": "function b = r85_vxm ( n, a, x )\n\n%*****************************************************************************80\n%\n%% R85_VXM multiplies a vector by a R85 matrix.\n%\n% Discussion:\n%\n% The R85 storage format represents a pentadiagonal matrix as a 5 \n% by N array, in which each row corresponds to a diagonal, and \n% column locations are preserved. Thus, the original matrix is \n% \"collapsed\" vertically into the array.\n%\n% Example:\n%\n% Here is how a R85 matrix of order 6 would be stored:\n%\n% * * A13 A24 A35 A46\n% * A12 A23 A34 A45 A56\n% A11 A22 A33 A44 A55 A66\n% A21 A32 A43 A54 A65 *\n% A31 A42 A53 A64 * *\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the linear system.\n%\n% Input, real A(5,N), the R85 matrix.\n%\n% Input, real X(N), the vector to be multiplied by A'.\n%\n% Output, real B(N), the product A' * x.\n%\n b(1:n) = a(3,1:n) * x(1:n);\n b(2:n) = b(2:n) + a(4,1:n-1) * x(1:n-1);\n b(3:n) = b(3:n) + a(5,1:n-2) * x(1:n-2);\n b(1:n-1) = b(1:n-1) + a(2,2:n) * x(2:n);\n b(1:n-2) = b(1:n-2) + a(1,3:n) * x(3:n);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r85_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7562811274548759}} {"text": "function [ x, w ] = ccfi_1 ( n, ell )\n\n%*****************************************************************************80\n%\n%% CCFI_1 returns a Boyd quadrature rule for the Laguerre integral.\n%\n% Discussion:\n%\n% The Laguerre integral I(f) is:\n% I(f) = integral ( 0 <= x < +oo ) f(x) dx\n% and the quadrature rule which approximates I(f) is\n% Q(f) = sum ( 1 <= i <= n ) w(i) * f(x(i))\n%\n% The parameter ELL controls the mapping between [-1,+1] and [0,+oo),\n% and can be initially chosen to be 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% John Boyd,\n% Exponentially convergent Fourier-Chebyshev quadrature schemes on\n% bounded and infinite intervals,\n% Journal of Scientific Computing,\n% Volume 2, Number 2, 1987, pages 99-109.\n%\n% Parameters:\n%\n% Input, integer N, the number of points to use in the rule.\n%\n% Input, real ELL, the mapping parameter.\n%\n% Output, real X(N), W(N), the points and weights for the quadrature rule.\n%\n t = ( pi * ( 1 : n ) / ( n + 1 ) )';\n x = ell * ( cot ( 0.5 * t ) ) .^ 2;\n\n w = zeros ( n, 1 );\n for i = 1 : n\n for j = 1 : n\n w(i) = w(i) + sin ( j * t(i) ) * ( 1.0 - cos ( j * pi ) ) / j;\n end\n end\n w = w * 2.0 * ell .* sin ( t ) ./ ( 1.0 - cos ( t ) ) .^ 2 * 2.0 / ( 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/cc_project/ccfi_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7562811234984348}} {"text": "function a = hilbert_inverse ( n )\n\n%*****************************************************************************80\n%\n%% HILBERT_INVERSE returns the inverse of the Hilbert matrix.\n%\n% Formula:\n%\n% A(I,J) = (-1)**(I+J) * (N+I-1)! * (N+J-1)! /\n% [ (I+J-1) * ((I-1)!*(J-1)!)**2 * (N-I)! * (N-J)! ]\n%\n% Example:\n%\n% N = 5\n%\n% 25 -300 1050 -1400 630\n% -300 4800 -18900 26880 -12600\n% 1050 -18900 79380 -117600 56700\n% -1400 26880 -117600 179200 -88200\n% 630 -12600 56700 -88200 44100\n%\n% Properties:\n%\n% A is symmetric.\n%\n% Because A is symmetric, it is normal, so diagonalizable.\n%\n% A is almost impossible to compute accurately by general routines\n% that compute the inverse.\n%\n% A is integral.\n%\n% The sum of the entries of A is N**2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 March 2004\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 inverse Hilbert matrix.\n%\n\n%\n% Set the (1,1) entry.\n%\n a(1,1) = n * n;\n%\n% Define Row 1, Column J by recursion on Row 1 Column J-1\n%\n i = 1;\n for j = 2 : n\n a(i,j) = -a(i,j-1) * ( ( n + j - 1 ) * ( i + j - 2 ) * ...\n ( n + 1 - j ) ) /( ( i + j - 1 ) * ( j - 1 ) * ( j - 1 ) );\n end\n%\n% Define Row I by recursion on row I-1\n%\n for i = 2 : n\n for j = 1 : n\n\n a(i,j) = -a(i-1,j) * ( ( n + i - 1 ) * ( i + j - 2 ) * ( n + 1 - i ) ) ...\n / ( (i+j-1) * ( i - 1 ) * ( i - 1 ) );\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/hilbert_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7562811181353262}} {"text": "function cpv_test01 ( )\n\n%*****************************************************************************80\n%\n%% CPV_TEST01 seeks the CPV of Integral ( -1 <= t <= 1 ) exp(t) / t dt\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CPV_TEST01:\\n' );\n fprintf ( 1, ' CPV of Integral ( -1 <= t <= 1 ) exp(t) / t dt\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Estimate Error\\n' );\n fprintf ( 1, '\\n' );\n exact = 2.11450175075;\n a = -1.0;\n b = +1.0;\n for n = 2 : 2 : 8\n value = cpv ( @f01, a, b, n );\n fprintf ( 1, ' %2d %24.16g %14.6g\\n', n, value, abs ( value - exact ) );\n end\n\n return\nend\nfunction value = f01 ( t )\n\n%*****************************************************************************80\n%\n%% F01 evaluates the integrand of Integral ( -1 <= t <= 1 ) exp(t) / t dt\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T, the argument.\n%\n% Output, real VALUE, the value of the integrand.\n%\n value = exp ( t );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cauchy_principal_value/cpv_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7562726754158369}} {"text": "function C = augment(A, alpha)\n%AUGMENT Augmented system matrix.\n% AUGMENT(A, ALPHA) is the square matrix\n% [ALPHA*EYE(m) A; A' ZEROS(n)] of dimension m+n, where A is m-by-n.\n% It is the symmetric and indefinite coefficient matrix of the\n% augmented system associated with a least squares problem\n% minimize NORM(A*x-b). ALPHA defaults to 1.\n% Special case: if A is a scalar, n say, then AUGMENT(A) is the\n% same as AUGMENT(RANDN(p,q)) where n = p+q and\n% p = ROUND(n/2), that is, a random augmented matrix\n% of dimension n is produced.\n% The eigenvalues of AUGMENT(A,ALPHA) are given in terms of the\n% singular values s(i) of A (where m>n) by\n% ALPHA/2 +/- SQRT( s(i)^2*ALPHA^2 + 1/4 ), i=1:n (2n eigenvalues),\n% ALPHA, (m-n eigenvalues).\n% If m < n then the first expression provides 2m eigenvalues and the\n% remaining n-m eigenvalues are zero.\n%\n% See also SPAUGMENT.\n\n% References:\n% G. H. Golub and C. F. Van Loan, Matrix Computations, third\n% Edition, Johns Hopkins University Press, Baltimore, Maryland,\n% 1996; sec. 5.6.4.\n% N. J. Higham, Accuracy and Stability of Numerical Algorithms,\n% Second edition, Society for Industrial and Applied Mathematics,\n% Philadelphia, PA, 2002; sec. 20.5.\n\n[m, n] = size(A);\nif nargin < 2, alpha = 1; end\n\nif max(m,n) == 1\n n = A;\n p = round(n/2);\n q = n - p;\n A = randn(p,q);\n m = p; n = q;\nend\n\nC = [alpha*eye(m) A; A' zeros(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/base/utilities/matrixcomp/augment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7562628724963512}} {"text": "function g=TaylorLinearTapering(nBar,sidelobedB,xPoints,a)\n%%TAYLORLINEARTAPERING The Taylor tapering is a set of amplitude weights\n% for a continuous linear (narrowband) aperture antenna that will\n% reduce the height of nBar of the close-in sidelobes at a cost of\n% widening the beam. Such a tapering can be discretized and\n% applied to the elements in a linear phased array (An array of\n% antenna elements can be viewed as a discrete approximation to a\n% continuous aperture). This function will provide the tapering\n% values at a set of discrete points given by xPoints (the origin\n% is taken to be the center of the aperture). The radius of the\n% aperture can either be provided or is taken as value of the\n% farthest point provided.\n%\n%INPUTS: nBar The number of terms to use in the expansion. High values can\n% produce undesirable results.\n% sidelobedB The number of decibels of the ratio of the close-in sidelobe\n% voltages to the main lobe voltage. This must be a negative\n% number. A typical value is -30.\n% xyPoints An NX1 or 1XN set of N points at which the tapering values\n% should be evaluated. The center of the aperture is taken to\n% be the origin. \n% a The radius of the aperture. Tapering weights for points in\n% xPoints outside of the aperture are taken to be zero. If\n% this parameter is omitted or an empty matrix is passed, then\n% the radius is taken to be the distance of the farthest point\n% from the origin in xPoints.\n%\n%OUTPUTS: g The NX1 set of discretized Taylor tapering values evaluated at\n% the points given in xPoints. All Taylor tapering values are\n% positive and real. The coefficients are not normalized.\n%\n%This function implements the algorithm in [1].\n%\n%EXAMPLE 1:\n%Here, we evaluate the tapering values for 30dB down on a large array of\n%points to see what the tapering looks like.\n% nBar=4;\n% sidelobedB=-30;\n% numPoints=100;\n% %Generate points symmetric about the origin. This makes the aperture size\n% %1.\n% k=0:(numPoints-1);\n% xPoints=(k-(1/2)*numPoints+1/2)/numPoints;\n% g=TaylorLinearTapering(nBar,sidelobedB,xPoints);\n% \n% figure(1)\n% clf\n% plot(xPoints,g)\n% h1=xlabel('x');\n% h2=ylabel('y');\n% title('Taylor Tapering Weight')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%EXAMPLE 2:\n%Here, we consider the array response when using tapering values for 30dB\n%sidelobes on a linear array with lambda/2 spacing between elements.\n% nBar=4;\n% sidelobedB=-30;\n% numPoints=30;\n% %Generate points symmetric about the origin.\n% k=0:(numPoints-1);\n% xPoints=(k-(1/2)*numPoints+1/2)/2;\n% g=TaylorLinearTapering(nBar,sidelobedB,xPoints);\n% \n% %Tapering matrix\n% T=diag(g);\n% \n% %Now, display the response with the tapering\n% [Rsp,U]=standardUVBeamPattern(T,xPoints,'NormPowGain');\n% \n% figure(2)\n% clf\n% plot(U,10*log10(Rsp),'-b','LineWidth',2);\n% axis([-1, 1, -40 1])\n% h1=xlabel('u');\n% h2=ylabel('Amplitude Response (decibels)');\n% title('Taylor Weighted Array Response')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] T. T. Taylor, \"Design of line-source antennas for narrow beamwidth and\n% low side lobes,\" IRE Transactions on Antennas and Propagation, vol. 3,\n% no. 1, pp. 16-28, Jan. 1955.\n%\n%August 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%After Equation 35 in [1], it is noted that cosh(pi*A) is the side-lobe\n%ratio. Thus, we get the following expression for A in terms of the\n%sidelobe level in decibels:\neta=10^(sidelobedB/(-20));\nA=acosh(eta)/pi;\n\n%The square of Sigma in Equation 41 in [1].\nsigma2=nBar^2/(A^2+(nBar-1/2)^2);\n\n%The suggestion for C after Equation 48 in [1].\nC=cosh(pi*A);\n\n%Fm holds values of F in Equation 48 for z being an integer>=1.\nFm=zeros(nBar-1,1);\nfor m=1:(nBar-1)\n%Equation 48 contains singularities when z=m is an integer. To evaluate it\n%when z is an integer, we first simplify Q in Equation 47 to eliminate the\n%singularity.\n\n %Equation 47 in [1], taking the limit of z to an integer to eliminate\n %the singularity.\n np=[1:(m-1),(m+1):(nBar-1)];\n Qm=(-1)^(m+1)/(2*prod(1-(m./np).^2));\n\n n=1:(nBar-1);\n Fm(m)=C*Qm*prod(1-m^2./(sigma2*(A^2+(n-1/2).^2)));\nend\nF0=C;%The case where z=0.\n\nnumPoints=length(xPoints);\n\nif(nargin<4||isempty(a))\n %The maximum distance from the origin to a point is taken to be the\n %radius of the aperture.\n a=sqrt(max(sum(xPoints.^2,1)));\nend\n\n%The loop below implements Equation 63 in [1].\ng=zeros(numPoints,1);\ng(:)=F0/(2*pi);\nfor curPoint=1:numPoints\n rho=norm(xPoints(curPoint));\n\n if(rho<=a)\n %The normalized radius at this point.\n p=pi*rho/a;\n\n m=(1:(nBar-1))';\n g(curPoint)=g(curPoint)+(1/pi)*sum(Fm.*cos(m*p));\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Signal_Processing/Array_Processing/Tapering/TaylorLinearTapering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7562520106236422}} {"text": "function a = upshift ( n )\n\n%*****************************************************************************80\n%\n%% UPSHIFT returns the UPSHIFT matrix.\n%\n% Formula:\n%\n% if ( J-I == 1 mod ( n ) )\n% A(I,J) = 1\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% N = 4\n%\n% 0 1 0 0\n% 0 0 1 0\n% 0 0 0 1\n% 1 0 0 0\n%\n% Rectangular properties:\n%\n% A is integral: int ( A ) = A.\n%\n% A is a zero/one matrix.\n%\n% Square Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is nonsingular.\n%\n% A is a permutation matrix.\n%\n% If N is even, det ( A ) = -1.\n% If N is odd, det ( A ) = +1.\n%\n% A is unimodular.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A is a Hankel matrix: constant along anti-diagonals.\n%\n% A is an N-th root of the identity matrix.\n%\n% The inverse of A is the downshift matrix.\n%\n% A circulant matrix C, whose first row is (c1, c2, ..., cn), can be\n% written as a polynomial in A:\n%\n% C = c1 * I + c2 * A + c3 * A**2 + ... + cn * A**n-1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of rows and columns \n% of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n if ( i4_modp ( j - i, n ) == 1 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/upshift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7562520049699777}} {"text": "function [mantissa,exponent,signBit]=decomposeFloat(x,decodeExp,addLeading1)\n%%DECOMPOSEFLOAT Given a floating point number, extract the sign but, the\n% mantissa and the exponent as three separate integer quantities.\n% Unlike the function [F,E]=log2(x), this provies the raw bits of\n% the mantissa rather than another float as in the F returned by\n% log2. The floating point value is assumed to be in IEEE 754\n% format, which is documented in [1].\n%\n%INPUTS: x The real, scalar floating point value to decompose. This can be\n% of class 'single' or 'double'.\n% decodeExp The raw exponent of the floating point number is biased by 1023\n% for a double and by 127 for a single. The bits are shifted (from\n% the original double) so that the first bit in the return value\n% exponent is the least significant bit in the exponent. If this\n% is true, then the bias is removed. The default if this parameter\n% is omitted or an empty matrix is passed is true. Note that when\n% decoded, the exponent for 1 is 0, but for 0 it is actually -1023\n% for a double and is -127 for a single.\n% addLeading1 For mantissas of normalized numbers, if this is true (the\n% default), then the leading 1 that is implied but not expressly\n% stored in the floating point register will be added. No 1 will\n% be added for subnormal numbers, where it is not implied that\n% there is a leading 1. Note that \"leading\" means that it is added\n% past the last bit in the mantissa.\n%\n%OUTPUTS: mantissa The mantissa of the float as a uint64 if x is a double\n% or uint32 if x is a single. If addLeading1=true, then\n% there are 53 significant bits for double and 24\n% significant bits for a single. Otherwise, there are\n% respectively 52 and 23 significant bits for a double or\n% for a single.\n% exponent The exponent value. If decodeExp is false, then this is\n% a uint64 if x is a double or a uint32 if x is a single.\n% If decodeExp is true, then this is respectively an int64\n% or an int32 for a double or for a single.\n% signBit This is 1 if the sign bit in x is 1 (negative) and 0 if\n% the sign bit in x is zero. This is a uint64 if x is a\n% double or a uint32 if x is a single.\n%\n%The IEEE 754 standard for floating point arithmetic in [1] formats a\n%double as a 64-bit floating point data type as\n%[mantissa (52 bits)] [exponent (11 bits)] [sign (1 bit)]\n%where bit numbering starts at 0 in the mantissa and goes through 63 with\n%the sign bit. For a 32-bit floating point single, the bit ordering is\n%[mantissa (23 bits)] [exponent (8 bits)] [sign (1 bit)]\n%If exponent is all ones and the mantissa is zero, then the value Inf is\n%represented with the sign given by the sign bit. If the exponent is all\n%ones and the mantissa is any nonzero value, then a NaN is given.\n%\n%To interpret the mantissa, consider that there is an implied binary point\n%after the highest bit and if exponent is nonzero, then an implied 1. If\n%exponent is zero, then it is implied that a 0 leads the binary point.\n%Thus, the mantissa represents a fraction >=0 and < 0.5. If one reverses\n%the order of the bits in the mantissa (because we wrtie numbers in big-\n%endian format), then the number represented by the float is of the form\n%1.mantissa*2^(exponent-bias) for a nonzero exponent and\n%0.mantissa*2^(-bias) for a zero exponent. The bias is 1023 for a double\n%and is 127 for a single.\n%\n%EXAMPLE:\n% [mantissa,exponent,signBit]=decomposeFloat(4568.321)\n%One gets mantissa=5022922058913284, exponent=12, signBit=0\n%\n%EXAMPLE:\n%When dealing with integers, the mantissa with the leading 1 added\n%multiplied by a power of two (shifted) is the integer value. Consider\n% [mantissa,exponent,signBit]=decomposeFloat(11)\n% %One gets mantissa=6192449487634432, exponent=3, signBit=0\n% %Now, shift until the first nonzero bit is at the start.\n% mantissaShifted=bitshift(mantissa,-findPosOfMin1Bit(mantissa)+1)\n%One will see that the shifted mantissa is the orignal value, 11. The\n%actual amount one has to shift the mantissa also depends on the exponent.\n%\n%REFERENCES:\n%[1] IEEE Standard for Floating Point Arithmetic, Institute for Electrical\n% and Electronics Engineers Std. IEEE Std 754-2008, 29 Aug. 2008.\n%\n%January 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(decodeExp))\n decodeExp=true;\nend\n\nif(nargin<3||isempty(addLeading1))\n addLeading1=true;\nend\n\nif(~isreal(x)||~isscalar(x))\n error('x must be a real, scalar, floating point value.') \nend\n\nif(isa(x,'double'))\n N=typecast(x,'uint64');\n \n %Get the sign bit.\n theMask=getBitMask(63,'uint64');\n signBit=bitshift(bitand(N,theMask),-63);\n \n %Select the bits that make up the exponent.\n expMask=getBitMask([52,62],'uint64');\n exponent=bitshift(bitand(N,expMask),-52);\n\n %Select the bits that make up the mantissa.\n theMask=getBitMask([0,51],'uint64');\n mantissa=bitand(N,theMask);\n if(addLeading1&&exponent~=0&&exponent~=expMask)\n %If a leading 1 is implied by the floating point number, then add\n %it. No leading 1 is added if theExp is the value indicating an INf\n %or a NaN.\n\n mantissa=bitor(mantissa,bitshift(uint64(1),52));\n end\n\n if(decodeExp)\n %Get rid of the bias. Note that two exceptions are that +/-0 maps\n %to -1023 instead of 0 and +/-Inf and NaN map to 1024.\n exponent=int64(exponent)-1023;\n end\nelseif(isa(x,'single'))\n N=typecast(x,'uint32');\n \n %Get the sign bit.\n theMask=getBitMask(31,'uint32');\n signBit=bitshift(bitand(N,theMask),-31);\n \n %Select the bits that make up the exponent.\n expMask=getBitMask([23,30],'uint32');\n exponent=bitshift(bitand(N,expMask),-23);\n \n %Select the bits that make up the mantissa.\n theMask=getBitMask([0,22],'uint32');\n mantissa=bitand(N,theMask);\n if(addLeading1&&exponent~=0&&exponent~=expMask)\n %If a leading 1 is implied by the floating point number, then add\n %it. No leading 1 is added if theExp is the value indicating an INf\n %or a NaN.\n\n mantissa=bitor(mantissa,bitshift(uint32(1),23));\n end\n\n if(decodeExp)\n %Get rid of the bias. Note that two exceptions are that +/-0 maps\n %to -127 instead of 0 and +/-Inf and NaN map to 127.\n exponent=int32(exponent)-127;\n end\nelse\n error('x must be a single or double floating point value.')\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/Bitwise_Functions/decomposeFloat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7562270182361857}} {"text": "function [ resultg, resultk, error_est ] = sum_sub_gk ( func, a, b, nsub, ...\n ng, wg, nk, xk, wk )\n\n%*****************************************************************************80\n%\n%% SUM_SUB_GK carries out a composite Gauss-Kronrod rule.\n%\n% Discussion:\n%\n% The integral:\n%\n% integral ( a <= x <= b ) f(x) dx\n%\n% The quadrature rule:\n%\n% H = ( B - A ) / NSUB\n% XMID(J) = A + 0.5 * H * ( 2 * J - 1 )\n%\n% Sum ( 1 <= J <= NSUB )\n% Sum ( 1 <= I <= NK )\n% WK(I) * F ( XMID(J) + 0.5 * H * XK(I) )\n%\n% The Gauss-Legendre weights should be computed by LEGCOM or LEGSET.\n% The Kronrod abscissas and weights should be computed by KRONSET.\n%\n% The orders of the Gauss-Legendre and Kronrod rules must satisfy\n% NK = 2 * NG + 1.\n%\n% The Kronrod rule uses the abscissas of the Gauss-Legendre rule,\n% plus more points, resulting in an efficient and higher order estimate.\n%\n% The difference between the Gauss-Legendre and Kronrod estimates\n% is taken as an estimate of the error in the approximation to the\n% integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the function which\n% evaluates the integrand. The function must have the form\n% function func ( x ).\n%\n% Input, real A, B, the lower and upper limits of integration.\n%\n% Input, integer NSUB, the number of equal subintervals into\n% which the finite interval (A,B) is to be subdivided for\n% higher accuracy. NSUB must be at least 1.\n%\n% Input, integer NG, the order of the Gauss-Legendre rule.\n% NG must be at least 1.\n%\n% Input, real WG(NG), the weights of the\n% Gauss-Legendre rule.\n%\n% Input, integer NK, the order of the Kronrod rule.\n% NK must be at least 1.\n%\n% Input, real XK(NK), the abscissas of the\n% Kronrod rule.\n%\n% Input, real WK(NK), the weights of the\n% Kronrod rule.\n%\n% Output, real RESULTG, the approximate value of the\n% integral based on the Gauss-Legendre rule.\n%\n% Output, real RESULTK, the approximate value of the\n% integral based on the Kronrod rule.\n%\n% Output, real ERROR_EST, an estimate of the approximation\n% error. This is computed by taking the sum of the absolute values of\n% the differences between the Gauss-Legendre and Kronrod rules\n% over each subinterval. This is usually a good estimate of\n% the error in the value RESULTG. The error in the Kronrod\n% estimate RESULTK is usually much smaller.\n%\n resultg = 0.0;\n resultk = 0.0;\n error_est = 0.0;\n\n if ( a == b )\n return\n end\n\n if ( nk ~= 2 * ng + 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SUM_SUB_GK - Fatal error!\\n' );\n fprintf ( 1, ' NK must equal 2 * NG + 1.\\n' );\n fprintf ( 1, ' The input value was NG = %d\\n', ng );\n fprintf ( 1, ' The input value was NK = %d\\n', nk );\n error ( 'SUM_SUB_GK - Fatal error!' );\n end\n\n h = ( b - a ) / nsub;\n\n for j = 1 : nsub\n\n xmid = a + 0.5 * h * ( 2 * j - 1 );\n\n partg = 0.0;\n partk = 0.0;\n\n for i = 1 : nk\n\n xval = xmid + 0.5 * h * xk(i);\n fk = func ( xval );\n partk = partk + 0.5 * h * wk(i) * fk;\n\n if ( mod ( i, 2 ) == 0 )\n partg = partg + 0.5 * h * wg(i/2) * fk;\n end\n\n end\n\n resultg = resultg + partg;\n resultk = resultk + partk;\n error_est = error_est + abs ( partk - partg );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/sum_sub_gk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7562270157978964}} {"text": "function node_xyz = sphere_grid_q9_node_xyz ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% SPHERE_GRID_Q9_NODE_XYZ produces node coordinates for a Q9 sphere grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 September 2006\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. \n%\n% Output, real NODE_XYZ(3,4*NELEMX*NELEMY-2*NELEMX+2), \n% the node coordinates.\n%\n node = 0;\n\n node = node + 1;\n node_xyz(1,node) = 0.0;\n node_xyz(2,node) = 0.0;\n node_xyz(3,node) = -1.0;\n\n for j = 2 * nelemy : -1 : 2\n\n phi = ( j - 1 ) * pi / ( 2 * nelemy );\n\n for i = 1 : 2 * nelemx\n\n theta = ( i - 1 ) * 2.0 * pi / ( 2 * nelemx );\n\n node = node + 1;\n node_xyz(1,node) = cos ( theta ) * sin ( phi );\n node_xyz(2,node) = sin ( theta ) * sin ( phi );\n node_xyz(3,node) = cos ( phi );\n\n end\n end\n\n node = node + 1;\n node_xyz(1,node) = 0.0;\n node_xyz(2,node) = 0.0;\n node_xyz(3,node) = 1.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/sphere_grid_q9_node_xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7562054493694714}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels\n%are in the range 1..K, where K = size(all_theta, 1).\n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples)\n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly\np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the\n% max element, for more information see 'help max'. If your examples\n% are in rows, then, you can use max(A, [], 2) to obtain the max\n% for each row.\n%\n\n\nz = X * all_theta';\n\nh = sigmoid(z);\n\n[pval p] = max(h, [], 2);\n\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "fewtime", "repo": "ML", "sha": "fd9679e9d6648d01e36047e97434f38c8d2d6168", "save_path": "github-repos/MATLAB/fewtime-ML", "path": "github-repos/MATLAB/fewtime-ML/ML-fd9679e9d6648d01e36047e97434f38c8d2d6168/coursera-machine-learning/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8757869900269367, "lm_q1q2_score": 0.7561471516272956}} {"text": "function gnuplot_taylor_test ( )\n\n%*****************************************************************************80\n%\n%% GNUPLOT_TAYLOR_TEST generates a field on a regular grid and plots it.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/navier_stokes_2d_exact/gnuplot_taylor_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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'GNUPLOT_TAYLOR_TEST:\\n' );\n fprintf ( 1, ' Taylor Vortex Flow:\\n' );\n fprintf ( 1, ' Generate a velocity field on a regular grid.\\n' );\n fprintf ( 1, ' Store in GNUPLOT data and command files.\\n' );\n\n x_lo = 0.5;\n x_hi = 2.5;\n x_num = 21;\n\n y_lo = 0.5;\n y_hi = 2.5;\n y_num = 21;\n\n [ x, y ] = grid_2d ( x_num, x_lo, x_hi, y_num, y_lo, y_hi );\n\n nu = 1.0;\n rho = 1.0;\n n = x_num * y_num;\n t = 0.0;\n\n [ u, v ] = uvp_taylor ( nu, rho, n, x, y, t );\n\n header = 'taylor';\n s = 0.10;\n ns2de_gnuplot ( header, n, x, y, u, v, s );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/navier_stokes_2d_exact/gnuplot_taylor_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.756147142112581}} {"text": "function [A, b, x, ProbInfo] = PRdiffusion(varargin) \n% PRdiffusion Generates data for use in an inverse diffusion problems\n%\n% [A, b, x, ProbInfo] = PRdiffusion\n% [A, b, x, ProbInfo] = PRdiffusion(n)\n% [A, b, x, ProbInfo] = PRdiffusion(n, options)\n%\n% This function generates a 2D inverse diffusion problem on a uniform\n% finite-element mesh with 2*(n-1)^2 triangular elements; think of the\n% domain as an n-by-n pixel grid with two triangular elements in each pixel.\n%\n% The data represents a function u(t) on the grid at time t = Tfinal.\n% The goal of the inverse problem is to compute the function u(t) at\n% time t = 0 which, when diffused, produces the data.\n%\n% The forward problem is a very simple diffusion problem\n% du/dt = u_xx + u_yy, 0 < t < Tfinal\n% with homogenous Neumann boundary conditions. It is solved by means of\n% the Crank-Nicolson-Galerkin finite-element method. The inverse problem\n% is to compute the initial condition, the function u(0) at time t = 0,\n% from the solution u(t) at time t = Tfinal.\n%\n% The functions u(0) and u(Tfinal) are represented by the vecors x and b,\n% resp., which hold the values at the corners of the finite elements.\n% Both vectors have a total of n^2 elements.\n%\n% The severity of the problem increases with Tfinal and does not depend on\n% Tsteps.\n%\n% Input:\n% n - The grid has n-1 pixels in each direction, and n must be an\n% integer. Default: n = 128. There are 2*(n-1)^2 finite\n% elements, and the number of unknowns is n^2.\n% options - Parameters that define the problem\n% Tfinal : diffusion time; default Tfinal = 0.01.\n% Tsteps : number of time steps; default Tsteps = 100.\n%\n% Output:\n% A - Function handle for the forward and adjoint problem.\n% b - Vector that represents the solution u(t) at t = Tfinal.\n% x - Vector that represents the initial condition u(t) at t = 0.\n% ProbInfo - Structure containing some information about problem\n% problemType : type of test problem generated\n% (in this case: 'diffusion')\n% xType : solution type (in this case 'fem')\n% bType : data type (in this case 'fem')\n% elmtab : table of FEM elements\n% elmX : X-coordinates of element grid\n% elmY : Y-coordinates of element grid\n%\n% See also: PRblur, PRinvinterp2, PRnmr, PRseismic, PRspherical, PRtomo,\n% PRnoise, PRshowb, PRshowx\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% Based on original code by Allan P. Engsig-Karup, DTU Compute.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD Licence. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('Tfinal', 0.01, 'Tsteps', 100);\n \n% If input is 'defaults,' return the default options in A.\nif nargin == 1 && nargout <= 1 && strcmp(varargin,'defaults')\n A = defaultopt;\n return;\nend\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n case 0\n n = []; options = [];\n case 1\n if isa(varargin{1}, 'double')\n n = varargin{1}; options = [];\n else\n n = []; options = varargin{1};\n end\n case 2\n if isa(varargin{1}, 'double')\n n = varargin{1}; options = varargin{2};\n else\n n = 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 = PRset(defaultopt, options);\nTfinal = PRget(options, 'Tfinal', [], 'fast');\nTsteps = PRget(options, 'Tsteps', [], 'fast');\n\nif isempty(n), n = 128; end\n\n% Create rectangular mesh consisting of uniformly distributed triangles.\n[elmX,elmY] = meshgrid(linspace(0,1,n));\nelmX = elmX(:);\nelmY = elmY(:);\n\n% Element table for uniformly distributed triangles in a rectangular domain.\nelmtab = zeros(2*(n-1)^2,3);\ncount = 0;\nfor j = 1:n-1\n for i = 1:n-1\n elmtab(count+(1:2),:) = [i i+1+n i+n;\n i+1 i+1+n i ] + (j-1)*n;\n count = count+2;\n end\nend\n\n% Initial condition.\nx = 0.7*exp( -((elmX-0.4)/0.12).^2 - ((elmY-0.5)/0.15).^2) + ...\n exp( -((elmX-0.7)/0.1 ).^2 - ((elmY-0.4)/0.08).^2);\n\n% Create the matrices.\ndt = Tfinal/Tsteps;\n[AA,CC] = assembly(elmX,elmY,elmtab);\nS = CC - 0.5*dt*AA;\nR = CC + 0.5*dt*AA;\n\n% A is a function handle to the function that carries out the forward\n% operation, i.e., interpolates from the regular grid to the randon points,\n% or the corresponding adjoint operation (representing A').\nA = @(xx,tflag) OPdiffusion(xx,R,S,Tsteps,tflag);\n\n% The right-hand side (the data) ...\nb = A(x,'notransp');\n\nProbInfo.problemType = 'diffusion';\nProbInfo.bType = 'fem';\nProbInfo.xType = 'fem';\nProbInfo.elmtab = elmtab;\nProbInfo.elmX = elmX;\nProbInfo.elmY = elmY;\nProbInfo.R = R; %PCH\nProbInfo.S = S;\n\n% SUBFUNCTIONS -----------------------------------------------------------\n\nfunction [A,C] = assembly(x,y,elmtab)\n% Generate linear system coefficient matrix and right hand side vector.\n% Symmetry is not exploited.\n\nP = size(elmtab,1);\niL = zeros(3*3*P,1);\njL = iL;\nAL = iL;\nCL = iL;\ncount = 0;\nfor p = 1:P\n [delta,abc] = basfun(p,x,y,elmtab);\n for r = 1:3\n i = elmtab(p,r);\n for s = 1:3 % Does not exploit symmetry.\n j = elmtab(p,s);\n Ars = 1/(4*abs(delta))*(abc(r,2)*abc(s,2) + abc(r,3)*abc(s,3));\n if r == s\n Crs = abs(delta)/6;\n else\n Crs = abs(delta)/12;\n end\n count = count + 1;\n iL(count) = i;\n jL(count) = j;\n AL(count) = Ars;\n CL(count) = Crs;\n end\n end \nend\niL = iL(1:count);\njL = jL(1:count);\nAL = AL(1:count);\nA = sparse(iL,jL,AL);\nC = sparse(iL,jL,CL);\n\nfunction [delta,abc] = basfun(p,x,y,elmtab)\n% For a given element compute the geometric properties of the element.\n\nxc = x(elmtab(p,:));\nyc = y(elmtab(p,:));\ndelta = 0.5*( xc(2)*yc(3) - yc(2)*xc(3) - (xc(1)*yc(3) - ...\n yc(1)*xc(3)) + xc(1)*yc(2) - yc(1)*xc(2) );\n\n% Vectorized output.\nj = [2 3 1]';\nk = [3 1 2]';\nat = xc(j).*yc(k) - xc(k).*yc(j);\nbt = yc(j) - yc(k);\nct = xc(k) - xc(j);\nabc = [at bt ct];", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/PRcodes/PRdiffusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7561201029244893}} {"text": " function ni = trl_curvature(yi, bi, ri, li, ctype)\n%function ni = trl_curvature(yi, bi, ri, li, ctype)\n%|\n%| Compute surrogate parabola curvatures for Poisson transmission model\n%| ctype:\n%|\toc\terdogan's optimal curvatures\n%|\tpc\tprecomputed curvatures, ala trpl3\n%|\tnc\tnewton curvatures\n%|\n%| fix: align with C version of trpl2,3\n%| The minimum returned curvature will be zero.\n%| It is the user's responsibility to impose additional bounds\n%| if desired for certain algorithms.\n%|\n%| Copyright 2002-1-28, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(yi, 'test'), trl_curvature_test, return, end\nif nargin < 4, ir_usage, end\n\n[h dh] = trl_h_dh;\n\nif ~isvar('ctype') || isempty(ctype)\n\tctype = 'oc'\nend\n\n% Compute optimal surrogate parabola curvatures\n% for Poisson transmission model based on Erdogan's formula.\nswitch ctype\ncase 'oc'\n\n\t% compute curvature at l=0\n\tni_max = zeros(size(yi));\n\tif numel(bi) == 1 % scalar bi (must be positive!)\n\t\tni_max = bi .* (1 - yi .* ri ./ (bi + ri).^2);\n\telse\n\t\ti0 = bi > 0;\n\t\tif numel(ri) == 1\n\t\t\trii = 1;\n\t\telse\n\t\t\trii = ri(i0);\n\t\tend\n\t\tni_max(i0) = bi(i0) .* (1 - yi(i0) .* rii ./ (bi(i0) + rii).^2);\n\tend\n\tni_max = max(ni_max, 0);\n\tni = ni_max;\n\n\tif 0\n\t\til0 = li <= 0;\n\telse % trick in C program due to numerical precision issues\n\t\til0 = li < 0.1;\n\tend\n\n\ttmp = h(yi,bi,ri,li) - h(yi,bi,ri,0) - li .* dh(yi,bi,ri,li);\n\ti = ~il0;\n\tni(i) = 2 ./ li(i).^2 .* max(tmp(i),0);\n\n\tif any(ni > ni_max)\n\t%\tplot([ni_max(:) ni(:) ni(:)>ni_max(:)])\n\t\twarning 'large ni'\n\tend\n\n\n% Precomputed approximating parabola curvatures\n% for Poisson transmission model.\n% The minimum returned curvature will be zero.\n% This is compatible with trpl/trp_init_der02_sino() in aspire.\ncase 'pc'\n\n\t% ni = (yi-ri)^2 / yi, if yi > ri >= 0 and bi > 0\n\tii = (yi > ri) & (ri >= 0) & (bi > 0); % good rays\n\tni = zeros(size(yi));\n\tni(ii) = (yi(ii) - ri(ii)).^2 ./ yi(ii);\n\n% newton curvatures (current 2nd derivative)\ncase 'nc'\n\tbel = bi .* exp(-li);\n\tyb = bel + ri;\n\tni = (1 - ri.*yi./yb.^2) .* bel;\n\notherwise\n\tfail 'bug'\nend\n\n\n% trl_h_dh()\n% transmission Poisson likelihood function\nfunction [h, dh] = trl_h_dh\nh = @(y,b,r,l) y .* log(b.*exp(-l)+r) - (b.*exp(-l)+r);\ndh = @(y,b,r,l) (1 - y ./ (b.*exp(-l)+r)) .* b.*exp(-l);\n\n\n% trl_curvature_test()\n% demonstrate an example surrogate parabola!\nfunction trl_curvature_test\n[h dh] = trl_h_dh;\nif 0\n\tl = linspace(0,2,101)';\n\tn = trl_curvature(2+0*l, 3, 3, l, 'oc');\n\tplot(l, n, '-o'), xlabel l, ylabel n\nelse\n%\ty = 4; b = 3; r = 1; ln = 3.8;\n%\ty = 2; b = 3; r = 3; ln = 0.05;\n\ty = 2; b = 3; r = 1; ln = 1;\n\tn.oc = trl_curvature(y, b, r, ln, 'oc');\n\tn.pc = trl_curvature(y, b, r, ln, 'pc');\n\tl = linspace(-0.2,5,101)';\n\thn = h(y,b,r,ln);\n\tdhn = dh(y, b, r, ln);%\n\thl = h(y,b,r,l);\n\tq.oc = hn + dhn * (l-ln) - 0.5 * n.oc * (l-ln).^2;\n\tq.pc = hn + dhn * (l-ln) - 0.5 * n.pc * (l-ln).^2;\n\tif im\n\t\tclf, plot(l, hl, '-', l, q.oc, '--', l, q.pc, '-.', ln, hn, 'o')\n\t\tgrid\n\t\taxis([minmax(l)' minmax(hl)'])\n\t\tlegend('h(l)',\tsprintf('q_o(l) n_i=%g', n.oc), ...\n\t\t\t\tsprintf('q_p(l) n_i=%g', n.pc))\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/transmission/trl_curvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7561201007284613}} {"text": "function value = ellipse_circumference_2d ( r1, r2 )\n\n%*****************************************************************************80\n%\n%% ELLIPSE_CIRCUMFERENCE_2D returns the circumference of an ellipse in 2D.\n%\n% Discussion:\n%\n% There is no closed formula for the circumference of an ellipse.\n%\n% Defining the eccentricity by\n%\n% E = sqrt ( 1 - ( r2 / r1 )**2 )\n%\n% where R1 and R2 are the major and minor axes, then\n%\n% circumference\n% = 4 * R1 * E(K,2*PI)\n% = R1 * Integral ( 0 <= T <= 2*PI ) sqrt ( 1 - E**2 * sin**2 ( T ) ) dT\n%\n% This integral can be approximated by the Gauss-Kummer formula.\n%\n% Integration region:\n%\n% Points (X,Y) such that\n%\n% ( ( X - XC ) / R1 )**2 + ( ( Y - YC ) / R2 )**2 <= 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% John Harris and Horst Stocker,\n% Handbook of Mathematics and Computational Science,\n% Springer, 1998.\n%\n% Parameters:\n%\n% Input, real R1, R2, the major and minor semi-axes.\n%\n% Output, real VALUE, the circumference of the ellipse.\n%\n if ( r1 == r2 ) then\n value = 2.0 * pi * r1;\n return\n end \n%\n% Compute the eccentricity of the ellipse.\n%\n e = sqrt ( 1.0 - ( min ( r1, r2 ) / max ( r1, r2 ) )^2 );\n\n value = 1.0;\n term = value;\n i = 0;\n\n while ( 1 )\n\n i = i + 1;\n term = term * ( 2 * i - 3 ) * ( 2 * i - 1 ) * e * e / ( 2 * 2 * i * i );\n\n if ( abs ( term ) <= eps * ( abs ( value ) + 1.0 ) )\n break\n end\n\n value = value + term;\n\n end\n\n value = 2.0 * pi * max ( r1, r2 ) * 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/stroud/ellipse_circumference_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7561200991102963}} {"text": "classdef spaces\n% Utility functions to work with vector spaces\n\n methods(Static)\n\n function result = insersection_space(A, B)\n % Let A and B represent vector spaces\n % The function returns basis for their intersection\n if size(A, 1) ~= size(B, 1)\n error('The ambient space must be same.');\n end\n\n % Orthogonalize the two bases\n A = orth(A); % A is n x a\n B = orth(B); % B is n x b\n % Count the rank of each of them\n % After orthogonalization number of columns may have reduced\n rank_a = size(A, 2); \n rank_b = size(B, 2);\n % Combine them\n C = [A B]; % C is n x (ra + rb)\n % Compute the null space of the whole thing\n D = null(C); % C * D = 0. D is (ra + rb) x m\n % m is the nullity of C\n % Pick up the first rank_a rows from D\n D2 = D(1:rank_a, :); % ra * m\n % Multiply with A\n result = A * D2 ; % n * m.\n % We get the basis we were looking for\n end\n\n function result = orth_complement(A, B)\n % Find orthogonal complement of A in B.\n if size(A, 1) ~= size(B, 1)\n error('The ambient space must be same.');\n end\n % Orthogonalize A to make sure that it is full rank.\n A = orth(A);\n rank_a = size(A,2);\n C = [A B];\n [Q, R] = qr(C, 0);\n % Leave the first rank_a columns from A\n result = Q(:, rank_a+ 1:end);\n end\n\n function result = principal_angles_orth_cos(A, B)\n % assumes that A and B are orthonormal bases\n % Compute the matrix of inner products of bases of A and B.\n M = A' * B;\n % Compute the SVD of M. The singular values are the cosine of principal angles\n result = svd(M);\n % make sure that result is bounded by 1.\n result = min(1, result);\n end\n\n function result = principal_angles_cos(A, B)\n % Finds the principal angles between the subspaces spanned by A and B\n % References\n % - http://in.mathworks.com/matlabcentral/newsreader/view_thread/284282 \n if size(A, 1) ~= size(B, 1)\n error('The ambient space must be same.');\n end\n A = orth(A);\n B = orth(B);\n result = spx.la.spaces.principal_angles_orth_cos(A, B);\n end\n\n function result = principal_angles_radian(A, B)\n % Returns the principal angles in radians\n s = spx.la.spaces.principal_angles_cos(A, B);\n % Return the angles as cos inverse of singular values\n % ensure that cos-theta values are <= 1. Otherwise complex numbers may appear.\n result = acos(min(1, s));\n end\n\n function result = principal_angles_degree(A, B)\n % Returns the principal angles in degrees\n radians = spx.la.spaces.principal_angles_radian(A, B);\n % Return the angles as cos inverse of singular values\n result = rad2deg(radians);\n end\n\n function result = smallest_angle_cos(A, B)\n % Returns the smallest angle between two subspaces as cos(theta)\n s = spx.la.spaces.principal_angles_cos(A, B);\n result = s(1);\n end\n\n function result = smallest_angle_orth_cos(A, B)\n % Returns the smallest angle between two subspaces as cos(theta)\n % assumes A and B are orthonormal bases\n s = spx.la.spaces.principal_angles_orth_cos(A, B);\n result = s(1);\n end\n\n function result = smallest_angle_rad(A, B)\n % Returns the smallest angle between two subspaces in radians\n cos_theta = spx.la.spaces.smallest_angle_cos(A, B);\n result = acos(cos_theta);\n end\n\n function result = smallest_angle_deg(A, B)\n % Returns the smallest angle between two subspaces in degree\n theta = spx.la.spaces.smallest_angle_rad(A, B);\n result = rad2deg(theta);\n end\n\n function result = smallest_angles_cos(subspaces, d)\n % subspaces is either a cell array of bases or a concatenated matrix.\n % d is the dimension of each subspace [needed only if all bases are concatenated]\n if iscell(subspaces)\n bases = subspaces;\n % number of subspaces\n s = numel(subspaces);\n % the ambient dimension\n m = size(bases{1}, 1);\n else\n if nargin < 2\n error('Dimension of each subspace must be specified.');\n end\n [m, n] = size(subspaces);\n if mod(n, d) ~= 0\n error('n must be multiple of d');\n end\n % number of subspaces\n s = n /d;\n % create the cell array for bases\n bases = cell(s, 1);\n for i=0:s-1\n %i-th subspace basis\n si = subspaces(:, i*d + (1:d));\n bases{i+1} = si;\n end\n end\n % Orthogonalize all subspaces\n for i=1:s\n bases{i} = orth(bases{i});\n end\n % The smallest angles result matrix\n result = eye(s);\n for i=1:s\n si = bases{i};\n for j=i+1:s\n % j-th subspace\n sj = bases{j};\n result(i, j) = spx.la.spaces.smallest_angle_orth_cos(si, sj);\n result(j, i) = result(i, j);\n end\n end\n end\n\n function result = smallest_angles_rad(subspaces, d)\n if nargin < 2\n % subspace dimensions are unspecified\n d = -1;\n end\n result = spx.la.spaces.smallest_angles_cos(subspaces, d);\n result = acos(result);\n end\n\n function result = smallest_angles_deg(subspaces, d)\n if nargin < 2\n % subspace dimensions are unspecified\n d = -1;\n end\n result = spx.la.spaces.smallest_angles_rad(subspaces, d);\n result = rad2deg(result);\n end\n\n function result = subspace_distance(A, B)\n % The distance between two subspaces based on Grassmannian\n % References\n % - http://math.stackexchange.com/questions/198111/distance-between-real-finite-dimensional-linear-subspaces\n if size(A, 1) ~= size(B, 1)\n error('The ambient space must be same.');\n end\n A = orth(A);\n B = orth(B);\n if size(A, 2) ~= size(B, 2)\n error('The two subspaces must be of same dimensions');\n end\n % Compute the projection matrices for the two spaces\n PA = A*A';\n PB = B*B';\n D = PA - PB;\n % We return the operator norm of D as the distance between the two subspaces.\n result = norm(D);\n end\n\n function result = is_in_range_orth(v, U)\n % Returns if v is in the range of U where U is a unitary matrix\n nv = norm(v);\n if nv == 0\n % zero vector is always in the column space of U\n result = true;\n return;\n end\n % Compute the projection of v into the space spanned by U.\n pv = U (U' * v);\n % Compute the difference [projection to the orthogonal complement of U]\n d = v - pv;\n % Compute it's norm\n nd = norm(d);\n % Verify that the norm of difference is indeed very small\n result = nd <= 1e-6 * nv;\n end\n\n function result = is_in_range(v, A)\n % Returns if v is in the range of an arbitrary matrix A\n result = is_in_range_orth(v, orth(A)); \n end\n\n function result = find_basis(A)\n % Returns a (not necessarily orthogonal) basis of A from columns of A\n [R, pivot_cols] = rref(A);\n [m, n] = size(A);\n i = 1;\n %pivot_cols = false(n, 1);\n %for j=1:n\n % if R(i, j) == 1\n % % Add the column containing the leading one\n % pivot_cols(j) = true;\n % % Move on to find the 1 in next row\n % i = i + 1;\n % end\n %end\n % Return a basis\n result = A (:, pivot_cols);\n end\n\n function [E, R] = elim(A)\n % References\n % - http://web.mit.edu/18.06/www/Course-Info/Mfiles/elim.m\n % Factorize: E R = A \n % where E is a product of elementary matrices and \n % R is the row reduced echelon form\n [m, n] = size(A);\n I = eye(m);\n RE = rref([A I]);\n R = RE(:, 1:n);\n E = RE(:, (n+1):m+n);\n end\n\n function N = null_basis(A)\n % Returns a null basis for A\n % References\n % - http://web.mit.edu/18.06/www/Course-Info/Mfiles/nulbasis.m\n [m, n] = size(A);\n [R, pivot_cols] = rref(A, sqrt(eps));\n r = length(pivot_cols);\n % The columns of A which are not part of pivots\n freecol = 1:n;\n freecol(pivot_cols) = [];\n % Create space for storing the null basis\n N = zeros(n, n-r);\n N(freecol, : ) = eye(n-r);\n N(pivot_cols, : ) = -R(1:r, freecol);\n end\n\n\n function [col_space, null_space, row_space, left_null_space] = four_bases(A)\n % Returns bases for the four spaces associated with the matrix A\n % These are not necessarily orthonormal bases\n [m, n] = size(A);\n [R, pivot_cols] = rref(A, sqrt(eps));\n rank_a = length(pivot_cols);\n % The first rank_a rows of the echelon matrix form the row space\n row_space = R(1:rank_a, :)'; \n % The columns of A indexed by the pivot columns form the column space\n col_space = A(:, pivot_cols);\n \n % Computation of the null space\n % The columns of A which are not part of pivots\n freecol = 1:n;\n freecol(pivot_cols) = [];\n % Allocate memory for the null space basis\n null_space = zeros(n, n-r);\n null_space(freecol, : ) = eye(n-r);\n null_space(pivot_cols, : ) = -R(1:r, freecol);\n\n left_null_space = E((r+1):m, :)';\n end\n\n function [col_space, null_space, row_space, left_null_space] = four_orth_bases(A)\n % Prepares the four bases using SVD\n [U, S, V] = svd(A);\n % Finding the rank of A\n s = diag(S);\n tol = max(size(A))*eps(max(s));\n r = sum(s > tol);\n col_space = U(:, 1:r);\n null_space = U(:, r+1:m);\n row_space = V(:, 1:r);\n left_null_space = V(:, r+1:n);\n end\n\n function Y = k_dim_to_n_dim(X, n, indices)\n % Maps the data in K dimensions to N-dimensions.\n [k, d] = size(X);\n if nargin < 2\n error('Target dimension must be specified');\n end\n if n < k\n error('n must be larger than k');\n end\n if nargin < 3\n indices = 1:k;\n end\n if ~isvector(indices)\n error('indices must be a vector.');\n end\n if numel(indices) > k\n error('Number of indices must be k');\n end\n if length(unique(indices)) n || min(indices) < 1\n error('Indices cannot point outside 1:n ');\n end\n Y = zeros(n, d);\n Y(indices, :) = X;\n end\n\n\n function [A, B, C] = three_spaces_at_angle(N, theta)\n if ~mod(N, 3) == 0\n error('N must be divisible by 3');\n end\n % First create two random orthonormal vectors\n X = orth(randn(N, 3));\n % Then tilt the second one w.r.t. first\n a1 = X(:, 1);\n a2 = X(:, 2);\n a3 = X(:, 3);\n p = cos(theta);\n % first vector for second space\n b1 = sqrt(1 - p^2) * a2 + p * a1;\n % first vector for third space\n c1_1 = p;\n c1_2 = p * (1 - p) / sqrt(1 - p^2);\n c1_3 = sqrt(1 - c1_1^2 - c1_2^2);\n c1 = c1_1 * a1 + c1_2 * a2 + c1_3 * a3;\n X = [a1 b1 c1];\n % Find the orthogonal complement of X\n [U S V] = svd(X);\n Y = U(:, 4:end);\n [~, n] = size(Y);\n % Distribute vectors from Y into A and B\n A = [a1 Y(:, 1:n/3)];\n B = [b1 Y(:, n/3 + (1:n/3))];\n C = [c1 Y(:, 2*n/3 + (1:n/3))];\n end\n\n function [A, B, C] = three_disjoint_spaces_at_angle(N, theta)\n X = eye(4);\n R1 = [cos(theta) -sin(theta); sin(theta) cos(theta)];\n a1 = [1 ; 0];\n a2 = R1*a1;\n a3 = R1*a2;\n theta2 = deg2rad(59);\n R2 = [cos(theta2) -sin(theta2); sin(theta2) cos(theta2)];\n b1 = [1 ; 0];\n b2 = R2*b1;\n b3 = R2*b2;\n z = zeros(2, 1);\n A = [a1 z; z b1];\n B = [a2 z; z b2];\n C = [a3 z; z b3];\n A =kron(A , eye(N / 2));\n B =kron(B , eye(N / 2));\n C =kron(C , eye(N / 2));\n end\n\n\n function describe_three_spaces(A, B, C)\n % Compute principal angles between the subspaces\n fprintf('Ranks: [A]: %d, [B]: %d, [A]: %d\\n', ...\n rank(A), rank(B), rank(C));\n fprintf('Cols: [A]: %d, [B]: %d, [A]: %d\\n', ...\n size(A, 2), size(B, 2), size(C, 2));\n fprintf('Ranks: [A B]: %d, [B C]: %d, [A C]: %d, \\n', ...\n rank([A B]), rank([B C]), rank([A C]));\n D = [A B C];\n fprintf('Rank [A B C]: %d\\n', rank(D));\n fprintf('Angle between A and B: %.4f deg\\n', spx.la.spaces.smallest_angle_deg(A, B));\n fprintf('Angle between B and C: %.4f deg\\n', spx.la.spaces.smallest_angle_deg(B, C));\n fprintf('Angle between A and C: %.4f deg\\n', spx.la.spaces.smallest_angle_deg(A, C));\n fprintf('Column wise norms: \\n');\n fprintf(' %.2f', spx.norm.norms_l2_cw(A));\n fprintf('\\n');\n fprintf(' %.2f', spx.norm.norms_l2_cw(B));\n fprintf('\\n');\n fprintf(' %.2f', spx.norm.norms_l2_cw(C));\n fprintf('\\n');\n end\n\n function [A, B, C] = abc_spaces_junk_1(N, theta)\n if ~mod(N, 2) == 0\n error('N must be divisible by 2');\n end\n d = N / 2;\n % First create three random orthonormal vectors\n X = orth(randn(N, 2));\n % Then tilt the second one w.r.t. first\n a1 = X(:, 1);\n a2 = X(:, 2);\n p = cos(theta);\n % first vector for second space\n b1 = sqrt(1 - p^2) * a2 + p * a1;\n X = [a1 b1];\n % Find the orthogonal complement of X\n [U S V] = svd(X);\n Y = U(:, 3:end);\n [~, n] = size(Y);\n % Distribute vectors from Y into A and B\n A = [a1 Y(:, 1:n/2)];\n B = [b1 Y(:, n/2 + 1:end)];\n\n % choose a vector a3 which is orthogonal to A and b1\n X = [A B(:, 1:d-1)];\n [U S V] = svd(X);\n a3 = U(:, size(X, 2) + 1);\n % first vector for third space\n c1_1 = p;\n c1_2 = p * (1 - p) / sqrt(1 - p^2);\n c1_3 = sqrt(1 - c1_1^2 - c1_2^2);\n c1 = c1_1 * a1 + c1_2 * a2 + c1_3 * a3;\n\n X = [A c1];\n % Find the orthogonal complement of X\n [U S V] = svd(X);\n Y = U(:, size(X, 2)+1:end);\n C = [c1 Y];\n end\n\n\n function result = have_same_column_spans(A, B)\n % Checks if the column spans of two matrices are same.\n r1 = rank(A);\n r2 = rank(B);\n if r1 ~= r2 \n result = false;\n return;\n end\n r3 = rank([A B]);\n if r3 ~= r1\n result = false;\n return;\n end\n result = true;\n end\n\n function result = bases(X, counts)\n % bases for individual subspaces\n K = length(counts);\n % bases cell array\n result = cell(1, K);\n [start_indices, end_indices] = spx.cluster.start_end_indices(counts);\n for k=1:K\n ss = start_indices(k);\n ee = end_indices(k);\n XX = X(:, ss:ee);\n basis = orth(XX);\n result{k} = basis;\n end\n end\n\n\n end\n\nend", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+la/spaces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7560855901083673}} {"text": "addpath(genpath('/dartfs-hpc/rc/home/m/f0042vm/software/fdaM'))\n\n% create a basis set\n\ndt = 0.0288;\norder = 3;\nl = 25;\ndegree = 8;\n\nbasis = create_bspline_basis([0,l/dt], degree+4, order); \nbf = full(eval_basis((1:l/dt),basis));\nbf = bf(:,3:end-2);\n\nobf = spm_orth(bf); % orthogonalize bf\n\nfigure(1);\nsubplot(3,1,1);\ncla\nh1 = plot(bf,'r');\ntitle('Spline Basis Set');\nsubplot(3,1,2);\nh2 = plot(obf,'b');\ntitle('SPM orthogonalized splines');\n\n% compute inverse orthogonal transform\n\niO = (obf'*obf)\\obf'*bf;\niO(iO < 0) = 0;\n\n% generate a random walk;\n\nrand_walk = sum(triu(repmat(randn(length(bf),1),1,length(bf))));\n\nfigure(1);\nsubplot(3,1,3);\ncla\nh1=plot(rand_walk,'bla');\nhold on;\n\n% fit both basis fnuctions to the random walk\n\nB = (bf'*bf)\\bf'*rand_walk';\north_B = (obf'*obf)\\obf'*rand_walk';\n\nh2=plot(obf*orth_B,'*b');\nh3=plot(bf*B,'r');\nh4=plot(bf.*repmat(B',size(bf,1),1),'g')\n\nlegend([h1(1),h2(1),h3(1),h4(1)],'Random Walk','spm spline model','spline model','weighted splines','location','southeast');\ntitle('Spline model can be obtained with either basis set');\n\n% so now we have the following\n% splineModel = bf*B\n% splineModel = obf*orth_B\n% obf*iO = bf\n% so we can rearrange\n% obf*iO*b = obf*orth_B\n% iO*b = orth_B\n% b = inv(iO)*orth_B\n\ni0 = (bf'*obf)'\\obf'*obf;\niO(iO<0) = 0;\n\nsum(inv(iO)*orth_B)\nsum(B)\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/GLM_Batch_tools/extra/spline_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7560166947331783}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_republican ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_REPUBLICAN converts a JED to a Republican YMDF date.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm F,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 324-325.\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F,\n% the YMDF date.\n%\n\n%\n% Determine the computational date (Y'/M'/D').\n%\n j = floor ( jed + 0.5 );\n f = ( jed + 0.5 ) - j;\n\n g =floor ( ( 4 * j + 578797 ) / 146097 );\n g = floor ( ( 3 * g ) / 4 ) - 51;\n j_prime = j + 111 + g;\n\n y_prime = floor ( ( 4 * j_prime + 3 ) / 1461 );\n t_prime = floor ( mod ( 4 * j_prime + 3, 1461 ) / 4 );\n m_prime = floor ( t_prime / 30 );\n d_prime = mod ( t_prime, 30 );\n%\n% Convert the computational date to a calendar date.\n%\n d = d_prime + 1;\n m = mod ( m_prime, 13 ) + 1;\n y = y_prime - 6504 + floor ( ( 13 - m ) / 13 );\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/jed_to_ymdf_republican.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7560166798608391}} {"text": "function [mask] = polygon_filter(x, y, XI, YI, in_or_out)\n % POLYGON_FILTER used Analytic Geometry to select points inside or outside polygon\n %\n % [mask] = POLYGON_FILTER(x, y, XI, YI, in_or_out)\n % \n % input params:\n % x, y : polygon vertices, with x(1)==x(end) and y(1)==y(end)\n % x & y must be vectors of same size, and include\n % more than 3 points (len(polyX) > 3)\n %\n % XI, YI : x and y values for points to be tested\n %\n % in_or_out : either 'inside' or 'outside'\n % 'inside' : returns a mask that is true for points inside polygon\n % 'outside': returns mask that is true for points outside polygon\n %\n % default is 'inside'\n %\n % I don't know about edge cases.\n %\n % see also inpolygon, inpoly\n \n \n assert(length(XI) == length(YI), 'test-points should have equal numbers of x and y' );\n assert(length(x) == length(y), 'number of polygon x should equal polygon y');\n assert(numel(x) > 3,'not enough points to be a polygon');\n \n m = length(x)-1; % number of coordinates of polygon\n l = zeros(size(XI));\n l2 = l; % Algorithm to select points inside a closed\n % polygon based on Analytic Geometry R.Z. 4/94\n for i = 1:m\n \n l= ((y(i)-YI < 0) & (y(i+1)-YI >= 0)) & ...\n (XI-x(i)-(YI-y(i))*(x(i+1)-x(i))/(y(i+1)-y(i)) < 0) | ...\n ((y(i)-YI >= 0) & (y(i+1)-YI < 0)) & ...\n (XI-x(i)-(YI-y(i))*(x(i+1)-x(i))/(y(i+1)-y(i)) < 0);\n \n if i ~= 1\n l2(l) = 1 - l2(l);\n else\n l2 = l;\n end % if i\n \n end \n \n if ~exist('in_or_out','var')\n in_or_out = 'inside';\n end\n \n switch(in_or_out)\n case 'inside'\n mask = l2;\n case 'outside'\n mask = ~l2;\n otherwise\n error(\"unrecognized in_or_out option. either 'inside' or 'outside'\");\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/cgr_utils/polygon_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7558775643038246}} {"text": "% IM = mkRamp(SIZE, DIRECTION, SLOPE, INTERCEPT, ORIGIN)\n%\n% Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar)\n% containing samples of a ramp function, with given gradient DIRECTION\n% (radians, CW from X-axis, default = 0), SLOPE (per pixel, default =\n% 1), and a value of INTERCEPT (default = 0) at the ORIGIN (default =\n% (size+1)/2, [1 1] = upper left). All but the first argument are\n% optional.\n\n% Eero Simoncelli, 6/96. 2/97: adjusted coordinate system.\n\nfunction [res] = mkRamp(sz, dir, slope, intercept, origin)\n\nsz = sz(:);\nif (size(sz,1) == 1)\n sz = [sz,sz];\nend\n\n% -----------------------------------------------------------------\n% OPTIONAL args:\n\nif (exist('dir') ~= 1)\n dir = 0;\nend\n \nif (exist('slope') ~= 1)\n slope = 1;\nend\n \nif (exist('intercept') ~= 1)\n intercept = 0;\nend\n\nif (exist('origin') ~= 1)\n origin = (sz+1)/2;\nend\n\n% -----------------------------------------------------------------\n\nxinc = slope*cos(dir);\nyinc = slope*sin(dir);\n\n[xramp,yramp] = meshgrid( xinc*([1:sz(2)]-origin(2)), ...\n yinc*([1:sz(1)]-origin(1)) );\n \nres = intercept + xramp + yramp;\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/mkRamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7558228479139457}} {"text": "function result = gaussint(P,a,b,ngp)\n% Integration using Gauss Quadratures\n% by Manuel Diaz 2013.03.20\n\n% compute gauss locations and weights\n[w,psi] = gauss1d(ngp);\n\n% compute the change the integration range to -1 to 1\nx = (b+a)/2 + (b-a)/2*psi;\n\n% perform quadrature\nresult = (b-a)/2*sum(w.*P(x));", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/FEM/BarSimple/gaussint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7557829039526227}} {"text": "function [orientim, G_xx, G_yy, G_xy, cos_2_theta, sin_2_theta, denom] = orient(or_im, g_sigma, b_sigma, o_smooth)\n \n \n % Calculate image gradients.\n hsize = fix(6*g_sigma); \n if ~mod(hsize,2); hsize = hsize+1; end\n f = fspecial('gaussian', hsize, g_sigma);\n [f_x,f_y] = gradient(f);\n \n \n G_x = filter2(f_x, or_im);\n G_y = filter2(f_y, or_im);\n \n G_xx = G_x.^2;\n G_xy = G_x.*G_y;\n G_yy = G_y.^2;\n \n % to smooth the covariance data\n \n hsize = fix(6*b_sigma); \n if ~mod(hsize,2); hsize = hsize+1; end \n f = fspecial('gaussian', hsize, b_sigma);\n \n G_xx = filter2(f, G_xx);\n G_xy = 2*filter2(f, G_xy);\n G_yy = filter2(f, G_yy);\n \n \n denom = sqrt(G_xy.^2 + (G_xx - G_yy).^2) + eps;\n sin_2_theta = G_xy./denom; % Sin of angle\n cos_2_theta = (G_xx-G_yy)./denom; % Cos of angle\n \n \n %Smooth\n hsize = fix(6*o_smooth); \n if ~mod(hsize,2); hsize = hsize+1; end \n f = fspecial('gaussian', hsize, o_smooth); \n cos_2_theta = filter2(f, cos_2_theta);\n sin_2_theta = filter2(f, sin_2_theta);\n \n a = pi/2;\n orientim = a + atan2(sin_2_theta,cos_2_theta)/2;\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/增强算法/Fingerprint-Image-Enhancement-Algorithm-master/src/orient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7557828979841082}} {"text": "rng default;\n% Signal space \nN = 256;\n% Number of measurements\nM = 64;\n% Sparsity level\nK = 10;\n% Construct the signal generator.\ngen = spx.data.synthetic.SparseSignalGenerator(N, K);\n% Generate bi-uniform signals\nx = gen.biUniform(1, 2);\n% Sensing matrix\nPhi = spx.dict.simple.gaussian_dict(M, N);\n% Measurement vectors\ny = Phi.apply(x);\n% OMP MMV solver instance\nresult = spx.pursuit.single.omp_chol(double(Phi), y, K, 1e-6);\n% Solution vector\nz = result.z;\n\nstats = spx.commons.sparse.recovery_performance(Phi, K, y, x, z);\nspx.commons.sparse.print_recovery_performance(stats);\n\nmf = spx.graphics.Figures();\nmf.new_figure('OMP solution');\nsubplot(411);\nstem(x, '.');\ntitle('Sparse vector');\nsubplot(412);\nstem(z, '.');\ntitle('Recovered sparse vector');\nsubplot(413);\nstem(abs(x - z), '.');\ntitle('Recovery error');\nsubplot(414);\nstem(y, '.');\ntitle('Measurement vector');\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/examples/pursuit/single_recovery/orthogonal_matching_pursuit/ex_omp_chol_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7557828938030082}} {"text": "function [C,R] = incircle(x,y)\n% incircle: compute the maximal in-circle of the polygonal convex hull of a set of points in the plane\n%\n% [C,R] = incircle(x,y)\n% Called with a pair of vectors of the same length, \n% incircle computes the convex hull in 2-dimensions,\n% then finds the maximal radius in-circle that lies\n% entirely within the polygon of the convex hull.\n%\n% [C,R] = incircle(xy)\n% Called with a single nx2 array, incircle treats\n% this as a list of points in 2 dimensions. Each row\n% of xy is treated as a single point. The convex hull\n% is computed and the maximal in-circle then computed\n% for the convex hull.\n%\n% [C,R] = incircle(xy,edges)\n% Called with two arguments, the first of which is an\n% nx2 array of data points, and the second a list of\n% edges of the convex hull as would be generated by\n% convhull (or convhulln), the maximal in-circle is\n% generated for the hull as provided. No test is made\n% to assure the hull is truly convex.\n%\n% All input forms return a row vector of length 2 (C)\n% which defines the center of the in-circle, and the\n% radius (R) of the in-circle.\n%\n% Example:\n% \n% [C,R] = incircle(rand(1000,1),rand(1000,1))\n%\n% C =\n% 0.50191 0.49999\n%\n% R =\n% 0.49788\n%\n% Example:\n%\n% x = randn(100,1) + 1;\n% y = randn(100,1) - 2.5;\n% H = convhull(x,y);\n% [C,R] = incircle([x,y],H)\n%\n% C =\n% 1.0212 -2.3458\n%\n% R =\n% 2.1329\n%\n% t = linspace(0,2*pi,200);\n% xc = R*cos(t) + C(1);\n% yc = R*sin(t) + C(2);\n% plot(x(H),y(H),'-r',x,y,'ko',xc,yc,'-b')\n% axis equal\n% xlabel X\n% ylabel Y\n% title 'Convex hull, with polygon in-circle'\n% grid on\n%\n%\n% See also: minboundcicle, convhull\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 6/14/09\n\nif (nargin < 1) || (nargin > 2)\n error('INCIRCLE:improperarguments', ...\n 'incircle requires exactly 1 or 2 arguments')\nelseif (nargin == 2) && isvector(x) && isvector(y) && (numel(x) == numel(y))\n % a pair of vectors\n xy = [x(:),y(:)];\n % compute the hull. I prefer convhulln.\n edges = convhulln(xy);\nelseif (nargin == 1) && (size(x,2) == 2)\n % a single list of points as rows of x\n xy = x;\n edges = convhulln(xy);\nelseif (nargin == 2) && (size(x,2) == 2) && (size(y,2) == 2)\n % y must be a list of edges from convhulln\n xy = x;\n edges = y;\nelseif (nargin == 2) && (size(x,2) == 2) && isvector(y) && (y(1) == y(end))\n % y must be a list of edges from convhull\n xy = x;\n I = y(:);\n % in case the first point was not wrapped in the polygon\n if I(1) ~= I(end)\n I = [I;I(1)];\n end\n edges = [I(1:(end-1)),I(2:end)];\nelse\n % none of the forms I allow seem to fit.\n % give up and throw an error.\n error('INCIRCLE:invaliddata', ...\n 'x and y do not seem to fit into any of the allowed forms for incircle input')\nend\nne = size(edges,1);\n\n% the end points of each edge are...\nA = xy(edges(:,1),:);\nB = xy(edges(:,2),:);\n\n% the normal vector to each edge\nN = (B - A)*[0 1;-1 0];\n\n% normalize to unit length\nL = sqrt(sum(N.^2,2));\nN = N./[L,L];\n\n% a central point inside the hull itself\nC0 = mean(A,1);\n\n% ensure the normals point inwards. While\n% I can use the signed area for a hull as\n% generated by convhull (suggestion by Bruno)\n% this test is also efficient, and it deals\n% with the case of a hull provided from some\n% unknown and less trusted source.\nk = sum(N.*bsxfun(@minus,C0,A),2) < 0;\nN(k,:) = -N(k,:);\n\n% formulate the linear programming problem.\n% given a point C inside the hull, the distance\n% from C to the edge that contains A(i,:) is\n% given by (dot(N(i,:),C - A(i,:))). If this\n% number is negative for any edge of the hull,\n% then C is outside of the hull.\n%\n% Now think of it as a set of slack variables,\n% one for each edge of the hull. Given the\n% unknown point C that defines the center of\n% the in-circle,\n%\n% dot(N(i,:),C-A(i,:)) - S(i) == 0\n%\n% Thus the vector S is of length ne, where ne is\n% the number of edges in the convex hull. Every\n% element of S must be positive.\n%\n% Create one more slack variable, a scalar R.\n% R is the minimum value that S attains for a\n% given point C. \n%\n% R >= 0\n% S(i) >= R\n%\n% The objective for our linear programming problem\n% is simple. It is just -R. When we find the\n% solution to the LP problem that satisfies the\n% equality constraints above between C and S, the\n% bound constraint on T, and the inequality\n% constraints between S and R, the solution yields\n% the maximal radius in-circle that fits inside\n% the convex hull polygon.\n%\n% The unknowns for the LP are a list of ne+3\n% variables. The first two variables represent\n% the center coordinates of the circle. X(3) = R\n% is the circle radius. The remainder of the\n% variables are the slack variabls S(i).\n\n% equality constraints defined by the dot products\n% with the normal vectors.\nAeq = [N,zeros(ne,1),-eye(ne)];\nbeq = sum(N.*A,2);\n\n% lower bounds only for the slack variables\nLB = [-inf; -inf; 0; zeros(ne,1)];\n% there are no upper bounds\nUB = [];\n\n% inequalities defined by the slack variable\n% constraints\nA = [zeros(ne,2),ones(ne,1),-eye(ne)];\nb = zeros(ne,1);\n\n% the objective is just -R\nf = zeros(ne+3,1);\nf(3) = -1;\n\n% just turn off the output message\noptions = optimset('linprog');\noptions.Display = 'off';\n\n% linprog does all of the hard work.\nresult = linprog(f,A,b,Aeq,beq,LB,UB,[],options);\n\n% unpack the circle parameters\nC = result(1:2)';\nR = result(3);\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/34767-a-suite-of-minimal-bounding-objects/MinBoundSuite/incircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.7557706209716908}} {"text": "function bitPos=findPosOfMin1Bit(n)\n%%FINDPOSOFMIN1BIT Given n, which is of an integer data type, determine the\n% position of the least significant bit that is a 1.\n%\n%INPUTS: n An integer or a matrix of integers. These must be an integer\n% data type (i.e. not a double).\n%\n%OUTPUTS: bitPos The position of the first 1 in the binary representation\n% of each of the integers in n. Counting starts at 1. A\n% value of 0 means that there is no 1 in the binary\n% representation.\n%\n%The algorithm just keeps shifting the number (dividing by 2) until it\n%the first digit is no longer 0, counting the number of shifts needed.\n%\n%EXAMPLE:\n% n=findPosOfMin1Bit(int32([0,4,1213,2^23]))\n%\n%The function returns n=[0, 3, 1, 24]. Binary representations of\n%the numbers (the least significant bit is to the left) are\n%0 0\n%4 001\n%1213 10111101001\n%2^23 000000000000000000000001\n%\n%January 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isfloat(n)||~isreal(n))\n error('The values must be real and be an integer data type.')\nend\n\nif(ischar(n))\n n=uint8(n); \nend\n\nbitPos=ones(size(n));\nnumEls=numel(n);\n\nfor curEl=1:numEls\n if(n(curEl)~=0) \n while(bitand(n(curEl),1)==0)\n bitPos(curEl)=bitPos(curEl)+1;\n n(curEl)=bitshift(n(curEl),-1);\n end\n else\n bitPos(curEl)=0;\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Misc/Bitwise_Functions/findPosOfMin1Bit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7557706069225394}} {"text": "function x_num = box_behnken_size ( dim_num )\n\n%*****************************************************************************80\n%\n%% BOX_BEHNKEN_SIZE returns the size of a Box-Behnken design.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% George Box, Donald Behnken,\n% Some new three level designs for the study of quantitative variables,\n% Technometrics,\n% Volume 2, pages 455-475, 1960.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Output, integer X_NUM, the number of elements of the design.\n% X_NUM will be equal to DIM_NUM * 2**(DIM_NUM-1) + 1.\n%\n if ( 1 <= dim_num )\n x_num = 1 + dim_num * 2^( dim_num - 1 );\n else\n x_num = -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/box_behnken/box_behnken_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7557705917763128}} {"text": "function fx = ln_cordic ( x, n )\n\n%*****************************************************************************80\n%\n%% LN_CORDIC evaluates the natural logarithm function using the CORDIC method.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Frederick Ruckdeschel,\n% BASIC Scientific Subroutines,\n% Volume II,\n% McGraw-Hill, 1980,\n% ISBN: 0-07-054202-3,\n% LC: QA76.95.R82.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Input, integer N, the number of steps to take.\n%\n% Output, real FX, the logarithm of X.\n%\n% Local Parameters:\n%\n% Local, real A(1:25) = exp ( (1/2)^(1:25) );\n%\n a_length = 25;\n\n a = [ ...\n 1.648721270700128, ...\n 1.284025416687742, ...\n 1.133148453066826, ...\n 1.064494458917859, ...\n 1.031743407499103, ...\n 1.015747708586686, ...\n 1.007843097206488, ...\n 1.003913889338348, ...\n 1.001955033591003, ...\n 1.000977039492417, ...\n 1.000488400478694, ...\n 1.000244170429748, ...\n 1.000122077763384, ...\n 1.000061037018933, ...\n 1.000030518043791, ...\n 1.0000152589054785, ...\n 1.0000076294236351, ...\n 1.0000038147045416, ...\n 1.0000019073504518, ...\n 1.0000009536747712, ...\n 1.0000004768372719, ...\n 1.0000002384186075, ...\n 1.0000001192092967, ...\n 1.0000000596046466, ...\n 1.0000000298023228 ];\n e = 2.718281828459045;\n\n if ( x <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LN_CORDIC - Fatal error!\\n' );\n fprintf ( 1, ' Input argument X <= 0.0\\n' );\n error ( 'LN_CORDIC - Fatal error!' );\n end\n\n k = 0;\n\n while ( e <= x )\n k = k + 1;\n x = x / e;\n end\n\n while ( x < 1.0 )\n k = k - 1;\n x = x * e;\n end\n%\n% Determine the weights.\n%\n for i = 1 : n\n\n w(i) = 0.0;\n\n if ( i <= a_length )\n ai = a(i);\n else\n ai = 1.0 + ( ai - 1.0 ) / 2.0;\n end\n\n if ( ai < x )\n w(i) = 1.0;\n x = x / ai;\n end\n\n end\n\n x = x - 1.0;\n x = x ...\n * ( 1.0 - ( x / 2.0 ) ...\n * ( 1.0 + ( x / 3.0 ) ...\n * ( 1.0 - x / 4.0 )));\n%\n% Assemble.\n%\n poweroftwo = 0.5;\n for i = 1 : n\n x = x + w(i) * poweroftwo;\n poweroftwo = poweroftwo / 2.0;\n end\n\n fx = k + x;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cordic/ln_cordic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.7557029116195466}} {"text": "function [ a, more ] = tree_rb_lex_next ( n, a, more )\n\n%*****************************************************************************80\n%\n%% TREE_RB_LEX_NEXT generates rooted binary trees in lexicographic order.\n%\n% Discussion:\n%\n% The information definining the tree of N nodes is stored in a vector \n% of 0's and 1's, in preorder traversal form. Essentially, the\n% shape of the tree is traced out with a pencil that starts at the root,\n% and stops at the very last null leaf. The first time that a (non-null) \n% node is encountered, a 1 is added to the vector, and the left \n% descendant of the node is visited next. When the path returns from\n% the first descendant, the second descendant is visited. When then path\n% returns again, the path passes back up from the node to its parent.\n% A null leaf is encountered only once, and causes a zero to be added to \n% the vector, and the path goes back up to the parent node. \n%\n% The lexicographic order is used to order the vectors of 1's and 0's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 June 2013\n%\n% Reference:\n%\n% Frank Ruskey,\n% Combinatorial Generation,\n% To appear.\n%\n% Parameters:\n%\n% Input, integer N, the number of nodes in the rooted binary\n% tree. N should be odd.\n%\n% Input/output, integer A(N), the preorder traversal form for\n% the previous/next rooted binary tree.\n%\n% Output, logical MORE, is TRUE if the next rooted binary tree was\n% returned on this call, or FALSE if there are no more rooted binary\n% trees, and the output of the previous call was the last one.\n%\n if ( ~ more )\n a(1:2:n-2) = 1;\n a(2:2:n-1) = 0;\n a(n) = 0;\n more = 1;\n return\n end\n%\n% Find the last 1 in A.\n%\n k = n;\n while ( a(k) == 0 )\n k = k - 1;\n end\n q = n - k - 1;\n%\n% Find the last 0 preceding the last 1 in A.\n% If there is none, then we are done, because 11...1100..00 \n% is the final element.\n%\n while ( 1 )\n\n if ( k == 1 )\n more = 0;\n return\n end\n\n if ( a(k) == 0 )\n break\n end\n\n k = k - 1;\n\n end\n\t\n p = n - k - q - 1;\n a(k) = 1;\n a(k+1:n-2*p+1) = 0;\n a(n-2*p+2:2:n-2) = 1;\n a(n-2*p+3:2:n-1) = 0;\n a(n) = 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/treepack/tree_rb_lex_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.7556883413652747}} {"text": "%DECOMPOSEESSENTIALMAT Decompose an essential matrix to possible rotations and translation\n%\n% S = cv.decomposeEssentialMat(E)\n%\n% ## Input\n% * __E__ The input essential matrix, 3x3.\n%\n% ## Output\n% * __S__ Decomposed `E`. A scalar struct with the following fields:\n% * __R1__ One possible rotation matrix, 3x3.\n% * __R2__ Another possible rotation matrix, 3x3.\n% * __t__ One possible translation, 3x1.\n%\n% This function decompose an essential matrix `E` using SVD decomposition\n% [HartleyZ00]. Generally 4 possible poses exists for a given `E`. They are\n% `[R1,t]`, `[R1,-t]`, `[R2,t]`, `[R2,-t]`. By decomposing `E`, you can only\n% get the direction of the translation, so the function returns unit `t`.\n%\n% ## References\n% [HartleyZ00]:\n% > Richard Hartley and Andrew Zisserman. \"Multiple view geometry in computer\n% > vision\". Cambridge university press, 2003.\n%\n% See also: cv.findEssentialMat, cv.SVD\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/decomposeEssentialMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7556883320906441}} {"text": "function [U_exact] = exact_translating_sphere(sphere_translational_velocity,sphere_radius,mesh_eval)\n%+========================================================================+\n%| |\n%| This function uses the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : |\n%| PROPERTY : |\n%| LICENCE : |\n%| CONTACT : |\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 : exact_translating_sphere.m |\n%| # | VERSION : 0.10 |\n%| _#_ | AUTHOR(S) : Luca Berti |\n%| ( # ) | CREATION : 25.12.2018 |\n%| / 0 \\ | LAST MODIF : |\n%| ( === ) | SYNOPSIS : |\n%| `---' | |\n%+========================================================================+\n% COMPUTE THE EXACT VELOCITY FIELD DETERMINED BY A TRANSLATING SPHERE IN \n% AN INFINITE FLUID ALONG THE Z AXIS \n% Reference: Happel-Brenner, \"Low Reynolds number hydrodynamics\"\n% (pag. 119 and formulas 4-17.17 and 4-17.18) transformed into Cartesian \n% coordinates (p.507 A-15.29 for the transformation)\n\n% Input -> mesh_eval: mesh containing the evaluation points for the exact\n% solution \n% sphere_translational_velocity -> translational velocity of the\n% vertically moving sphere\n% [0,0,W]\n% Output -> U_exact: 3xN_eval vector containing the values of the exact\n% solution at the evaluation point, expressed IN CARTESIAN\n% COORDINATES\n\nW = sphere_translational_velocity(3);\n% Exact solutions taken from the reference - SPHERICAL COORDINATES\nu_r = @(x,y,z) -W.*cos(acos(z./sqrt(x.^2+y.^2+z.^2))).*(sphere_radius^3./(2*sqrt(x.^2+y.^2+z.^2).^3) -3*sphere_radius./(2*sqrt(x.^2+y.^2+z.^2)));\nu_theta = @(x,y,z) -W.*sin(acos(z./sqrt(x.^2+y.^2+z.^2))).*(sphere_radius^3./(4*sqrt(x.^2+y.^2+z.^2).^3)+3*sphere_radius./(4*sqrt(x.^2+y.^2+z.^2)));\nu_phi =@(x,y,z) 0;\n\nX = mesh_eval.vtx;\nN_eval = size(X,1);\n\n% Evaluation vector - SPHERICAL COORDINATES\nU_exact = zeros(N_eval*3,1);\nU_exact(1:N_eval,1) = feval(u_r,X(:,1),X(:,2),X(:,3));\nU_exact(N_eval+1:2*N_eval,1) = feval(u_theta,X(:,1),X(:,2),X(:,3));\nU_exact(2*N_eval+1:end,1) = feval(u_phi,X(:,1),X(:,2),X(:,3));\n\n% Expression of the evaluation points in spherical coordinates, to extract\n% (r,theta,phi) needed to transform the exact velocities from spherical to\n% Cartesian coordinates\nY = X;\n[X(:,3),X(:,2),X(:,1)] = cart2sph(Y(:,1),Y(:,2),Y(:,3));\n% Latitude is needed instead of colatitude (as computed by Matlab)\nX(:,2) = pi/2-X(:,2);\n\ntemporary = zeros(N_eval*3,1);\n% Transformation of the exact velocity vector field from spherical to\n% Cartesian coordinates - CARTESIAN COORDINATES\ntemporary(1:N_eval,1) = U_exact(1:N_eval,1).*sin(X(:,2)).*cos(X(:,3)) + ...\n U_exact(N_eval+1:N_eval*2,1).*cos(X(:,2)).*cos(X(:,3))- ...\n U_exact(1+2*N_eval:end,1).*sin(X(:,3));\n\ntemporary(1+N_eval:2*N_eval,1) = U_exact(1:N_eval,1).*sin(X(:,2)).*sin(X(:,3)) + ...\n U_exact(N_eval+1:N_eval*2,1).*cos(X(:,2)).*sin(X(:,3)) + ...\n U_exact(1+2*N_eval:end,1).*cos(X(:,3));\n \ntemporary(1+2*N_eval:end,1) = U_exact(1:N_eval,1).*cos(X(:,2)) - ...\n U_exact(N_eval+1:N_eval*2,1).*sin(X(:,2));\nU_exact = temporary; \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/gypsilabModified/nonRegressionTest/stokes/translatingSphere/exact_translating_sphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7555609472086411}} {"text": "function X_zero=assignPerimeterPositions(radius,mesh); \n% Define a set of perimeter points on the circle.\n%\n% X_zero=assignPerimeterPositions(perimeterDists,mesh); \n%\n% orderMeshPerimeterPointsAll is the routine that gets the perimeter points\n% into the proper order for the mapping here. The mapping here simply\n% puts these points on a circle. In principle, we could put the points at\n% these angles but adjust for distance. In that case, however, we might\n% not have a convex set. So, we use a circle.\n%\n% The most anterior point in the sub mesh should map to the top of the\n% circle. The most posterior point should be on the left or right.\n%\n% Stanford.\n\nnumPerimPoints=length(mesh.orderedUniquePerimeterPoints);\n\n% Find the maximum y value in the perimeter\n[maxHeight,maxHIndex]=max(mesh.uniqueVertices(mesh.orderedUniquePerimeterPoints,2));\n\nangles=linspace(0,2*pi,numPerimPoints)';\nangles=shift(angles(:),[-maxHIndex,0]);\n\nX_zero=zeros(numPerimPoints,2);\n\n% Perimeter must be convex for Tutte's algorithm to work properly - \nX_zero(:,1)=radius.*cos(angles);\nX_zero(:,2)=radius.*sin(angles);\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/meshOperations/assignPerimeterPositions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7555609378542859}} {"text": "function value = p18_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P18_F evaluates the integrand for problem 18.\n%\n% Discussion:\n%\n% This is the characteristic function of the interior of the \n% N sphere of radius R and center Z, to be integrated within the\n% unit hypercube [0,1]^N. If the user picks a combination of R\n% and Z that causes the volume of the sphere to lie at least\n% partially outside the unit hypercube, the formula for the\n% exact integral will no longer be correct.\n%\n% Dimension:\n%\n% DIM_NUM is arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% R defaults to 0.50. \n% You can change R by calling P18_R8.\n%\n% Z(1:DIM_NUM) defaults to (0.5,0.5,...0.5). \n% You can change Z by calling P18_R8VEC.\n%\n% Integrand:\n%\n% f(x) = 1 if X(1:DIM_NUM) is less than R from Z(1:DIM_NUM),\n% 0 otherwise.\n%\n% Exact Integral:\n%\n% The volume of the DIM_NUM sphere of radius R.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n z = [];\n z = p18_r8vec ( 'G', 'Z', dim_num, z );\n\n r = 0.0;\n r = p18_r8 ( 'G', 'R', r );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n d = sqrt ( sum ( ( x(1:dim_num,point) - z(1:dim_num)' ).^2 ) );\n\n if ( d <= r )\n value(point) = 1.0;\n else\n value(point) = 0.0;\n end\n\n end\n\n p18_i4 ( 'I', '#', point_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p18_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7555196426233844}} {"text": "function itree = pruefer_to_tree_2 ( nnode, iarray )\n\n%*****************************************************************************80\n%\n%% PRUEFER_TO_TREE_2 produces the edge list of a tree from its Pruefer code.\n%\n% Discussion:\n%\n% One can thus exhibit all trees on N nodes, produce\n% one at random, find the M-th one on the list, etc, by\n% manipulating the Pruefer codes.\n%\n% For every labeled tree on N nodes, there is a unique N-2 tuple\n% of integers A1 through AN-2, with each A between 1 and N. There\n% are N^(N-2) such sequences, and each one is associated with exactly\n% one tree.\n%\n% This routine apparently assumes that the Pruefer code is\n% generated by taking the LOWEST labeled terminal node each time.\n% This is not consistent with PRUEFER_TO_TREE and TREE_TO_PRUEFER.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 June 2013\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Albert Nijenhuis. Herbert Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer NNODE, number of nodes in desired tree.\n%\n% Input, integer IARRAY(NNODE). IARRAY(I), I = 1, NNODE-2 \n% is the Pruefer code for the tree.\n%\n% Output, integer ITREE(NNODE); the I-th edge of the tree\n% joins nodes I and ITREE(I).\n%\n itree(1:nnode) = 0;\n \n for i = nnode-2 : -1 : 1\n \n l = iarray(i);\n \n if ( itree(l) == 0 )\n iarray(i) = - l;\n itree(l) = - 1;\n end\n \n end\n \n iarray(nnode-1) = nnode;\n%\n% Find next index K so that ITREE(K) is 0.\n%\n k = 1;\n j = 0;\n \n while ( itree(k) ~= 0 )\n k = k + 1;\n end\n \n kp = k;\n \n while ( 1 )\n \n j = j + 1;\n ir = abs ( iarray(j) );\n itree(kp) = ir;\n \n if ( j == nnode - 1 )\n break\n end\n \n if ( 0 < iarray(j) )\n while ( itree(k) ~= 0 )\n k = k + 1;\n end\n kp = k;\n continue\n end\n \n if ( k < ir )\n itree(ir) = 0;\n while ( itree(k) ~= 0 )\n k = k + 1;\n end\n kp = k;\n continue\n end\n \n kp = ir;\n\n end\n%\n% Restore the signs of IARRAY.\n%\n iarray(1:nnode-2) = abs ( iarray(1:nnode-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/treepack/pruefer_to_tree_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.7555196420134858}} {"text": "function [lmval,indd]=lmax(xx,filt)\n%LMAX \t[lmval, indd]=lmax(xx,filt). Find local maxima in vector XX,where\n%\tLMVAL is the output vector with maxima values, INDD is the \n%\tcorresponding indexes, FILT is the number of passes of the small\n%\trunning average filter in order to get rid of small peaks. Default\n%\tvalue FILT =0 (no filtering). FILT in the range from 1 to 3 is \n%\tusially sufficient to remove most of a small peaks\n%\tFor example:\n%\txx=0:0.01:35; y=sin(xx) + cos(xx ./3); \n%\tplot(xx,y); grid; hold on;\n%\t[b,a]=lmax(y,2)\n%\t plot(xx(a),y(a),'r+')\n%\tsee also LMIN, MAX, MIN\n\t\n%**************************************************|\n% \tSerge Koptenko, Guigne International Ltd., |\n%\tphone (709)895-3819, fax (709)895-3822 |\n%--------------06/03/97----------------------------|\n\nx=xx;\nlen_x = length(x);\n\tfltr=[1 1 1]/3;\n if nargin <2, filt=0; \n\telse\nx1=x(1); x2=x(len_x); \n\tfor jj=1:filt,\n\tc=conv(fltr,x);\n\tx=c(2:len_x+1);\n\tx(1)=x1; \n x(len_x)=x2; \n\tend\n end\nlmval=[]; indd=[];\ni=2;\t\t% start at second data point in time series\n while i < len_x-1,\n\tif x(i) > x(i-1)\n\t if x(i) > x(i+1)\t% definite max\nlmval =[lmval x(i)];\nindd = [ indd i];\n\t elseif x(i)==x(i+1)&x(i)==x(i+2)\t% 'long' flat spot\n%lmval =[lmval x(i)]; \t%1 comment these two lines for strict case\n%indd = [ indd i];\t%2 when only definite max included\ni = i + 2; \t\t% skip 2 points\n\t elseif x(i)==x(i+1)\t% 'short' flat spot\n%lmval =[lmval x(i)];\t%1 comment these two lines for strict case\n%indd = [ indd i];\t%2 when only definite max included\ni = i + 1;\t\t% skip one point\n\t end\n\tend\n\ti = i + 1;\n end\nif filt>0 & ~isempty(indd),\n\tif (indd(1)<= 3)|(indd(length(indd))+2>length(xx)), \n\t rng=1;\t%check if index too close to the edge\n\telse rng=2;\n\tend\n\t for ii=1:length(indd), \t% Find the real maximum value\n\t [val(ii) iind(ii)] = max(xx(indd(ii) -rng:indd(ii) +rng));\n\t iind(ii)=indd(ii) + iind(ii) -rng-1;\n\t end\n indd=iind; lmval=val;\nelse\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/3170-local-min-max-nearest-neighbour/lmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7555196394208568}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1 \n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the \n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\nfor i = 1:size(X,1)\n\tmin = Inf;\n\tfor j = 1:K\n\t\tdiff = sum((X(i,:) - centroids(j,:)).^2);\n\t\tif min > diff\n\t\t\tmin = diff;\n\t\t\tidx(i) = j;\n\t\tend\n\tend\nend\t\t\t\n\n\n\n\n\n% =============================================================\n\nend\n\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex7/ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8807970670261975, "lm_q1q2_score": 0.7555196246588477}} {"text": "function [upsilonaa, upsilonap] = lfmaaComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode)\n\n% LFMAACOMPUTEUPSILONMATRIX Upsilon matrix acce. accel. with t1, t2 limits\n% FORMAT\n% DESC computes a portion of the LFM kernel.\n% ARG gamma : Gamma value for system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\nsigma = sqrt(sigma2);\ngridt1 = repmat(t1, 1, length(t2));\ngridt2 = repmat(t2', length(t1), 1);\ntimeGrid = gridt1 - gridt2;\n\nif mode==0\n if nargout > 1\n upsilonap = lfmapComputeUpsilonMatrix(gamma, sigma2, t1, t2,1);\n upsilonaa = gamma^2*upsilonap + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + 2*timeGrid/sigma2).*(2/sigma2 - (2*timeGrid/sigma2).^2) + 8*timeGrid/sigma^4);\n else\n upsilonaa = gamma^2*lfmapComputeUpsilonMatrix(gamma, sigma2, t1, t2,1) ...\n + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + 2*timeGrid/sigma2).*(2/sigma2 - (2*timeGrid/sigma2).^2) + 8*timeGrid/sigma^4);\n end\nelse\n if nargout > 1\n upsilonap = lfmapComputeUpsilonMatrix(gamma, sigma2, t1, t2, 0);\n upsilonaa = gamma^2*upsilonap + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + 2*timeGrid/sigma2).*(2/sigma2 - (2*timeGrid/sigma2).^2) + 8*timeGrid/sigma^4) ...\n + (2*gamma^2/(sqrt(pi)*sigma))*exp(-gamma*t1)*((gamma - 2*t2/sigma2).*exp(-(t2.^2)/sigma2)).';\n\n else\n upsilonaa = gamma^2*lfmapComputeUpsilonMatrix(gamma, sigma2, t1, t2, 0) ...\n + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + 2*timeGrid/sigma2).*(2/sigma2 - (2*timeGrid/sigma2).^2) + 8*timeGrid/sigma^4) ...\n + (2*gamma^2/(sqrt(pi)*sigma))*exp(-gamma*t1)*((gamma - 2*t2/sigma2).*exp(-(t2.^2)/sigma2)).';\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/lfmaaComputeUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.755511724441646}} {"text": "function [ x, seed ] = burr_sample ( a, b, c, d, seed )\n\n%*****************************************************************************80\n%\n%% BURR_SAMPLE samples the Burr PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, D, the parameters of the PDF.\n% 0 < B,\n% 0 < C.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = burr_cdf_inv ( cdf, a, b, c, d );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/burr_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7554667702486206}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\n\nfor i = 1:length(lambda_vec)\n lambda = lambda_vec(i);\n\n theta = trainLinearReg(X, y, lambda);\n\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nend\n\n\n\n\n\n\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "Borye", "repo": "machine-learning-coursera-1", "sha": "033fdc2e6da393eeb1179a09aafe92362021effb", "save_path": "github-repos/MATLAB/Borye-machine-learning-coursera-1", "path": "github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 6 Assignments/Regularized Linear Regression and Bias,Variance/mlclass-ex5-005/mlclass-ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.9019206712569267, "lm_q1q2_score": 0.7554667668996262}} {"text": "function yi=akimai(x,y,xi)\n%\n% Usage: yi=akimai(x,y,xi)\n%\n% Given vectors x and y (of the same length)\n% and the array xi at which to interpolate,\n% fits piecewise cubic polynomials and returns\n% the interpolated values yi at xi.\n%\n% Ref. : Hiroshi Akima, Journal of the ACM, Vol. 17, No. 4, October 1970,\n% pages 589-602.\n%\n% Programmer: N. Shamsundar, University of Houston, 6/2002\n% Correction to lines 32-33, 9/2004, motivated by Gilford Ward,\n% to make routine work correctly for linear data.\n%\n% Notes: Use only for precise data, as the fitted curve passes through the\n% given points exactly. This routine is useful for plotting a pleasingly\n% smooth curve through a few given points for purposes of plotting.\n%\nx=x(:); y=y(:); xi=xi(:); n=length(x);\nif n~=length(y), error('input x and y arrays must be of same length'), end\ndx=diff(x); if any(dx <= 0) error('input x-array must be in strictly ascending order'), end\nif any(xi x(n))\n warning('All interpolation points xi must lie between x(1) and x(n)')\nend\nm=diff(y)./dx;\nmm=2*m(1)-m(2); mmm=2*mm-m(1); % augment at left\nmp=2*m(n-1)-m(n-2); mpp=2*mp-m(n-1); % augment at right\nm1=[mmm; mm; m; mp; mpp]; % slopes\ndm=abs(diff(m1)); f1=dm(3:n+2); f2=dm(1:n); f12=f1+f2;\nid=find(f12 > 1e-8*max(f12)); b=m1(2:n+1);\nb(id)=(f1(id).*m1(id+1)+f2(id).*m1(id+2))./f12(id);\nc=(3*m-2*b(1:n-1)-b(2:n))./dx;\nd=(b(1:n-1)+b(2:n)-2*m)./dx.^2;\n\n% Loop replaced by vector ops following tip from johannes.korsawe@volkswagen.de\n% 1/19/2006\n%\n[ncnt,bin]=histc(xi,x);\nbin=min(bin,n-1);\nbb=bin(1:length(xi));\nwj=xi-x(bb);\nyi=((wj.*d(bb) +c(bb)).*wj+b(bb)).*wj+y(bb);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1814-akima-interpolation/akima.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7554667665926885}} {"text": "function [H,Q,M,W]=matExpIntFam(T,A,B,Qc)\n%%MATEXPINTFAM This function explicitly solves a number of real matrix\n% integral problems that arise when solving for optimal linear\n% regulators. The integrals are:\n% H=int_0^T expm(A*s)*B ds\n% Q=int_0^T expm(A'*s)*Qc*expm(A*s) ds\n% M=int_0^T expm(A'*s)*Qc*H(s) ds\n% W=int_0^T H(s)'*Qc*H(s) ds\n% where s is the scalar parameter of integration, expm is the matrix\n% exponential function int refers to a definite integral, and the\n% function\n% H(s) is defined to be\n% H(s)=(int_0^sexpm(A*tau) dtau)*B\n%\n%INPUTS: T The real, positive, scalar upper bound of the integrals.\n% A A real nXn matrix.\n% B A real nXp matrix. If this parameter is omitted or an empty\n% matrix is passed, then it is assumed that p=0, in which case H,\n% M, and W will be empty matrices.\n% Qc A symmetric positive (semi)definite nXn matrix. If omitted or an\n% empty matrix is passed, then it is assumed that Qc=eye(n,n);\n%\n%OUTPUTS: H,Q,M,W The values of the desired matrix integrals, which are\n% defined above\n%\n%Expressions for obtaining the solutions to the integrals by evaluating a\n%single matrix exponential are given in [1]. The type of linear regulator\n%problem addressed by these integrals is given in [2].\n%\n%REFERENCES:\n%[1] C. F. Van Loan, \"Computing Integrals Involving the Matrix\n% Exponential,\" IEEE Transactions on Automatic Control, vol. AC-23, no.\n% 3, pp. 395-404, Jun. 1967.\n%[2] E. S. Armstrong and A. K. Caglayan, \"An algorithm for the weighting\n% matrices in the sampled-data optimal linear regulator problem,\"\n% National Aeronautics and Space Administration, Langley Research\n% Center, Hampton, VA, Tech. Rep. NASA TN D-8372, Dec. 1976.\n%\n%September 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(A,1);\n\nif(nargin<4||isempty(Qc))\n Qc=eye(n,n); \nend\n\nif(isempty(B)||nargin<2)\n p=0;\n B=zeros(n,p);\nelse\n p=size(B,2);\nend\n\nC=[-A.', eye(n,n), zeros(n,n+p);\n zeros(n,n), -A.', Qc, zeros(n,p);\n zeros(n,2*n), A, B;\n zeros(p,3*n+p)];\n\nCExp=expm(C*T);\n\nF3=CExp((2*n+1):(3*n),(2*n+1):(3*n));\nG2=CExp((n+1):(2*n),(2*n+1):(3*n));\nG3=CExp((2*n+1):(3*n),(3*n+1):(3*n+p));\nH2=CExp((n+1):(2*n),(3*n+1):(3*n+p));\nK1=CExp(1:n,(3*n+1):(3*n+p));\n\nH=G3;\nQ=F3.'*G2;\nM=F3.'*H2;\n\ntemp=B.'*F3.'*K1;\nW=temp+temp.';\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Specific_Integrals/matExpIntFam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7554667665926885}} {"text": "function geometry_test016 ( )\n\n%*****************************************************************************80\n%\n%% GEOMETRY_TEST016 tests CIRCLE_IMP_POINTS_2D, POLYGON_AREA_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n center(1:2,1) = [ 5.0; -2.0 ];\n r = 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEOMETRY_TEST016\\n' );\n fprintf ( 1, ' CIRCLE_IMP_POINTS_2D gets points on a circle;\\n' );\n fprintf ( 1, ' POLYGON_AREA_2D finds the area of a polygon.\\n' );\n\n circle_imp_print_2d ( r, center, ' The implicit circle:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The area = %f\\n', pi * r * r );\n\n n = 8;\n\n p = circle_imp_points_2d ( r, center, n );\n\n r8mat_print ( 2, n, p, ' Sample results:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For any N, the sampled points define a polygon\\n' );\n fprintf ( 1, ' whose area approximates the circle area.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Area\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 3 : 24\n\n p = circle_imp_points_2d ( r, center, n );\n result = polygon_area_2d ( n, p );\n fprintf ( 1, ' %6d %12f\\n', n, result );\n\n end\n\n return\nend\n", "meta": {"author": "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_test016.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.755419359958428}} {"text": "% Surface fit artifact removal\n[x,y] = meshgrid(0:.01:1);\nz0 = exp(x+y);\n\nznan = z0;\nznan(20:50,40:70) = NaN;\nznan(30:90,5:10) = NaN;\nznan(70:75,40:90) = NaN;\n\nz = inpaint_nans(znan,3);\n\n% Comparison to griddata\nk = isnan(znan);\nzk = griddata(x(~k),y(~k),z(~k),x(k),y(k));\nzg = znan;\nzg(k) = zk;\n\nclose all\nfigure\nsurf(z0)\ntitle 'Original surface'\n\nfigure\nsurf(znan)\ntitle 'Artifacts (large holes) in surface'\n\nfigure\nsurf(zg)\ntitle(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])\n\nfigure\nsurf(z)\ntitle 'Inpainted surface'\n\nfigure\nsurf(zg-z0)\ntitle 'Griddata error surface'\n\nfigure\nsurf(z-z0)\ntitle 'Inpainting error surface (Note z-axis scale)'\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/Inpaint_nans/demo/inpaint_nans_demo_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7554193582696097}} {"text": "function [ x, seed ] = hyperball01_sample ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% HYPERBALL01_SAMPLE uniformly samples the unit hyperball.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 05 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Russell Cheng,\n% Random Variate Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998, pages 168.\n%\n% Reuven Rubinstein,\n% Monte Carlo Optimization, Simulation, and Sensitivity \n% of Queueing Networks,\n% Krieger, 1992,\n% ISBN: 0894647644,\n% LC: QA298.R79.\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input/output, integer SEED, a seed for the random \n% number generator.\n%\n% Output, real X(M,N), the points.\n%\n x = randn ( m, n );\n norm = ones ( 1, m ) * ( x.^2 );\n norm = sqrt ( norm );\n for i = 1 : m\n x(i,1:n) = x(i,1:n) ./ norm(1:n);\n end\n\n for j = 1 : n\n r = rand ( 1, 1 );\n x(1:m,j) = r ^ ( 1.0 / m ) * x(1:m,j);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hyperball_monte_carlo/hyperball01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7553471675950193}} {"text": "%% ---------------Truncated Amplitude Spectral Initializer-----------------\n\n% Intializer proposed for Truncated Amplitude Flow as given in Algorithm 1\n% of the Truncated Amplitude Flow (TAF) paper. For certain definitions and\n% descriptions, user may need to refer to equations (14, 17) and Algorithm\n% box 1 for details.\n%\n% The authors of the paper propose two different initialization schemes \n% (this function implements the second approach, described below).\n% In the first approach, one throws out the measurements of large\n% magnitude, and only keeps the remaining measurement vectors that produce\n% small measurements. These vectors are nearly orthogonal to the signal,\n% and so we approximate the signal by finding a vector that is\n% un-correlated with these measurement vectors. This requires finding the\n% smallest eigenvalue of a large matrix.\n% In the second method, the authors propose to throw out the smallest\n% measurements, and find the signal most correlated with the remaining\n% measurement vectors (which produce large measurement) by finding the\n% largest eigenvalue of a matrix. \n% For certain isometric measurement matrices, these appraoches are both\n% equivalent. However, for non-isometric matrices they differ. The\n% authors of the paper claim that it is difficult to find a small\n% eigenvector, and so they adopt the second method that requires a large\n% eigenvector. This second method, which requires the leading (largest)\n% eigenvalue/vector, is implemented here. \n% Note: in practice, small eigenvalues can be computed efficiently using\n% an Arnoldi method, and this often leads to better initializers. For an \n% implementation using the smallest eigenvalue/vector, see initNull.m.\n%\n% See the script 'testInitOrthogonal.m' for an example of proper usage of\n% this function.\n\n% PAPER TITLE:\n% Solving Systems of Random Quadratic Equations via Truncated\n% Amplitude Flow.\n\n% ARXIV LINK:\n% https://arxiv.org/pdf/1605.08285.pdf\n\n% INPUTS:\n% A: Function handle/numerical matrix for data matrix A. The rows\n% of this matrix are the measurement vectors that produce\n% amplitude measurements '\\psi'.\n% At: Function handle/numerical matrix for A transpose.\n% b0: Observed data vector consisting of amplitude measurements\n% generated from b0 = |A*x|. We assign it to 'psi' to be\n% consistent with the notation in the paper.\n% n: Length of unknown signal to be recovered by phase retrieval.\n\n% OUPTUT :\n% x0: The initial vector to be used by any solver.\n\n% Note: When a function handle is used, the value of 'n' (the length\n% of the unknown signal) and 'At' (a function handle for the\n% adjoint of 'A') must be supplied. When 'A' is numeric, the\n% values of 'At' and 'n' are ignored and inferred from the\n% arguments\n\n\n% DESCRIPTION:\n% Random vectors in high dimensions are almost always\n% orthogonal to each other. Using this very intuitive result,\n% this method computes an initial guess that is orthogonal to\n% as many measurement vectors as possible. The orthogonal\n% promoting initializer solves the limitations of the spectral\n% methods, namely heavy tailed distributions due to 4th moment\n% generating functions by using a truncation step.\n% Specifically, it removes measurement vectors that are not\n% orthogonal to the initial random guess. We form the matrix Y\n% = (1/card_I) * S_bar^T* S_bar using the truncated vectors\n% and compute the leading eigenvector. S_bar is the complement\n% of the set S. Refer to the paper for a description of S.\n\n% METHOD:\n% 1.) Find the set 'I_Bar'. I is set of indices of |I| smallest\n% measurement vectors as defined in equation(14) in the paper,\n% where |I| is the cardinality of I.I_bar is the complement of\n% I. This is done because by using I, we are required to find\n% the smallest eignevalue of a matrix formed from the data\n% vectors. However, finding the smallest eigenvalue is often\n% intractible in practice. So we find the largest eigenvalue\n% instead.\n\n% 2.) Using a mask R, form the matrix Y = (1/card_I) * S_bar^T *\n% S_bar where S_bar is the complement of the S which is defined\n% in equation (17) in the Truncated Amplitude Paper.\n\n% 3.) Compute the leading eigenvector of Y (computed in previous\n% step) and scale it according to the norm of x as described in\n% Step 3, Algorithm 1 of the paper.\n%\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n%% -----------------------------START----------------------------------\n\n\nfunction [x0] = initAmplitude(A,At,b0,n,verbose)\n\npsi = b0; % To be consistent with the notation used in the paper\n\n% If A is a matrix, infer n and At from A\nif isnumeric(A)\n n = size(A, 2);\n % Transform matrix into function form\n At = @(x) A' * x;\n A = @(x) A * x;\nend\n\nm = length(psi); % Number of measurements.\n\nif ~exist('verbose','var') || verbose\nfprintf(['Estimating signal of length %d using an orthogonal ',...\n 'initializer with %d measurements...\\n'],n,m);\nend\n\n% Cardinality of I. I is the set that contains the indices of the\n% truncated vectors. Namely, it removes measurement vectors that are\n% not orthogonal to the initial random guess\ncard_I = ceil(m/6);\n\n\n% STEP 1: Construct the set I of indices. We approximate by assuming that\n% the norm of each row of A is same.\n[~, index_array] = sort(psi, 'descend'); % Sort the data vector\nind = index_array(1: card_I); % Truncate the indexes. \n\n\n% STEP 2: Form Y\nR = zeros(m, 1);\n% Defining the mask for truncation\nR(ind) = 1; \n% Forming the truncated matrix Y according to equation (17) in referenced paper.\nY = @(x) 1/card_I * At(R.*A(x)); \n\n\n% STEP 3: Use eigs to compute leading eigenvector of Y (Y is computed in\n% previous step)\nopts = struct;\nopts.isreal = false; % Create opts struct for eigs\n[V, ~] = eigs(Y, n, 1, 'lr', opts);\n% Scale the norm to match that of x\nAV = abs(A(V));\nalpha = (AV'*psi) / ( AV'*AV );\nx0 = V*alpha;\n\nif ~exist('verbose','var') || verbose\n fprintf('Initialization finished.\\n');\nend\n\nend\n\n\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/initializers/initAmplitude.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7552974986803698}} {"text": "function [shortestPath, totalCost] = dijkstra(netCostMatrix, s, d)\n%==============================================================\n% shortestPath: the list of nodes in the shortestPath from source to destination;\n% totalCost: the total cost of the shortestPath;\n% farthestNode: the farthest node to reach for each node after performing the routing;\n% n: the number of nodes in the network;\n% s: source node index;\n% d: destination node index;\n%==============================================================\n% Code by:\n% ++by Xiaodong Wang\n% ++23 Jul 2004 (Updated 29 Jul 2004)\n% ++http://www.mathworks.com/matlabcentral/fileexchange/5550-dijkstra-shortest-path-routing\n% Modifications (simplifications) by Meral Shirazipour 9 Dec 2009\n%==============================================================\nn = size(netCostMatrix,1);\nfor i = 1:n\n % initialize the farthest node to be itself;\n farthestPrevHop(i) = i; % used to compute the RTS/CTS range;\n farthestNextHop(i) = i;\nend\n\n% all the nodes are un-visited;\nvisited(1:n) = false;\n\ndistance(1:n) = inf; % it stores the shortest distance between each node and the source node;\nparent(1:n) = 0;\n\ndistance(s) = 0;\nfor i = 1:(n-1),\n temp = [];\n for h = 1:n,\n if ~visited(h) % in the tree;\n temp=[temp distance(h)];\n else\n temp=[temp inf];\n end\n end;\n [t, u] = min(temp); % it starts from node with the shortest distance to the source;\n visited(u) = true; % mark it as visited;\n for v = 1:n, % for each neighbors of node u;\n if ( ( netCostMatrix(u, v) + distance(u)) < distance(v) )\n distance(v) = distance(u) + netCostMatrix(u, v); % update the shortest distance when a shorter shortestPath is found;\n parent(v) = u; % update its parent;\n end; \n end;\nend;\n\nshortestPath = [];\nif parent(d) ~= 0 % if there is a shortestPath!\n t = d;\n shortestPath = [d];\n while t ~= s\n p = parent(t);\n shortestPath = [p shortestPath];\n \n if netCostMatrix(t, farthestPrevHop(t)) < netCostMatrix(t, p)\n farthestPrevHop(t) = p;\n end;\n if netCostMatrix(p, farthestNextHop(p)) < netCostMatrix(p, t)\n farthestNextHop(p) = t;\n end;\n\n t = p; \n end;\nend;\n\ntotalCost = distance(d);\n\n%return;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32513-k-shortest-path-yens-algorithm/MATLAB_kShortestPath_Yen's algorithm/dijkstra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7552269036690284}} {"text": "function [F,totalCost,exitCode]=minCostFlow(AMat,CMat,b,maxIter)\n%%MINCOSTFLOW Solve the minimum cost flow problem using a strong polynomial\n% time cycle cancelling algorithm that works with non-integer\n% costs. Minimum cost flow problems include transportation\n% problems.\n%\n%INPUTS: AMat An NXN matrix of costs in a directed graph such that\n% AMat(i,j) is the cost of an edge going from vertex i to\n% vertex j. If no vertex goes from node i to node j, then a\n% cost of 0 should be inserted.\n% CMat An NXN matrix of capacities of the edges in the graph.\n% CMat(i,j) is the capacity of an edge from node i to node j.\n% If no edge exists, then a capacity of zero should be used. It\n% is assumed that all capacities are finite.\n% b An NX1 vector of the supply provided by each node. It is\n% required that sum(b)=0.\n% maxIter An optional parameter specifying the maximum number of\n% iterations that should be performed by the algorithm. If\n% omitted, a maximum of 100+10N iterations is used.\n%\n%OUTPUTS: F The flow matrix. F(i,j) is the amount of flow going from node i\n% to node j. Note that F(i,j)=-F(j,i). If the algorithm could not\n% obtain an initial feasible solution, then an empty matrix is\n% returned. If the maximum number of iterations is exceeded, then\n% the algorithm will return a feasible solution that is not\n% optimal.\n% totalCost The total cost of the flow. This is the quantity being\n% minimized. If the algorithm could not obtain an initial\n% feasible solution, then an empty matrix is returned.\n% exitCode A parameter indicating whether an error occurred or whether the\n% algorithm terminated successfully. Possible values are:\n% 0 The algorithm was successful.\n% 1 No feasible solution could be found.\n% 2 The maximum number of iterations was reached.\n% 3 Inputs are invalid. This means that either C contains NaN\n% values, sum(b)~=0 or AMat contains nonfinite values.\n%\n%The minimum cost flow problems seeks to find a flow F to minimize\n%sum(sum(AMat.*F)) subject to the constraints:\n%4) Total Vertex Flow: sum(F(i,:))=b(i) for all i.\n%2) Capacity Constraint: 0<=F(u,v)<=CMat(u,v)\n%3) Skew Symmetry: F(u,v)=-F(v,u)\n%Whereas the maximum flow problem, which is solved in the function\n%solveMaxFlowEdmondsKarp seeks to maximize the flow between two nodes the\n%minimum cost flow problem seeks to minimize the total cost of a fixed\n%amount of flow.\n%\n%The strong polynomial cycle cancelling algorithm of [1] is used. However,\n%the epsilon-based convergence acceleration method described in [1] is not\n%used. Rather, the algorithm is more similar to the simple cycle\n%cancellation algorithm of Chapter 7.2 of [2], except the minimum mean\n%cycle is always augmented rather than any negative cost cycle.\n%\n%The complexity of the non-epsilon accelerated algorithm in [1] is bounded\n%as O(N^2*m^3*log(N)), where N is the number of vertices in the graph, and\n%m is the number of edges. The true complexity depends on the efficiency of\n%the function computeResidualCapacity, which is used to obtain the negative\n%cycles.\n%\n%EXAMPLE: This is example 7.1 in Chapter 7.2 of [2].\n% AMat=[0, 4, 1, 0;\n% 0, 0, 2, 5;\n% 0, 3, 0, 2;\n% 0, 0, 0, 0];\n% CMat=[0, 2, 2, 0;\n% 0, 0, 1, 1;\n% 0, 1, 0, 1;\n% 0, 0, 0, 0];%Capacity matrix\n% b=[2;0;0;-2];\n% [F,totalCost,exitCode]=minCostFlow(AMat,CMat,b)\n%One will get a flow matrix of \n% F =[ 0 0 2 0;\n% 0 0 -1 1;\n% -2 1 0 1;\n% 0 -1 -1 0];\n%having a total cost of 12.\n%\n%OTHER EXAMPLES: Transportation problems can be transformed into minimum\n%cost flow problems and vice versa, as shown in Chapters 7.4 and 7.5 of\n%[2]. Thus, the examples in the comments to the function\n%solveTransportationProblem can be taken as additional examples of the\n%minimum cost flow problem.\n%\n%REFERENCES:\n%[1] A. V. Goldberg and R. E. Tarjan, \"Finding minimum-cost circulations\n% by canceling negative cycles,\" Journal of the Association for\n% Computing Machinery, vol. 36, no. 4, pp. 873-886, Oct. 1989.\n%[2] C. H. Papadimitriou and K. Steiglitz, Combinatorial Optimization:\n% Algorithms and Complexity. Englewood Cliffs, NJ: Prentice-Hall Inc.,\n% 1982.\n%\n%July 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumVertex=length(b);\n\nif(nargin<5||isempty(maxIter))\n maxIter=100+10*numVertex;\nend\n\nif(any(isnan(CMat(:)))||sum(b)~=0||any(~isfinite(AMat(:))))\n exitCode=3;%The problem is infeasible. \n F=[];\n totalCost=[];\n return;\nend\n\n%Step 1: Find a feasible flow.\n%In this step, we must find a feasible flow F. This is a flow that\n%satisfies constraints 1-3 but does not necessarily minimize the cost\n%sum(sum(AMat.*F)). This can be done by ignoring costs and solving a\n%maximum flow problem based only on the constraints. The maximum flow\n%problem does not have demand constraints on all of the nodes, rather it\n%only has them on a sink and source which are added.\n%\n%To enforce constraint 1, we have to create a network with an artificial\n%sink and source. If b(i) is positive, then we need an arc from the source\n%to that node with capacity b(i). If b(i) is negative, then we need an arc\n%from the sink to that node with capacity -b(i). If the maximum flow\n%problem solved on the modified graph saturates all of the edges coming out\n%of the source, then the problem is feasible.\n\n%Augment the capacity matrix.\nCMatAugment=[CMat,zeros(numVertex,2);\n zeros(2,numVertex+2)];\n\nsource=numVertex+1;\nsink=numVertex+2;\ntotalFlowIn=0;\nfor curVertex=1:numVertex\n if(b(curVertex)>0)\n CMatAugment(source,curVertex)=b(curVertex);\n totalFlowIn=totalFlowIn+b(curVertex);\n else\n CMatAugment(curVertex,sink)=-b(curVertex);\n end\nend\n\n[maxFlow,F]=solveMaxFlowEdmondsKarp(CMatAugment,source,sink);\n\n%Check whether all of the source nodes have been saturated. This is true if\n%the total flow in equals the maximum flow found. A comparison to an\n%epsilon value is used as it is not clear whether it can be guaranteed\n%within finite precision bounds that the two quantities will always be\n%equal for feasible problems, though they seem to generally be equal for\n%feasible problems.\nif(abs(maxFlow-totalFlowIn)>eps(totalFlowIn))\n exitCode=1;%The problem is infeasible. \n F=[];\n totalCost=[];\n return;\nend\n\n%Get rid of the artificial source and sink nodes from the flow matrix.\nF=F(1:numVertex,1:numVertex);\n\n%To make the computation of the residual matrix simpler, we will transform\n%the cost matrix. This simplifies the computation of costs in the residual\n%flow network.\nAMatOrig=AMat;\nAMat=AMat-AMat';\n\n%Compute the residual flow network, also known as the incremental flow\n%network. Definition 7.3 from Chapter 7.2 of [2] explains what the\n%incremental flow network is and how the costs are assigned. The residual\n%capacity is updated during augmentation of the flow matrix F, so that it\n%need not be recomputed each loop.\n\n%Find the capacity of the residual flow network.\nresidualCapacity=CMat-F;\nfor curIter=1:maxIter\n %Step 2: Find the minimum mean cost cycle with respect to the costs on\n % the residual flow network, also known as the incremental flow\n % network.\n \n %The costs associated with the residual flow network are AMat(i,j) on\n %forward nodes and -AMat(i,j) on backward nodes. Hence the reason why\n %we replaced AMat with AMat-AMat'.\n costMat=Inf(numVertex,numVertex);\n costMat(residualCapacity~=0)=AMat(residualCapacity~=0);\n \n [minCycleMean,cycleVertices]=findMinMaxCycleMean(costMat,true);\n \n if(minCycleMean>=0)\n exitCode=0;\n FP=F;\n FP(F<0)=0;\n totalCost=sum(sum(FP.*AMatOrig));\n return;\n end\n \n %Step 3: The minimum mean cycle is negative. We must cancel the minimum\n % mean cycle. That is, we augment the graph along the negative\n % cycle. We adjust the flow around the cycle by as much\n % as possible without violating capacity constraints, so that\n % the negative cycle no longer exists. \n \n %Determine the minimum residual capacity of the cycle.\n numVertexInCycle=length(cycleVertices);\n minCapacity=Inf;\n startVertex=cycleVertices(1);\n for curEndVertex=2:numVertexInCycle\n endVertex=cycleVertices(curEndVertex);\n \n curCapacity=residualCapacity(startVertex,endVertex);\n minCapacity=min(curCapacity,minCapacity);\n \n startVertex=endVertex;\n end\n \n %Push the amount of flow around the negative cycle that will saturate\n %the minimum capacity arc on the minimum mean cycle. Note that the skew\n %symmetry constraint dictates how the flow is to be added (how\n %augmentation is performed).\n startVertex=cycleVertices(1);\n for curEndVertex=2:numVertexInCycle\n endVertex=cycleVertices(curEndVertex);\n \n %Update the flow\n F(startVertex,endVertex)=F(startVertex,endVertex)+minCapacity;\n F(endVertex,startVertex)=F(endVertex,startVertex)-minCapacity;\n\n %Update the residual flow network. The update is opposite that of\n %F, because the residual flow is CMat-F.\n residualCapacity(startVertex,endVertex)=residualCapacity(startVertex,endVertex)-minCapacity;\n residualCapacity(endVertex,startVertex)=residualCapacity(endVertex,startVertex)+minCapacity;\n \n startVertex=endVertex;\n end\nend\n\n%Find the cost of the flow.\nFP=F;\nFP(F<0)=0;\ntotalCost=sum(sum(FP.*AMatOrig));\n\n%If we are here, the maximum number of iterations has elapsed. We will\n%check whether convergence occurred on the final iteration, and it not,\n%then we will return accordingly.\ncostMat=Inf(numVertex,numVertex);\ncostMat(residualCapacity~=0)=AMat(residualCapacity~=0);\n\nminCycleMean=findMinMaxCycleMean(costMat,true);\nif(minCycleMean>=0)\n exitCode=0;\n return;\nend\n\n%If we get here, then the algorithm terminated without cancelling all\n%negative cycles. Thus, the algorithm did not converge.\nexitCode=2;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Graph_Algorithms/minCostFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7552268947062182}} {"text": "function [xi,w]=fifthOrderPyramidCubPoints()\n%%FIFTHORDERPYRAMIDCUBPOINTS Generate fifth-order cubature points for\n% integration over a 3-dimensional pyramid with a square base with the\n% peak vertex at (0,0,1) and the base vertices at (1,-1,-1), (-1,-1,-1),\n% (-1,1,-1), and (1,1,-1).\n% \n%INPUTS: None\n%\n%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard\n% square pyramid.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard square pyramid (8/3).\n%\n%This function implements the points given in [1] (15 points).\n%\n%EXAMPLE:\n%We compare a 5th-order moment computed using these cubature points\n%to one computed using monomialIntPyramid. The results are the same within\n%typical finite precision limits.\n% [xi,w]=fifthOrderPyramidCubPoints();\n% alpha=[2;2;1];\n% theMoment=findMomentFromSamp(alpha,xi,w);\n% intVal=monomialIntPyramid(alpha);\n% RelErr=(theMoment-intVal)/intVal\n%\n%REFERENCES:\n%[1] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=[ 0, 0, 0.45971576156501338586164265377920811314, 0.18249431975770692138374895897213800931;\n 0, 0, -0.39919795837246198593385139590712322914, 0.45172563864726406056400285032640105704;\n 0, 0, -0.99999998701645569241460017355590234925, 0.15654542887619877154120304977336547704;\n 0.70652603154632457420722562974792066862, 0, -0.75, 0.20384344839498724639142514342645843799;\n 0, 0.70652603154632457420722562974792066862, -0.75, 0.20384344839498724639142514342645843799;\n-0.70652603154632457420722562974792066862, 0, -0.75, 0.20384344839498724639142514342645843799;\n 0, -0.70652603154632457420722562974792066862, -0.75, 0.20384344839498724639142514342645843799;\n 0.70511712277882760181079385797948261057, 0.70511712277882760181079385797948261057, -0.87777618587595407108464357252416911085, 0.10578907087905457654220386143818487109;\n 0.70511712277882760181079385797948261057, -0.70511712277882760181079385797948261057, -0.87777618587595407108464357252416911085, 0.10578907087905457654220386143818487109;\n-0.70511712277882760181079385797948261057, 0.70511712277882760181079385797948261057, -0.87777618587595407108464357252416911085, 0.10578907087905457654220386143818487109;\n-0.70511712277882760181079385797948261057, -0.70511712277882760181079385797948261057, -0.87777618587595407108464357252416911085, 0.10578907087905457654220386143818487109;\n 0.43288286410354097685000790909815143591, 0.43288286410354097685000790909815143591, -0.15279732576055038842025517341026975071, 0.15934280057233240536079894703404722173;\n 0.43288286410354097685000790909815143591, -0.43288286410354097685000790909815143591, -0.15279732576055038842025517341026975071, 0.15934280057233240536079894703404722173;\n-0.43288286410354097685000790909815143591, 0.43288286410354097685000790909815143591, -0.15279732576055038842025517341026975071, 0.15934280057233240536079894703404722173;\n-0.43288286410354097685000790909815143591, -0.43288286410354097685000790909815143591, -0.15279732576055038842025517341026975071, 0.15934280057233240536079894703404722173];\n\nw=M(:,4);\nxi=M(:,1:3)';\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Pyramid/fifthOrderPyramidCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7551644672341093}} {"text": "function V=covnw(data,nlag,demean)\n% Long-run covariance estimation using Newey-West (Bartlett) weights \n% \n% USAGE:\n% [V] = covnw(DATA)\n% [V] = covnw(DATA,NLAG,DEMEAN)\n%\n% INPUTS:\n% DATA - T by K vector of dependent data\n% NLAG - Non-negative integer containing the lag length to use. If empty or not included,\n% NLAG=min(floor(1.2*T^(1/3)),T) is used \n% DEMEAN - Logical true or false (0 or 1) indicating whether the mean should be subtracted when\n% computing the covariance \n%\n% OUTPUTS:\n% V - A K by K covariance matrix estimated using Newey-West (Bartlett) weights\n% \n% COMMENTS:\n%\n% EXAMPLES:\n% Simulate an AR(1)\n% y = armaxfilter_simulate(1000,0,1,.9);\n% Newey-West covariance with automatic BW selection\n% lrcov = covnw(y)\n% Newey-West covariance with 10 lags\n% lrcov = covnw(y, 10)\n% Newey-West covariance with 10 lags and no demeaning\n% lrcov = covnw(y, 10, 0)\n%\n% See also COVVAR\n \n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 5/1/2007\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nT=size(data,1);\nif nargin==1\n nlag=min(floor(1.2*T^(1/3)),T);\n demean=true;\nelseif nargin==2\n demean=true; \nend \nif isempty(nlag)\n nlag=min(floor(1.2*T^(1/3)),T);\nend\nif isempty(demean)\n demean=true;\nend\nif ~ismember(demean,[0 1]) \n error('DEMEAN must be either logical true or false.')\nend\nif floor(nlag)~=nlag || nlag<0 \n error('NLAG must be a non-negative integer.')\nend\nif ndims(data)>2\n error('DATA must be a T by K matrix of data.')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif demean\n data=data-repmat(mean(data),T,1);\nend\n \n% NW weights\nw=(nlag+1-(0:nlag))./(nlag+1);\n% Start the covariance\nV=data'*data/T;\nfor i=1:nlag\n Gammai=(data((i+1):T,:)'*data(1:T-i,:))/T;\n GplusGprime=Gammai+Gammai';\n V=V+w(i+1)*GplusGprime;\nend\n\n\n", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/utility/covnw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7551084576549503}} {"text": "%% Optimization of a simple (Rosenbrock) function, with no constraints\n% The unconstrained solution is at [1,1]\nrosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;\n\n% With no constraints, operation simply passes through\n% directly to fminsearch. The solution should be [1 1]\nxsol = fminsearchbnd(rosen,[3 3])\n\n%% Full lower and upper bound constraints which will all be inactive\nxsol = fminsearchbnd(rosen,[3 3],[-1 -1],[4 4])\n\n%% Only lower bound constraints\nxsol = fminsearchbnd(rosen,[3 3],[2 2])\n\n%% Only upper bound constraints\nxsol = fminsearchbnd(rosen,[-5 -5],[],[0 0])\n\n%% Dual constraints\nxsol = fminsearchbnd(rosen,[2.5 2.5],[2 2],[3 3])\n\n%% Dual constraints, with an infeasible starting guess\nxsol = fminsearchbnd(rosen,[0 0],[2 2],[3 3])\n\n%% Mixed constraints\nxsol = fminsearchbnd(rosen,[0 0],[2 -inf],[inf 3])\n\n%% Provide your own fminsearch options\nopts = optimset('fminsearch');\nopts.Display = 'iter';\nopts.TolX = 1.e-12;\n\nn = [10,5];\nH = randn(n);\nH=H'*H;\nQuadraticfun = @(x) x*H*x';\n\n% Global minimizer is at [0 0 0 0 0].\n% Set all lower bound constraints, all of which will\n% be active in this test.\nLB = [.5 .5 .5 .5 .5];\nxsol = fminsearchbnd(Quadraticfun,[1 2 3 4 5],LB,[],opts)\n\n%% Exactly fix one variable, constrain some others, and set a tolerance\nopts = optimset('fminsearch');\nopts.TolFun = 1.e-12;\n\nLB = [-inf 2 1 -10];\nUB = [ inf inf 1 inf];\nxsol = fminsearchbnd(@(x) norm(x),[1 3 1 1],LB,UB,opts)\n\n%% All the standard outputs from fminsearch are still returned\n[xsol,fval,exitflag,output] = fminsearchbnd(@(x) norm(x),[1 3 1 1],LB,UB)\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8277-fminsearchbnd-fminsearchcon/FMINSEARCHBND/test/test_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7551084505519812}} {"text": "function d=v_distchpf(pf1,pf2,mode)\n%V_DISTCHPF calculates the cosh spectral distance between power spectra D=(PF1,PF2,MODE)\n%\n% Inputs: PF1,PF2 Power spectra to be compared. Each row represents a power spectrum: the first\n% and last columns represent the DC and Nyquist terms respectively.\n% PF1 and PF2 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 PF1 to every row of PF2\n% 'd' Calculate only the distance between corresponding rows of PF1 and PF2\n% The default is 'd' if PF1 and PF2 have the same number of rows otherwise 'x'.\n% \n% Output: D If MODE='d' then D is a column vector with the same number of rows as the shorter of PF1 and PF2.\n% If MODE='x' then D is a matrix with the same number of rows as PF1 and the same number of columns as PF2'.\n%\n% The COSH spectral distance is the average over +ve and -ve frequency of \n%\n% cosh(log(p1/p2))-1 = (p1-p2)^2/(2p1*p2) = (p1/p2 + p2/p1)/2 - 1\n%\n% The COSH distance is a symmetrical version of the Itakura-Saito distance: v_distchpf(x,y)=(v_distispf(x,y)+v_distispf(y,x))/2\n\n% The Cosh distance can also be calculated directly from AR coefficients; providing np is large\n% enough, the values of d0 and d1 in the following will be very similar:\n%\n% np=255; d0=v_distchar(ar1,ar2); d1=v_distchpf(v_lpcar2pf(ar1,np),v_lpcar2pf(ar2,np))\n%\n\n% Ref: A.H.Gray Jr and J.D.Markel, \"Distance measures for speech processing\", IEEE ASSP-24(5): 380-391, Oct 1976\n% L. Rabiner abd B-H Juang, \"Fundamentals of Speech Recognition\", Section 4.5, Prentice-Hall 1993, ISBN 0-13-015157-2\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: v_distchpf.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf1,p2]=size(pf1);\np1=p2-1;\nnf2=size(pf2,1);\nif nargin<3 | isempty(mode) mode='0'; end\nif any(mode=='d') | (mode~='x' & nf1==nf2)\n nx=min(nf1,nf2);\n r=pf1(1:nx,:)./pf2(1:nx,:);\n q=r+r.^(-1);\n d=(2*sum(q(:,2:p1),2)+q(:,1)+q(:,p2))/(4*p1)-1;\nelse\n r=permute(pf1(:,:,ones(1,nf2)),[1 3 2])./permute(pf2(:,:,ones(1,nf1)),[3 1 2]);\n q=r+r.^(-1);\n d=(2*sum(q(:,:,2:p1),3)+q(:,:,1)+q(:,:,p2))/(4*p1)-1;\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_distchpf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7551084494066553}} {"text": "function h = p37_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P37_H evaluates the Hessian for problem 37.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n arg = - ( x(1) - pi )^2 - ( x(2) - pi )^2;\n dargdx1 = - 2.0 * ( x(1) - pi );\n dargdx2 = - 2.0 * ( x(2) - pi );\n\n factor = cos ( x(2) ) * ( sin ( x(1) ) - cos ( x(1) ) * dargdx1 );\n dfdx1 = cos ( x(2) ) * ( cos ( x(1) ) + sin ( x(1) ) * dargdx1 + 2.0 * cos ( x(1) ) );\n dfdx2 = - sin ( x(2) ) * ( sin ( x(1) ) - cos ( x(1) ) * dargdx1 );\n\n h(1,1) = ( dfdx1 + factor * dargdx1 ) * exp ( arg );\n h(1,2) = ( dfdx2 + factor * dargdx2 ) * exp ( arg );\n\n factor = cos ( x(1) ) * ( sin ( x(2) ) - cos ( x(2) ) * dargdx2 );\n dfdx1 = - sin ( x(1) ) * ( sin ( x(2) ) - cos ( x(2) ) * dargdx2 );\n dfdx2 = cos ( x(1) ) * ( cos ( x(2) ) + sin ( x(2) ) * dargdx2 ...\n + 2.0 * cos ( x(2) ) );\n\n h(2,1) = ( dfdx1 + factor * dargdx1 ) * exp ( arg );\n h(2,2) = ( dfdx2 + factor * dargdx2 ) * exp ( arg );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p37_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7551084464278335}} {"text": "function value = p19_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P19_F evaluates the integrand for problem 19.\n%\n% Dimension:\n%\n% DIM_NUM is arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% Z defaults to (1/3,1/3,...,1/3). \n% You can reset Z by calling P19_R8VEC.\n%\n% Integrand:\n%\n% f(x) = product ( sqrt ( abs ( x(1:dim_num) - z(1:dim_num) ) ) )\n%\n% Exact Integral:\n%\n% With Z as given, \n%\n% (2/3)**DIM_NUM * ( (2/3)**(3/2) + (1/3)**(3/2) )**DIM_NUM\n%\n% or approximately 0.49**DIM_NUM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arnold Krommer, Christoph Ueberhuber,\n% Numerical Integration on Advanced Systems,\n% Springer, 1994,\n% ISBN: 3540584102,\n% LC: QA299.3.K76.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n z = [];\n z = p19_r8vec ( 'G', 'Z', dim_num, z );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n value(point) = prod ( sqrt ( abs ( x(1:dim_num,point) - z(1:dim_num)' ) ) );\n end\n\n p19_i4 ( 'I', '#', point_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p19_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7551084446713425}} {"text": "function y = contract(x,i,j)\n%CONTRACT Contract tensor along two dimensions (array trace).\n%\n% Y = CONTRACT(X,I,J) contracts the entries of X along dimensions I\n% and J. Contraction is a generalization of matrix trace. In other\n% words, the trace is performed along the two-dimensional slices\n% defined by dimensions I and J. It is possible to implement tensor\n% multiplication as an outer product followed by a contraction.\n%\n% Examples\n% X = tensor(rand(4,3,2)); Y = tensor(rand(3,2,4));\n% Z1 = ttt(X,Y,1,3); %<-- Normal tensor multiplication\n% Z2 = contract(ttt(X,Y),1,6); %<-- Outer product + contract\n% norm(Z1-Z2) %<-- Should be zero\n%\n% See also TENSOR, TENSOR/TTT.\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% Error checking\nif x.size(i) ~= x.size(j)\n error('Must contract along equally sized dimensions');\nend\n\n% Error checking\nif i == j\n error('Must contract along two different dimensions');\nend\n\n% Easy case - returns a scalar\nif ndims(x) == 2\n y = trace(x.data);\n return;\nend\n\n% Remaining dimensions after trace\nremdims = setdiff(1:ndims(x),[i j]);\n\n% Size for y\nnewsize = x.size(remdims);\n\n% Total size of remainder\nm = prod(newsize);\n\n% Number of items to add for trace\nn = x.size(i);\n\n% Permute trace dimensions to the end\nx = permute(x, [remdims i j]);\n\n% Reshape data to be 3D\ndata = reshape(x.data, m, n, n);\n\n% Add diagonal entries for each slice\nnewdata = zeros(m,1);\nfor i = 1:n\n newdata = newdata + data(:,i,i);\nend\n\n% Reshape result\nif numel(newsize) > 1\n newdata = reshape(newdata,newsize);\nend\ny = tensor(newdata,newsize);\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/@tensor/contract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.755108439401869}} {"text": "function value = p07_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P07_F evaluates the integrand for problem 07.\n%\n% Dimension:\n%\n% N arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integrand:\n%\n% product ( pi / 2 ) * sin ( pi * x(1:dim_num) )\n%\n% Exact Integral:\n%\n% 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n value(point) = prod ( 0.5 * pi * sin ( pi * x(1:dim_num,point) ) );\n end\n\n p07_i4 ( 'I', '#', point_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p07_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7551084376453778}} {"text": "function [Q, R] = gs_c(A)\n%GS_C Classical Gram-Schmidt QR factorization.\n% [Q, R] = GS_C(A) uses the classical Gram-Schmidt method to compute the\n% factorization A = Q*R for m-by-n A of full rank,\n% where Q is m-by-n with orthonormal columns and R is n-by-n.\n\n% Reference:\n% N. J. Higham, Accuracy and Stability of Numerical Algorithms,\n% Second edition, Society for Industrial and Applied Mathematics,\n% Philadelphia, PA, 2002; sec 19.8.\n\n[m, n] = size(A);\nQ = zeros(m,n);\nR = zeros(n);\n\nfor j=1:n\n R(1:j-1,j) = Q(:,1:j-1)'*A(:,j);\n temp = A(:,j) - Q(:,1:j-1)*R(1:j-1,j);\n R(j,j) = norm(temp);\n Q(:,j) = temp/R(j,j);\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/utilities/matrixcomp/gs_c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7550540974012513}} {"text": "% EX_LAPLACE_SQUARE: solve the Poisson problem in the unit square with a B-spline discretization.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nclear problem_data \n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_square.txt';\n\n% Type of boundary conditions for each side of the domain\nproblem_data.nmnn_sides = [];\nproblem_data.drchlt_sides = [1 2 3 4];\n\n% Physical parameters\nproblem_data.c_diff = @(x, y) ones(size(x));\n\n% Source and boundary terms\nproblem_data.f = @(x, y) zeros (size (x));\nproblem_data.g = @test_square_g_nmnn;\nproblem_data.h = @(x, y, ind) exp (x) .* sin(y);\n\n% Exact solution (optional)\nproblem_data.uex = @(x, y) exp (x) .* sin (y);\nproblem_data.graduex = @(x, y) cat (1, ...\n reshape (exp(x).*sin(y), [1, size(x)]), ...\n reshape (exp(x).*cos(y), [1, size(x)]));\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nclear method_data\nmethod_data.degree = [3 3]; % Degree of the splines\nmethod_data.regularity = [2 2]; % Regularity of the splines\nmethod_data.nsub = [9 9]; % Number of subdivisions\nmethod_data.nquad = [4 4]; % Points for the Gaussian quadrature rule\n\n% 3) CALL TO THE SOLVER\n\n[geometry, msh, space, u] = solve_laplace (problem_data, method_data);\n\n% 4) POST-PROCESSING\n% 4.1) EXPORT TO PARAVIEW\n\noutput_file = 'Square_BSP_Deg3_Reg2_Sub9';\n\nvtk_pts = {linspace(0, 1, 20), linspace(0, 1, 20)};\nfprintf ('The result is saved in the file %s \\n \\n', output_file);\nsp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')\n\n% 4.2) PLOT IN MATLAB. COMPARISON WITH THE EXACT SOLUTION\n\n[eu, F] = sp_eval (u, space, geometry, vtk_pts);\n[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));\nsubplot (1,2,1)\nsurf (X, Y, eu)\ntitle ('Numerical solution'), axis tight\nsubplot (1,2,2)\nsurf (X, Y, problem_data.uex (X,Y))\ntitle ('Exact solution'), axis tight\n\n% Display errors of the computed solution in the L2 and H1 norm\n[error_h1, error_l2] = ...\n sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex)\n\n%!demo\n%! ex_laplace_square\n\n%!test\n%! problem_data.geo_name = 'geo_square.txt';\n%! problem_data.nmnn_sides = [];\n%! problem_data.drchlt_sides = [1 2 3 4];\n%! problem_data.c_diff = @(x, y) ones(size(x));\n%! problem_data.f = @(x, y) zeros (size (x));\n%! problem_data.g = @test_square_g_nmnn;\n%! problem_data.h = @(x, y, ind) exp (x) .* sin(y);\n%! problem_data.uex = @(x, y) exp (x) .* sin (y);\n%! problem_data.graduex = @(x, y) cat (1, ...\n%! reshape (exp(x).*sin(y), [1, size(x)]), ...\n%! reshape (exp(x).*cos(y), [1, size(x)]));\n%! method_data.degree = [3 3]; % Degree of the splines\n%! method_data.regularity = [2 2]; % Regularity of the splines\n%! method_data.nsub = [9 9]; % Number of subdivisions\n%! method_data.nquad = [4 4]; % Points for the Gaussian quadrature rule\n%! [geometry, msh, space, u] = solve_laplace (problem_data, method_data);\n%! [error_h1, error_l2] = ...\n%! sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex);\n%! assert (msh.nel, 81)\n%! assert (space.ndof, 144)\n%! assert (error_h1, 9.86428525677199e-06, 1e-14)\n%! assert (error_l2, 1.68004134750130e-07, 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/examples/base/ex_laplace_square.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7550540954614814}} {"text": "function [q, M] = conversionMatrix2Quaternion(M, varargin)\n% conversionMatrix2Quaternion - function to convert Rotation Matrix to Quaternion coeff\n%\n% Syntax: q = conversionMatrix2Quaternion(M(3,3))\n% q = conversionMatrix2Quaternion(M(1,1),M(1,2),M(1,3),M(2,1),M(2,2),M(2,3),M(3,1),M(3,2),M(3,3))\n% q = conversionMatrix2Quaternion([theta, psi, phi])\n% q = conversionMatrix2Quaternion(theta, psi, phi)\n%\n% Inputs:\n% M - Rotation Matrix (3,3)\n% *theta - X rotation angle (deg)\n% *psi - Y rotation angle (deg)\n% *phi - Z rotation angle (deg)\n%\n% Outputs:\n% q - quaternion values [q0 qx qy qz]\n% M - Rotation Matrix used to compute q\n%\n%\n% Other m-files required: none\n% Subfunctions: none\n% MAT-files required: none\n%\n% See also: none;\n\n% Author: Marco Borges, Ph.D. Student, Computer/Biomedical Engineer\n% UFMG, PPGEE, Neurodinamica Lab, Brazil\n% email address: marcoafborges@gmail.com\n% Website: http://www.cpdee.ufmg.br/\n% Reference: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/\n% April 2013; v2; Last revision: 2013-04-18\n% Changelog: v2 - add linear velocity extraction\n\n%------------- BEGIN CODE --------------\n% M = [m00 m01 m02;\n% m10 m11 m12;\n% m20 m21 m22];\n\nif length(M) == 1 && nargin == 8\n M = [M, varargin{1}, varargin{2}; varargin{3}, varargin{4}, varargin{5}; varargin{6}, varargin{7}, varargin{8}];\n \nelseif length(M) == 9\n M = [M(1), M(2), M(3); M(4), M(5), M(6); M(7), M(8), M(9)];\n \nelseif length(M) == 3 % [theta (x rot), psi (y rot), phi (z rot)]\n theta = M(1); psi = M(2); phi = M(3);\n M = [cos(deg2rad(psi))*cos(deg2rad(phi)), cos(deg2rad(psi))*sin(deg2rad(phi)), -sin(deg2rad(psi));\n (-cos(deg2rad(theta))*sin(deg2rad(phi)))+(sin(deg2rad(theta))*sin(deg2rad(psi))*cos(deg2rad(phi))), (cos(deg2rad(theta))*cos(deg2rad(phi)))+(sin(deg2rad(theta))*sin(deg2rad(psi))*sin(deg2rad(phi))), sin(deg2rad(theta))*cos(deg2rad(psi));\n (sin(deg2rad(theta))*sin(deg2rad(phi)))+(cos(deg2rad(theta))*sin(deg2rad(psi))*cos(deg2rad(phi))), (-sin(deg2rad(theta))*cos(deg2rad(phi)))+(cos(deg2rad(theta))*sin(deg2rad(psi))*sin(deg2rad(phi))), cos(deg2rad(theta))*cos(deg2rad(psi))];\n\nelseif length(M) == 1 && nargin == 3 % (theta (x rot), psi (y rot), phi (z rot))\n theta = M; psi = varargin{1}; phi = varargin{2};\n M = [cos(deg2rad(psi))*cos(deg2rad(phi)), cos(deg2rad(psi))*sin(deg2rad(phi)), -sin(deg2rad(psi));\n (-cos(deg2rad(theta))*sin(deg2rad(phi)))+(sin(deg2rad(theta))*sin(deg2rad(psi))*cos(deg2rad(phi))), (cos(deg2rad(theta))*cos(deg2rad(phi)))+(sin(deg2rad(theta))*sin(deg2rad(psi))*sin(deg2rad(phi))), sin(deg2rad(theta))*cos(deg2rad(psi));\n (sin(deg2rad(theta))*sin(deg2rad(phi)))+(cos(deg2rad(theta))*sin(deg2rad(psi))*cos(deg2rad(phi))), (-sin(deg2rad(theta))*cos(deg2rad(phi)))+(cos(deg2rad(theta))*sin(deg2rad(psi))*sin(deg2rad(phi))), cos(deg2rad(theta))*cos(deg2rad(psi))];\nend\n \n\ntr = M(1,1) + M(2,2) + M(3,3);\n\nif (tr > 0)\n S = sqrt(tr+1.0) * 2; % S=4*qw\n qw = 0.25 * S;\n qx = (M(3,2) - M(2,3)) / S;\n qy = (M(1,3) - M(3,1)) / S;\n qz = (M(2,1) - M(1,2)) / S;\nelseif ((M(1,1) > M(2,2)) && (M(1,1) > M(3,3)))\n S = sqrt(1.0 + M(1,1) - M(2,2) - M(3,3)) * 2; % S=4*qx\n qw = (M(3,2) - M(2,3)) / S;\n qx = 0.25 * S;\n qy = (M(1,2) + M(2,1)) / S;\n qz = (M(1,3) + M(3,1)) / S;\nelseif (M(2,2) > M(3,3))\n S = sqrt(1.0 + M(2,2) - M(1,1) - M(3,3)) * 2; % S=4*qy\n qw = (M(1,3) - M(3,1)) / S;\n qx = (M(1,2) + M(2,1)) / S;\n qy = 0.25 * S;\n qz = (M(2,3) + M(3,2)) / S;\nelse\n S = sqrt(1.0 + M(3,3) - M(1,1) - M(2,2)) * 2; % S=4*qz\n qw = (M(2,1) - M(1,2)) / S;\n qx = (M(1,3) + M(3,1)) / S;\n qy = (M(2,3) + M(3,2)) / S;\n qz = 0.25 * S;\nend\n\nq = [qw qx qy qz];\n%-------------- END CODE ---------------", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42887-conversionmatrix2quaternion/conversionMatrix2Quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7550540952417805}} {"text": "function theta = polygon3dNormalAngle(points, ind)\n%POLYGON3DNORMALANGLE Normal angle at a vertex of the 3D polygon\n%\n% THETA = polygon3DNormalAngle(POLYGON, IND)\n% where POLYGON is a set of points, and IND is index of a point in\n% polygon. The function compute the angle of the normal cone localized at\n% this vertex.\n% If IND is a vector of indices, normal angle is computed for each vertex\n% specified by IND.\n%\n% Example\n% % create an equilateral triangle in space\n% poly3d = [1 1 0;-1 0 1;0 -1 -1];\n% % compute each normal angle\n% theta = polygon3dNormalAngle(poly3d, 1:size(poly3d, 1));\n% % sum of normal angles must be equal to 2*PI for simple polygons\n% sum(theta)\n%\n% IMPORTANT NOTE: works only for convex angles ! ! ! !\n%\n% See also\n% polygons3d, faceNormalAngle\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2005-11-30\n% Copyright 2005 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n\n% number of points\nnp = size(points, 1);\n\n% number of angles to compute\nnv = length(ind);\n\ntheta = zeros(nv, 1);\n\nfor i=1:nv\n p0 = points(ind(i), :);\n \n if ind(i)==1\n p1 = points(np, :);\n else\n p1 = points(ind(i)-1, :);\n end\n \n if ind(i)==np\n p2 = points(1, :);\n else\n p2 = points(ind(i)+1, :);\n end\n \n theta(i) = pi - anglePoints3d(p1, p0, p2);\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/polygon3dNormalAngle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7550227624233137}} {"text": "function A=polyarea_signed(V)\n\n% function A=polyarea_signed(V)\n%-------------------------------------------------------------------------\n% \n%\n% \n% Background (https://demonstrations.wolfram.com/SignedAreaOfAPolygon/):\n% The formula for the area of a simple polygon can be elegantly derived\n% using Green's theorem and extended to moments of the region. S. F.\n% Bockman, \"Generalizing the Formula for Areas of Polygons to Moments,\"\n% Amer. Math. Monthly, 96(2), 1989 pp. 131-132. \n%\n%-------------------------------------------------------------------------\n%%\n\nE=[(1:size(V,1))' [(2:size(V,1))'; 1]]; %Edge array\nX=V(:,1); %X coordinates\nY=V(:,2); %Y coordinates\nXE=X(E); %X coordinates of edge points\nYE=Y(E); %Y coordinates of edge points\nA=sum(0.5*((XE(:,1).*YE(:,2))-(XE(:,2).*YE(:,1)))); %Signed area\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/polyarea_signed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.755022751604668}} {"text": "function H = circlePlane3D( center, normal, radious, theintv, normalon, color, style )\n%CIRCLEPLANE3D Summary of this function goes here\n%--------------------------------------------------------------------------\n%Generate a circle plane in 3D with the given center and radious\n%The plane is defined by the normal vector\n%theintv is the interval theta which allow you to control your polygon\n%shape\n% Example:,\n%\n% circlePlane3D([0 0 0], [1 -1 2], 5, 0.2, 1, [0 0 1], '-'); \n% circlePlane3D([3 3 -3],[0 1 1], 3, 0.1, 1, 'y', '-');\n% \n% Cheng-Yuan Wu \n% Version 1.00\n% Aug, 2012\n%--------------------------------------------------------------------------\n%generate circle polygon\nt = 0:theintv:2*pi;\nx = radious*cos(t);\ny = radious*sin(t);\nz = zeros(size(x));\n%compute rotate theta and axis\nzaxis = [0 0 1];\nnormal = normal/norm(normal);\nang = acos(dot(zaxis,normal));\naxis = cross(zaxis, normal)/norm(cross(zaxis, normal));\n% A skew symmetric representation of the normalized axis \naxis_skewed = [ 0 -axis(3) axis(2) ; axis(3) 0 -axis(1) ; -axis(2) axis(1) 0]; \n% Rodrigues formula for the rotation matrix \nR = eye(3) + sin(ang)*axis_skewed + (1-cos(ang))*axis_skewed*axis_skewed;\nfx = R(1,1)*x + R(1,2)*y + R(1,3)*z;\nfy = R(2,1)*x + R(2,2)*y + R(2,3)*z;\nfz = R(3,1)*x + R(3,2)*y + R(3,3)*z;\n%translate center\nfx = fx+center(1);\nfy = fy+center(2);\nfz = fz+center(3);\nH = fill3(fx, fy, fz, color);\nif normalon == 1\n hold on;\n H = plot3([center(1) center(1)+normal(1)],[center(2) center(2)+normal(2)],[center(3) center(3)+normal(3)],style);\nend\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/37879-circle-plane-in-3d/circlePlane3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7549835966775919}} {"text": "%MAIN_simpleHarmonicOscillator.m\n%\n% This script runs a simulation of a simple harmonic oscillator\n\n% Use: EoM_Single_Pendulum to write the equations of motion\n\nm = 1.0; % (kg) mass\nk = 1.0; % (N/m) spring constant\n\ntSpan = [0,10]; %Simulation time interval\n\nx0 = 0.5; % (m) initial position \nv0 = 0; % (m/s) initial velocit\nz0 = [x0;v0];\n\nuserFunc = @(t,z)simpleHarmonicOscillatorDynamics(t,z,m,k);\n\noptions = odeset(...\n 'AbsTol',1e-8,...\n 'RelTol',1e-8,...\n 'Vectorized','on');\n\n% Run the simulation!\nsol = ode45(userFunc,tSpan,z0,options);\n\n% Break apart solution for plotting\nnPlot = 1000;\ntime = linspace(tSpan(1),tSpan(2),nPlot);\nz = deval(sol,time); %Evaluate solution from ode45 at points in time\nx = z(1,:);\nv = z(2,:);\n\n\n% Plotting!\n\nfigure(111);clf;\n\nsubplot(2,1,1);\nplot(time,x,'k-','LineWidth',2);\nxlabel('time (s)')\nylabel('position (m)');\n\nsubplot(2,1,2);\nplot(time,v,'k-','LineWidth',2);\nxlabel('time (s)')\nylabel('velocity (m/s)');\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/simpleHarmonicOscillator/MAIN_singleHarmonicOscillator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7549493286837358}} {"text": "function x = r8mat_lt_solve ( n, a, b )\n\n%*****************************************************************************80\n%\n%% R8MAT_LT_SOLVE solves a transposed lower triangular linear system.\n%\n% Discussion:\n%\n% Given the lower triangular matrix A, the linear system to be solved is:\n%\n% A' * x = b\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of rows and columns of the matrix A.\n%\n% Input, real A(N,N), the N by N lower triangular matrix.\n%\n% Input, real B(N), the right hand side of the linear system.\n%\n% Output, real X(N), the solution of the linear system.\n%\n x(1:n) = 0.0;\n%\n% Solve L'*x = b.\n%\n for i = n : -1 : 1\n x(i) = ( b(i) - x(i+1:n) * a(i+1:n,i) ) / a(i,i);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_lt_solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7549493281958165}} {"text": "function Trans = PUMA_TransMatrices(alpha, a, d, theta)\n% This creates the Robot Manipulator Link(s) Transformation Matrix.\n% The entries of the DH Table are passed in as the parameter.\n\n%% Handle errors (if any) for the parameters passed into the function\n\n% Check for the dimensions of the parameters passed\n[~, c(1)] = size(alpha);\n[~, c(2)] = size(a);\n[~, c(3)] = size(d);\n[~, c(4)] = size(theta);\n\nif (c(1) ~= c(2) || c(1) ~= c(3) || c(1) ~= c(4))\n error('Invalid arguments. Size of all the arguments should be same')\n return\nend\n\n%% Generate the Transformation Matrices from the DH-parameters passed\n\n% Find the Transformation matrix from the first row of DH-Table\n% This will give us the position and orientation of the end of first link\n% of the Robot Manipulator\nTrans(:,:,1) = PUMA_Transformation(alpha(1), a(1), d(1), theta(1));\n\n% Find the Transformation matrix from the rest of the rows of DH-Table\n% This will give us the position and orientation of the rest of the links\n% of the Robot Manipulator\nfor i = 2:c(1)\n Trans(:,:,i)= PUMA_Transformation(alpha(i), a(i), d(i), theta(i), Trans(:,:, i-1));\nend\n\nend\n\n", "meta": {"author": "YashBansod", "repo": "Robotics-Planning-Dynamics-and-Control", "sha": "ee8984dd5f090b803c87ac9fdf4f9be625787b2b", "save_path": "github-repos/MATLAB/YashBansod-Robotics-Planning-Dynamics-and-Control", "path": "github-repos/MATLAB/YashBansod-Robotics-Planning-Dynamics-and-Control/Robotics-Planning-Dynamics-and-Control-ee8984dd5f090b803c87ac9fdf4f9be625787b2b/5_PUMA560_Robot_Simulation/PUMA-functions/PUMA_TransMatrices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7549493179907013}} {"text": "function mu = moebius ( n )\n\n%*****************************************************************************80\n%\n%% MOEBIUS returns the value of MU(N), the Moebius function of N.\n%\n% Definition:\n%\n% MU(N) is defined as follows:\n%\n% MU(N) = 1 if N = 1;\n% 0 if N is divisible by the square of a prime;\n% (-1)^K, if N is the product of K distinct primes.\n%\n% First values:\n%\n% N MU(N)\n%\n% 1 1\n% 2 -1\n% 3 -1\n% 4 0\n% 5 -1\n% 6 1\n% 7 -1\n% 8 0\n% 9 0\n% 10 1\n% 11 -1\n% 12 0\n% 13 -1\n% 14 1\n% 15 1\n% 16 0\n% 17 -1\n% 18 0\n% 19 -1\n% 20 0\n%\n% As special cases, MU(N) is -1 if N is a prime, and MU(N) is 0\n% if N is a square, cube, etc.\n%\n% The Moebius function is related to Euler's totient function:\n%\n% PHI(N) = Sum ( D divides N ) MU(D) * ( N / D ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the value to be analyzed.\n%\n% Output, integer MU, the value of MU(N).\n% If N is less than or equal to 0, MU will be returned as -2.\n% If there was not enough internal space for factoring, MU\n% is returned as -3.\n%\n if ( n <= 0 )\n mu = -2;\n return\n end\n\n if ( n == 1 )\n mu = 1;\n return\n end\n%\n% Factor N.\n%\n [ nfactor, factor, power, nleft ] = i4_factor ( n );\n\n if ( nleft ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MOEBIUS - Fatal error!\\n' );\n fprintf ( 1, ' Not enough factorization space.\\n' );\n mu = -3;\n return\n end\n\n mu = 1;\n\n for i = 1 : nfactor\n\n mu = - mu;\n\n if ( 1 < power(i) )\n mu = 0;\n return\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/moebius.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.75494080264199}} {"text": "% function vectorized_bspline_coeff\n% ------\n% \n% Input\n% vi [n x m] \n% vs: [n x m]\n% \n% see Kristin Branson's \"A Practical Review of Uniform B-splines\"\n%\n% Output\n% C [n x 1]: the coefficients\nfunction C = vectorized_bspline_coeff(vi,vs)\n \n assert(isequal(size(vi),size(vs)));\n \n % Go through conditions \n C = zeros(size(vi));\n \n sel1 = vs >= vi & vs < vi+1;\n C(sel1) = (1/6)*(vs(sel1)-vi(sel1)).^3;\n \n sel2 = vs >= vi+1 & vs < vi+2;\n C(sel2) = (1/6)*(-3*(vs(sel2)-vi(sel2)-1).^3 + 3*(vs(sel2)-vi(sel2)-1).^2 + 3*(vs(sel2)-vi(sel2)-1)+1);\n \n sel3 = vs >= vi+2 & vs < vi+3;\n C(sel3) = (1/6)*(3*(vs(sel3)-vi(sel3)-2).^3 - 6*(vs(sel3)-vi(sel3)-2).^2 + 4);\n \n sel4 = vs >= vi+3 & vs < vi+4;\n C(sel4) = (1/6)*(1-(vs(sel4)-vi(sel4)-3)).^3;\n\nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/splines/vectorized_bspline_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7549260752037628}} {"text": "function [ar,xi,kappa,ehat] = lpcana(x,M)\n% lpcana --> Linear prediction analysis.\n%\n% [ar,xi,kappa,ehat] = lpcana(x,M)\n%\n% The function performs autocorrelation based LP analysis on the\n% signal vector x using the Levinson-Durbin recursion. Thus, the\n% function finds the coefficients, ar=[1 -a(1) ... -a(M)], of an\n% M'th order forward linear predictor\n% \n% xhat(n) = a(1)*x(n-1) + a(2)*x(n-2) + ... + a(M)*x(n-M)\n%\n% such that the sum of the squares of the prediction errors\n%\n% ehat(n) = x(n) - xhat(n)\n%\n% is minimized. The reflection coefficients are returned in the\n% vector kappa, and the prediction error energies for the 0'th to\n% the M'th order solution are returned in the vector xi. Finally,\n% the residual signal, ehat, is obtained by applying the inverse\n% filter A(z) to the signal frame.\n\n% Short-term autocorrelation.\n[rx,eta] = xcorr(x,M,'biased');\n\n% LP analysis based on Levinson-Durbin recursion.\n[a,xi,kappa] = durbin(rx(M+1:2*M+1),M);\nar = [1; -a];\n\n% Prediction error signal obtained by inverse filtering.\nehat = filter(ar,1,x);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39038-celp-codec/CELP_done/lpcana.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7549260601943221}} {"text": "function Q = M2Q(M)\n% Convert from rotation matrix to quaternion form\n% See: http://skal.planet-d.net/demo/matrixfaq.htm\n%__________________________________________________________________________\n% Copyright (C) 2005-2017 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id: M2Q.m 7147 2017-08-03 14:07:01Z spm $\n\n\nd = diag(M(1:3,1:3));\nt = sum(d) + 1;\nif t>0.5\n s = sqrt(t)*2;\n Q = [(M(3,2)-M(2,3))/s (M(1,3)-M(3,1))/s (M(2,1)-M(1,2))/s 0.25*s]';\nelse\n t = find(d==max(d));\n t = t(1);\n switch(t)\n case 1\n s = 2*sqrt(1 + M(1,1) - M(2,2) - M(3,3));\n Q = [0.25*s (M(1,2)+M(2,1))/s (M(3,1)+M(1,3))/s (M(3,2)-M(2,3))/s]';\n case 2\n s = 2*sqrt(1 + M(2,2) - M(1,1) - M(3,3));\n Q = [(M(1,2)+M(2,1))/s 0.25*s (M(2,3)+M(3,2))/s (M(1,3)-M(3,1))/s ]';\n case 3\n s = 2*sqrt(1 + M(3,3) - M(1,1) - M(2,2));\n Q = [(M(3,1)+M(1,3))/s (M(2,3)+M(3,2))/s 0.25*s (M(2,1)-M(1,2))/s]';\n end\nend\nif Q(4)<0, Q = -Q; end % w must be +ve\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/M2Q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7549137734262747}} {"text": "function [fNewLat1, fNewLat2, fNewLon1, fNewLon2] = rotate_xsection(fLat1, fLat2, fLon1, fLon2, fAngle)\n\n % Compute the center of the given cross-section\n fCenterLat = fLat1 - ((fLat1 - fLat2)/2);\n fCenterLon = fLon1 - ((fLon1 - fLon2)/2);\n\n % Move the center of the cross-section to the origin\n vPos1 = [fLon1-fCenterLon; fLat1-fCenterLat];\n vPos2 = [fLon2-fCenterLon; fLat2-fCenterLat];\n\n % Compute angle in radians\n fAngle = fAngle*pi/180;\n\n % Set up the rotation matrix\n mRotate = [cos(fAngle) -sin(fAngle); sin(fAngle) cos(fAngle)];\n\n % Rotate the cross-section vectors\n vNewPos1 = mRotate * vPos1;\n vNewPos2 = mRotate * vPos2;\n\n % Move them back to their previous position\n fNewLon1 = vNewPos1(1) + fCenterLon;\n fNewLat1 = vNewPos1(2) + fCenterLat;\n fNewLon2 = vNewPos2(1) + fCenterLon;\n fNewLat2 = vNewPos2(2) + fCenterLat;\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/utils/rotate_xsection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7546777175646392}} {"text": "function [ a_lu, pivot, info ] = r8ge_fa ( a, n )\n\n%*****************************************************************************80\n%\n%% R8GE_FA factors a general matrix.\n%\n% Discussion:\n%\n% R8GE_FA is a simplified version of the LINPACK routine DGEFA.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 27 November 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the matrix to be factored.\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Output, real A_LU(LDA,N), contains an upper \n% triangular matrix and the multipliers which were used to obtain \n% it. The factorization can be written A = L * U, where L is a \n% product of permutation and unit lower triangular matrices and \n% U is upper triangular.\n%\n% Output, integer PIVOT(N), a vector of pivot indices.\n%\n% Output, integer INFO, singularity flag.\n% 0, no singularity detected.\n% nonzero, the factorization failed on the INFO-th step.\n%\n info = 0;\n a_lu(1:n,1:n) = a(1:n,1:n);\n\n for k = 1 : n-1\n%\n% Find L, the index of the pivot row.\n%\n l = k;\n for i = k+1 : n\n if ( abs ( a_lu(l,k) ) < abs ( a_lu(i,k) ) )\n l = i;\n end\n end\n\n pivot(k) = l;\n%\n% If the pivot index is zero, the algorithm has failed.\n%\n if ( a_lu(l,k) == 0.0E+00 )\n info = k;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8GE_FA - Warning!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return\n end\n%\n% Interchange rows L and K if necessary.\n%\n if ( l ~= k )\n [ a_lu(l,k), a_lu(k,k) ] = r8_swap ( a_lu(l,k), a_lu(k,k) );\n end\n%\n% Normalize the values that lie below the pivot entry A(K,K).\n%\n a_lu(k+1:n,k) = -a_lu(k+1:n,k) / a_lu(k,k);\n%\n% Row elimination with column indexing.\n%\n for j = k+1 : n\n\n if ( l ~= k )\n [ a_lu(l,j), a_lu(k,j) ] = r8_swap ( a_lu(l,j), a_lu(k,j) );\n end\n\n a_lu(k+1:n,j) = a_lu(k+1:n,j) + a_lu(k+1:n,k) * a_lu(k,j);\n\n end\n\n end\n\n pivot(n) = n;\n\n if ( a_lu(n,n) == 0.0E+00 )\n info = n;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8GE_FA - Warning!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/r8ge_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7546709410375032}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\n% We can reuse ex1's computeCost() but it be messier and slower\nh0 = X*theta;\nJ = (sum((h0 - y) .^ 2) + lambda*sum(theta(2:end) .^ 2))/(2*m);\n\ngrad = (1/m)*(X'*(h0-y)) + [0; (lambda/m)*theta(2:end)];\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "SaveTheRbtz", "repo": "ml-class", "sha": "74ce689e21e9f3ca184e60313351b31112e5dd56", "save_path": "github-repos/MATLAB/SaveTheRbtz-ml-class", "path": "github-repos/MATLAB/SaveTheRbtz-ml-class/ml-class-74ce689e21e9f3ca184e60313351b31112e5dd56/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8175744828610096, "lm_q1q2_score": 0.7546532708780429}} {"text": "% S = SKEW2(MTX,MEAN,VAR)\n%\n% Sample skew (third moment divided by variance^3/2) of a matrix.\n% MEAN (optional) and VAR (optional) make the computation faster.\n\nfunction res = skew2(mtx, mn, v)\n\nif (exist('mn') ~= 1)\n mn = mean2(mtx);\nend\n\nif (exist('v') ~= 1)\n v = var2(mtx,mn);\nend\n\nif (isreal(mtx))\n res = mean(mean((mtx-mn).^3)) / (v^(3/2));\nelse\n res = mean(mean(real(mtx-mn).^3)) / (real(v)^(3/2)) + ...\n i * mean(mean(imag(mtx-mn).^3)) / (imag(v)^(3/2));\nend\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/skew2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7546532551078}} {"text": "function sincos_test ( )\n\n%*****************************************************************************80\n%\n%% SINCOS_TEST demonstrates SPINTERP on a function of a 2D argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2012\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SINCOS_TEST:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Demonstrate the use of SPINTERP to construct an\\n' );\n fprintf ( 1, ' interpolant to the function z(x,y) = sin(x) + cos(y)\\n' );\n%\n% We need to have the spinterp program in the Matlab path.\n%\n addpath ( '../spinterp' );\n%\n% To alter the default spinterp options, we must call spset().\n% We want to use a grid that uses Chebyshev spacing, and we\n% want to use at least 5 levels of interpolation.\n%\n OPTIONS = spset ( 'GridType', 'Chebyshev', ...\n 'MinDepth', 5 );\n%\n% Now we call spvals() to set up in C the data defining \n% the sparse grid interpolant. C is a Matlab structure.\n%\n m = 2;\n\n box = [ 0.0, pi; ...\n 0.0, pi ];\n\n c = spvals ( @sincos_f, m, box, OPTIONS );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here is the sparse interpolant structure:\\n' );\n fprintf ( 1, '\\n' );\n\n c\n%\n% Just for information, print out the grid points added at each level.\n%\n l_max = 4;\n for l = 0 : l_max\n fprintf ( 1, '\\n' );\n label = sprintf ( ' Grid points added at level %d', l );\n x = spgrid ( l, m, OPTIONS );\n [ n, ~ ] = size ( x );\n r8mat_print ( n, m, x, label );\n end\n\n figure ( 1 )\n l_max = 5;\n plotgrid ( l_max, m );\n grid on\n xlabel ( '<---X--->' );\n ylabel ( '<---Y--->' );\n title ( sprintf ( 'Spinterp Chebyshev Grid of level %d', l_max ) )\n\n filename = 'sincos_grid.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Grid plot stored as \"%s\".\\n', filename );\n%\n% Evaluate the interpolant at some random points in the region.\n%\n n = 25;\n x = pi * rand ( 1, n );\n y = pi * rand ( 1, n );\n z = spinterp ( c, x, y );\n\n e = max ( abs ( z - sincos_f ( x, y ) ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Maximum approximation error at %d random points is %g\\n', n, e );\n%\n% Display plots of the function and interpolant.\n%\n figure ( 2 )\n subplot ( 1, 2, 1 );\n ezmesh ( @sincos_f, [ 0.0, pi ] );\n title ( 'z(x,y) = sin(x) + cos(y)' );\n\n subplot ( 1, 2, 2 );\n ezmesh ( @(x,y) spinterp ( c, x, y ), [ 0, pi ] );\n title ( 'Sparse grid interpolant' );\n\n filename = 'sincos_interp.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Interpolant plot stored as \"%s\".\\n', filename );\n\n rmpath ( '../spinterp' )\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SINCOS_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/spinterp_examples/sincos_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7545239538342412}} {"text": "function point = intersectLinePlane(line, plane, varargin)\n%INTERSECTLINEPLANE Intersection point between a 3D line and a plane\n%\n% PT = intersectLinePlane(LINE, PLANE)\n% Returns the intersection point of the given line and the given plane.\n% LINE: [x0 y0 z0 dx dy dz]\n% PLANE: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]\n% PT: [xi yi zi]\n% If LINE and PLANE are parallel, return [NaN NaN NaN].\n% If LINE (or PLANE) is a matrix with 6 (or 9) columns and N rows, result\n% is an array of points with N rows and 3 columns.\n% \n% PT = intersectLinePlane(LINE, PLANE, TOL)\n% Specifies the tolerance factor to test if a line is parallel to a\n% plane. Default is 1e-14.\n%\n% Example\n% % define horizontal plane through origin\n% plane = [0 0 0 1 0 0 0 1 0];\n% % intersection with a vertical line\n% line = [2 3 4 0 0 1];\n% intersectLinePlane(line, plane)\n% ans = \n% 2 3 0\n% % intersection with a line \"parallel\" to plane\n% line = [2 3 4 1 2 0];\n% intersectLinePlane(line, plane)\n% ans = \n% NaN NaN NaN\n%\n% See also:\n% lines3d, planes3d, points3d, clipLine3d\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% 23/06/2006 correction from Songbai Ji allowing different number of\n% lines or plane if other input has one row\n% 14/12/2006 correction for parallel lines and plane normals\n% 05/01/2007 fixup for parallel lines and plane normals\n% 24/04/2007 rename as 'intersectLinePlane'\n% 11/19/2010 Added bsxfun functionality for improved speed (Sven Holcombe)\n% 01/02/2011 code cleanup, add option for tolerance, update doc\n\n\n% extract tolerance if needed\ntol = 1e-14;\nif nargin > 2\n tol = varargin{1};\nend\n\n% unify sizes of data\nnLines = size(line, 1);\nnPlanes = size(plane, 1);\n\n% N planes and M lines not allowed \nif nLines ~= nPlanes && min(nLines, nPlanes) > 1\n error('MatGeom:geom3d:intersectLinePlane', ...\n 'Input must have same number of rows, or one must be 1');\nend\n\n% plane normal\nn = crossProduct3d(plane(:,4:6), plane(:,7:9));\n\n% difference between origins of plane and line\ndp = bsxfun(@minus, plane(:, 1:3), line(:, 1:3));\n\n% dot product of line direction with plane normal\ndenom = sum(bsxfun(@times, n, line(:,4:6)), 2);\n\n% relative position of intersection point on line (can be inf in case of a\n% line parallel to the plane)\nt = sum(bsxfun(@times, n, dp),2) ./ denom;\n\n% compute coord of intersection point\npoint = bsxfun(@plus, line(:,1:3), bsxfun(@times, [t t t], line(:,4:6)));\n\n% set indices of line and plane which are parallel to NaN\npar = abs(denom) < tol;\npoint(par,:) = NaN;\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/intersectLinePlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7545162139662098}} {"text": "function [ l, p, u ] = r8mat_lu ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8MAT_LU computes the LU factorization of an R8MAT.\n%\n% Discussion:\n%\n% The routine is given an M by N matrix A, and produces\n%\n% L, an M by M unit lower triangular matrix,\n% U, an M by N upper triangular matrix, and\n% P, an M by M permutation matrix P,\n%\n% so that\n%\n% A = P' * L * U.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 May 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, real A(M,N), the M by N matrix to be factored.\n%\n% Output, real L(M,M), the M by M unit lower triangular factor.\n%\n% Output, real P(M,M), the M by M permutation matrix.\n%\n% Output, real U(M,N), the M by N upper triangular factor.\n%\n\n% Initialize:\n%\n% U:=A\n% L:=Identity\n% P:=Identity\n%\n u(1:m,1:n) = a(1:m,1:n);\n\n l = r8mat_identity ( m );\n\n p(1:m,1:m) = l(1:m,1:m);\n%\n% On step J, find the pivot row, IPIV, and the pivot value PIVOT.\n%\n for j = 1 : min ( m - 1, n )\n\n pivot = 0.0;\n ipiv = 0;\n\n for i = j : m\n\n if ( pivot < abs ( u(i,j) ) )\n pivot = abs ( u(i,j) );\n ipiv = i;\n end\n\n end\n%\n% Unless IPIV is zero, swap rows J and IPIV.\n%\n if ( ipiv ~= 0 )\n\n u = r8row_swap ( m, n, u, j, ipiv );\n\n l = r8row_swap ( m, m, l, j, ipiv );\n\n p = r8row_swap ( m, m, p, j, ipiv );\n%\n% Zero out the entries in column J, from row J+1 to M.\n%\n for i = j+1 : m\n\n if ( u(i,j) ~= 0.0 )\n\n l(i,j) = u(i,j) / u(j,j);\n\n u(i,j) = 0.0;\n\n u(i,j+1:n) = u(i,j+1:n) - l(i,j) * u(j,j+1:n);\n\n end\n\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.841825655188238, "lm_q1q2_score": 0.7544874040672425}} {"text": "function tensor_product_test ( )\n\n%*****************************************************************************80\n%\n%% TENSOR_PRODUCT_TEST tests TENSOR_PRODUCT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TENSOR_PRODUCT_TEST:\\n' );\n fprintf ( 1, ' Given a sequence of 1D quadrature rules, construct the\\n' );\n fprintf ( 1, ' tensor product rule.\\n' );\n%\n% 1D rule.\n%\n n1D = { [ -1.0; +1.0 ] };\n w1D = { [ 1.0; 1.0 ] };\n\n [ x, w ] = tensor_product ( n1D, w1D );\n \n x = x';\n\n [ m, n ] = size ( x );\n\n quad_rule_print ( m, n, x, w, ' A 1D rule over [-1,+1]:' );\n%\n% 2D rule.\n%\n n1D{2} = [ 2.0; 2.5; 3.0 ];\n w1D{2} = [ 0.25; 0.50; 0.25 ];\n\n [ x, w ] = tensor_product ( n1D, w1D );\n x = x';\n \n [ m, n ] = size ( x );\n\n quad_rule_print ( m, n, x, w, ' A 2D rule over [-1,+1] x [2.0,3.0]:' );\n%\n% 3D rule.\n%\n n1D{3} = [ 10.0; 15.0 ];\n w1D{3} = [ 2.50; 2.50 ];\n\n [ x, w ] = tensor_product ( n1D, w1D );\n x = x'; \n [ m, n ] = size ( x );\n\n quad_rule_print ( m, n, x, w, ' A 3D rule over [-1,+1] x [2.0,3.0] x [10.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/sparse_grid_hw/tensor_product_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7544874005106169}} {"text": "function [ w, x ] = line_o02 ( )\n\n%*****************************************************************************80\n%\n%% LINE_O02 returns a 2 point quadrature rule for the unit line.\n%\n% Discussion:\n%\n% The integration region is:\n%\n% - 1.0 <= X <= 1.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Output, real W(2), the weights.\n%\n% Output, real X(2), the abscissas.\n%\n w(1:2) = [ ...\n 0.5, ...\n 0.5 ];\n\n x(1:2) = [ ...\n -0.57735026918962576451, ...\n 0.57735026918962576451 ];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wedge_felippa_rule/line_o02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888304, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7544208159932236}} {"text": "function y = rms(f,varargin)\n%RMS RMS value of signal\n% Usage: y = rms(f);\n% y = rms(f,...);\n%\n% `RMS(f)` computes the RMS (Root Mean Square) value of a finite sampled\n% signal sampled at a uniform sampling rate. This is a vector norm\n% equal to the $l^2$ averaged by the length of the signal.\n%\n% If the input is a matrix or ND-array, the RMS is computed along the\n% first (non-singleton) dimension, and a vector of values is returned.\n%\n% The RMS value of a signal *x* of length *N* is computed by\n%\n% .. N\n% rms(f) = 1/sqrt(N) ( sum |f(n)|^2 )^(1/2)\n% n=1\n%\n% .. math:: rms(f) = \\frac{1}{\\sqrt N} \\left( \\sum_{n=1}^N |f(n)|^2\n% \\right)^{\\frac{1}{2}}\n%\n% `RMS` takes the following flags at the end of the line of input\n% parameters:\n%\n% 'ac' Consider only the AC component of the signal (i.e. the mean is\n% removed).\n%\n% 'dim',d Work along specified dimension. The default value of `[]`\n% means to work along the first non-singleton one.\n%\n\n% AUTHOR : Peter L. Søndergaard\n \n%% ------ Checking of input parameters ---------\n\nif ~isnumeric(f) \n error('%s: Input must be numerical.',upper(mfilename));\nend;\n\nif nargin<1\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\ndefinput.keyvals.dim=[];\ndefinput.flags.mean={'noac','ac'};\n[flags,kv]=ltfatarghelper({'dim'},definput,varargin);\n\n%% ------ Computation --------------------------\n\n% It is better to use 'norm' instead of explicitly summing the squares, as\n% norm (hopefully) attempts to avoid numerical overflow.\n \n[f,L,Ls,W,dim,permutedsize,order]=assert_sigreshape_pre(f,[],kv.dim, ...\n upper(mfilename));\npermutedsize(1)=1;\ny=zeros(permutedsize);\nif flags.do_ac\n\n for ii=1:W \n y(1,ii) = norm(f(:,ii)-mean(f(:,ii)))/sqrt(L);\n end;\n\nelse\n\n for ii=1:W\n y(1,ii)=norm(f(:,ii))/sqrt(L);\n end;\n\nend;\n \ny=assert_sigreshape_post(y,kv.dim,permutedsize,order);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/rms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7544208090265236}} {"text": "function [V2D] = Vandermonde2D(N,r,s)\n\n% function [V2D] = Vandermonde2D(N, r, s);\n% Purpose : Initialize the 2D Vandermonde Matrix, V_{ij} = phi_j(r_i, s_i);\n\nV2D = zeros(length(r),(N+1)*(N+2)/2);\n\n% Transfer to (a,b) coordinates\n[a, b] = rstoab(r, s);\n\n% build the Vandermonde matrix\nsk = 1;\nfor i=0:N\n for j=0:N - i\n V2D(:,sk) = Simplex2DP(a,b,i,j);\n sk = sk+1;\n end\nend\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/Vandermonde2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7543565549699767}} {"text": "function nseq = bal_seq_enum ( n )\n\n%*****************************************************************************80\n%\n%% BAL_SEQ_ENUM enumerates the balanced sequences.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the number of 0's (and 1's) in the sequence.\n% N must be nonnegative.\n%\n% Output, integer NSEQ, the number of balanced sequences.\n%\n nseq = i4_choose ( 2*n, n ) / ( 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/combo/bal_seq_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7543349884660149}} {"text": "function [ n_data, x, fx ] = bessel_j0_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BESSEL_J0_VALUES returns some values of the J0 Bessel function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% BesselJ[0,x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 21;\n\n fx_vec = [ ...\n -0.1775967713143383E+00, ...\n -0.3971498098638474E+00, ...\n -0.2600519549019334E+00, ...\n 0.2238907791412357E+00, ...\n 0.7651976865579666E+00, ...\n 0.1000000000000000E+01, ...\n 0.7651976865579666E+00, ...\n 0.2238907791412357E+00, ...\n -0.2600519549019334E+00, ...\n -0.3971498098638474E+00, ...\n -0.1775967713143383E+00, ...\n 0.1506452572509969E+00, ...\n 0.3000792705195556E+00, ...\n 0.1716508071375539E+00, ...\n -0.9033361118287613E-01, ...\n -0.2459357644513483E+00, ...\n -0.1711903004071961E+00, ...\n 0.4768931079683354E-01, ...\n 0.2069261023770678E+00, ...\n 0.1710734761104587E+00, ...\n -0.1422447282678077E-01 ];\n\n x_vec = [ ...\n -5.0E+00, ...\n -4.0E+00, ...\n -3.0E+00, ...\n -2.0E+00, ...\n -1.0E+00, ...\n 0.0E+00, ...\n 1.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 6.0E+00, ...\n 7.0E+00, ...\n 8.0E+00, ...\n 9.0E+00, ...\n 10.0E+00, ...\n 11.0E+00, ...\n 12.0E+00, ...\n 13.0E+00, ...\n 14.0E+00, ...\n 15.0E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n\n", "meta": {"author": "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_j0_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7543349766717317}} {"text": "function boundary = p06_boundary_nearest ( m, n, point )\n\n%*****************************************************************************80\n%\n%% P06_BOUNDARY_NEAREST returns a nearest boundary point in problem 06.\n%\n% Discussion:\n%\n% The given input point need not be inside the region.\n%\n% In some cases, more than one boundary point may be \"nearest\",\n% but only one will be returned.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real POINT(M,N), the coordinates of the points.\n%\n% Output, real BOUNDARY(M,N), points on the boundary\n% that are nearest to each point.\n%\n r1 = 1.0;\n r2 = 0.5;\n\n for j = 1 : n\n\n x = point(1,j);\n y = point(2,j);\n\n if ( x == 0.0 & y == 0.0 )\n\n boundary(1:2,j) = [ r2, 0.0 ]';\n%\n% Determine the angle formed by (0,0) and the point.\n%\n else\n\n t = atan4 ( y, x );\n%\n% Find the nearest point on the superellipse x^4 + y^4 = 1^4.\n%\n t1 = t - pi / 4.0;\n t2 = t + pi / 4.0;\n\n status = 0;\n dstar1 = 0.0;\n\n while ( 1 )\n\n [ t1, t2, tstar1, status ] = fmin_rc ( t1, t2, status, dstar1 );\n\n if ( status == 0 )\n break\n end\n\n cm = abs ( cos ( tstar1 ) );\n cs = r8_sign ( cos ( tstar1 ) );\n sm = abs ( sin ( tstar1 ) );\n ss = r8_sign ( sin ( tstar1 ) );\n\n dstar1 = ( x - r1 * cs * sqrt ( cm ) ).^2 ...\n + ( y - r1 * ss * sqrt ( sm ) ).^2;\n\n end\n\n boundary(1,j) = r1 * cs * sqrt ( cm );\n boundary(2,j) = r1 * ss * sqrt ( sm );\n%\n% Find the nearest point on the superellipse x^4 + y^4 = 1/2^4.\n%\n t1 = t - pi / 4.0;\n t2 = t + pi / 4.0;\n\n status = 0;\n dstar2 = 0.0;\n\n while ( 1 )\n\n [ t1, t2, tstar2, status ] = fmin_rc ( t1, t2, status, dstar2 );\n\n if ( status == 0 )\n break\n end\n\n cm = abs ( cos ( tstar2 ) );\n cs = r8_sign ( cos ( tstar2 ) );\n sm = abs ( sin ( tstar2 ) );\n ss = r8_sign ( sin ( tstar2 ) );\n\n dstar2 = ( x - r2 * cs * sqrt ( cm ) ).^2 ...\n + ( y - r2 * ss * sqrt ( sm ) ).^2;\n\n end\n%\n% Because of some MATLAB idiocy I don't have the patience to figure out,\n% involving SQRT having the wrong number of arguments(!),\n% I must replace the line\n% boundary(1:2,j) = [ r2 * cs * sqrt ( cm ), r2 * ss * sqrt ( sm ) ]';\n%\n if ( dstar2 < dstar1 )\n boundary(1,j) = r2 * cs * sqrt ( cm );\n boundary(2,j) = r2 * ss * sqrt ( sm );\n end\n\n end\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p06_boundary_nearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7543017254253325}} {"text": "function [qn,QNq] = normquat(q)\n\n% NORMQUAT Normalize quaternion to unit length\n% NORMQUAT(Q) returns a unit length quaternion Q/norm(Q)\n%\n% [qn,QNq] = NORMQUAT(Q) returns also the Jacobian wrt Q. Note that this\n% Jacobian is a symmetric 4x4 matrix.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nnq = sqrt(q(:)'*q(:));\nqn = q/nq;\n\n\nif nargout > 1\n \n a = q(1);\n b = q(2);\n c = q(3);\n d = q(4);\n\n nq3 = nq^3;\n \n QNq = [...\n [ (b^2+c^2+d^2)/nq3, -a/nq3*b, -a/nq3*c, -a/nq3*d]\n [ -a/nq3*b, (a^2+c^2+d^2)/nq3, -b/nq3*c, -b/nq3*d]\n [ -a/nq3*c, -b/nq3*c, (a^2+b^2+d^2)/nq3, -c/nq3*d]\n [ -a/nq3*d, -b/nq3*d, -c/nq3*d, (a^2+b^2+c^2)/nq3]];\nend\nreturn\n\n%%\n\nsyms a b c d real\nq = [a;b;c;d];\n[qn,QNq] = normquat(q);\n\nQNq - simple(jacobian(qn,q))\n\nQNq - QNq'\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Math/normquat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7543017187170782}} {"text": "function [ x, ierror ] = r8mat_solve2 ( n, a, b, x )\n\n%*****************************************************************************80\n%\n%% R8MAT_SOLVE2 computes the solution of an N by N linear system.\n%\n% Discussion:\n%\n% The linear system may be represented as\n%\n% A*X = B\n%\n% If the linear system is singular, but consistent, then the routine will\n% still produce a solution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of equations.\n%\n% Input, real A(N,N), the coefficient matrix to be inverted.\n%\n% Input, real B(N), the right hand side of the system.\n%\n% Output, real X(N), the solution of the linear system.\n%\n% Output, integer IERROR.\n% 0, no error detected.\n% 1, consistent singularity.\n% 2, inconsistent singularity.\n%\n ierror = 0;\n\n ipiv(1:n) = 0;\n x(1:n) = 0.0;\n%\n% Process the matrix.\n%\n for k = 1 : n\n%\n% In column K:\n% Seek the row IMAX with the properties that:\n% IMAX has not already been used as a pivot;\n% A(IMAX,K) is larger in magnitude than any other candidate.\n%\n amax = 0.0;\n imax = 0;\n for i = 1 : n\n if ( ipiv(i) == 0 )\n if ( amax < abs ( a(i,k) ) )\n imax = i;\n amax = abs ( a(i,k) );\n end\n end\n end\n%\n% If you found a pivot row IMAX, then,\n% eliminate the K-th entry in all rows that have not been used for pivoting.\n%\n if ( imax ~= 0 )\n\n ipiv(imax) = k;\n a(imax,k+1:n) = a(imax,k+1:n) / a(imax,k);\n b(imax) = b(imax) / a(imax,k);\n a(imax,k) = 1.0;\n\n for i = 1 : n\n\n if ( ipiv(i) == 0 )\n a(i,k+1:n) = a(i,k+1:n) - a(i,k) * a(imax,k+1:n);\n b(i) = b(i) - a(i,k) * b(imax);\n a(i,k) = 0.0;\n end\n\n end\n end\n end\n%\n% Now, every row with nonzero IPIV begins with a 1, and\n% all other rows are all zero. Begin solution.\n%\n for j = n : -1 : 1\n\n imax = 0;\n for k = 1 : n\n if ( ipiv(k) == j )\n imax = k;\n end\n end\n\n if ( imax == 0 )\n\n x(j) = 0.0;\n\n if ( b(j) == 0.0 )\n ierror = 1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_SOLVE2 - Warning:\\n' );\n fprintf ( 1, ' Consistent singularity, equation = %d\\n', j );\n else\n ierror = 2;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_SOLVE2 - Error:\\n' );\n fprintf ( 1, ' Inconsistent singularity, equation = %d\\n', j );\n end\n\n else\n\n x(j) = b(imax);\n\n for i = 1 : n\n if ( i ~= imax )\n b(i) = b(i) - a(i,j) * x(j);\n end\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_solve2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7543017174842648}} {"text": "function Results=weightedfit(data)\n% This code fits makes a linear fit to a data set (using y =bx+a) where each data point\n% has a different or constant standard deviation. Your data should have three or two columns.\n% The first column should be the independent variable(x) and the second\n% column should be the dependent variable(y). Column three should contain\n% your standard deviations for each datapoint. In the situations where you\n% do not specify a column three, the code assigns a weight of one to all\n% data points and this corresponds to the regular linear fits.\n%==========\n% INPUTS\n%==========\n%data = 3 columns; column 1 = x, column2 = y and column 3 = standard dev.\n\n%==========\n%OUTPUTS\n%==========\n%Result.slope= b; Fitted slope\n%Result.Intercept = a; Fitted intercept\n\n%Coded by Ebo Ewusi-Annan (University of Florida, 2011)\n%============\n%REFERENCES\n%===========\n%1. Willam H. Press, Saul A. Teukolsky and Willan T. Vetterling (1997).\n%Numerical Recipes in Fortran.\n%2. Philip R. Bevington and D. Keith Robinson (2003). Data Reduction and\n%Error Analysis for the Physical Sciences.\n \nx= data(:,1);\ny=data(:,2);\n[s t]= size(data);\nstdv=ones(s,1);\nif t==3\nstdv=data(:,3);\nend\nw = 1./stdv.^2;\nS = sum(w);\nSx = sum(w.*x);\nSy = sum(w.*y);\nSxx= sum(w.*x.^2);\nSxy= sum(w.*x.*y);\nDelta = S*Sxx - (Sx)^2;\na = (Sxx*Sy - Sx*Sxy)./Delta;\nb = (S*Sxy - Sx*Sy)./Delta;\nfprintf('\\n slope=%f Int=%f \\n',b,a)\nResults.slope=b;\nResults.Intercept= a;\ny_fit = a + b*x;\n if t==2\n h=plot(x,y,'rs','MarkerFaceColor','r');\n title('Unweighted fit')\n else\n clf;set(gcf,'color','w');\n h=errorbar(x,y,stdv,'rs','MarkerFaceColor','r');\n title('Weighted fit')\n end\nhold on; q=plot(x,y_fit,'b.--','linewidth',2);\nxlabel('x (Column 1)')\nylabel('y (Column 2)')\nlegend([h(1),q(1)],'Data',sprintf('\\nSlope=%f\\nIntercept=%f\\n',b,a),'location','Southeast') \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/34352-weighted-and-unweighted-linear-fit/weightedfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7543013364339797}} {"text": "function [D,G,B] = autoGen_acrobotDynamics(q1,q2,dq1,dq2,m1,m2,g,l1,l2)\n%AUTOGEN_ACROBOTDYNAMICS\n% [D,G,B] = AUTOGEN_ACROBOTDYNAMICS(Q1,Q2,DQ1,DQ2,M1,M2,G,L1,L2)\n\n% This function was generated by the Symbolic Math Toolbox version 6.2.\n% 12-Jun-2015 16:56:47\n\nt2 = cos(q1);\nt3 = l1.^2;\nt4 = sin(q1);\nt5 = cos(q2);\nt6 = l1.*t2;\nt7 = l2.*t5;\nt8 = t6+t7;\nt9 = sin(q2);\nt10 = l1.*t4;\nt11 = l2.*t9;\nt12 = t10+t11;\nt13 = l2.^2;\nD = reshape([-m1.*t2.^2.*t3-m1.*t3.*t4.^2-l1.*m2.*t2.*t8-l1.*m2.*t4.*t12,-l1.*l2.*m2.*t2.*t5-l1.*l2.*m2.*t4.*t9,-l2.*m2.*t5.*t8-l2.*m2.*t9.*t12,-m2.*t5.^2.*t13-m2.*t9.^2.*t13],[2, 2]);\nif nargout > 1\n t14 = dq1.^2;\n t15 = dq2.^2;\n t16 = l1.*t2.*t14;\n t17 = l2.*t5.*t15;\n t18 = t16+t17;\n t19 = l1.*t4.*t14;\n t20 = l2.*t9.*t15;\n t21 = t19+t20;\n G = [-g.*m2.*t12+m2.*t8.*t21-m2.*t12.*t18-g.*l1.*m1.*t4;-g.*l2.*m2.*t9+l2.*m2.*t5.*t21-l2.*m2.*t9.*t18];\nend\nif nargout > 2\n B = [0.0;-1.0];\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/Acrobot/autoGen_acrobotDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7543010193415196}} {"text": "%% PLANEWAVEMAXWELL1 plane wave solutions to Maxwell equations in a cube.\n%\n% Test Maxwell function can solve problems with complex solution and\n% indefinite case.\n%\n% See also planewaveMaxwell, planewaveMaxwell2\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all;\n\n%% Generate an initial mesh \n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\nbdFlag = setboundary3(node,elem,'Neumann');\n\n%% Parameters\nmaxIt = 4; \nN = zeros(maxIt,1); \nh = zeros(maxIt,1);\nenergyErr = zeros(maxIt,1);\nL2Err = zeros(maxIt,1);\nenergyErrImag = zeros(maxIt,1);\nL2ErrImag = zeros(maxIt,1);\n\n%% Get the data of the pde\nglobal d P omega\nd = [1, pi/2, pi/2]; % in sphereical coordinate\nP = [1, 0, 0];\nomega = 1;\nr = d(1); theta = d(2); phi = d(3);\nd = [r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)];\n% pde = planewavedataC; % plane wave with complex coefficients\npde = planewavedata; % plane wave with real coefficients and complex solution\n\n%% Finite Element Method \nfor k = 1:maxIt\n % refine grid \n [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n % solve the equation\n% [u,edge,A,M] = Maxwell(node,elem,HB,pde,bdFlag);\n [u,edge,eqn] = Maxwell1(node,elem,bdFlag,pde); \n % compute the error\n uI = edgeinterpolate1(pde.exactu,node,edge);\n L2Err(k) = sqrt(abs(real(u-uI)'*eqn.M*real(u-uI))); \n energyErr(k) = sqrt(abs(real(u-uI)'*eqn.A*real(u-uI)) + L2Err(k)^2);\n L2ErrImag(k) = sqrt(abs(imag(u-uI)'*eqn.M*imag(u-uI)));\n energyErrImag(k) = sqrt(abs(imag(u-uI)'*eqn.A*imag(u-uI)) + L2ErrImag(k)^2);\n% energyErr(k) = getHcurlerror3ND1(node,elem,pde.curlu,u);\n% L2Err(k) = getL2error3ND1(node,elem,pde.exactu,u);\n N(k) = length(u);\n h(k) = 1./(size(node,1)^(1/3)-1); \nend\n\n%% Plot convergence rates\nfigure(1); clf; \nshowrateh2(h,energyErr,1,'r-+','|| Re(u-u_h)||_A',...\n h,L2Err,1,'b-+','|| Re(u-u_h)||');\nfigure(2); clf; \nshowrateh2(h,energyErrImag,1,'r-+','|| Img(u-u_h)||_A',...\n h,L2ErrImag,1,'b-+','|| Img(u-u_h)||');", "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/planewaveMaxwell1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7543010154554589}} {"text": "function example4 ( )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4 demonstrates the use of PDEPE on a variable coefficient PDE system.\n%\n% Discussion:\n%\n% Solve the system of convection-diffusion equations.\n%\n% PDE: \n% ut - 2 ux - vx = uxx\n% vt - ux - 2 vx - ( 3 (ubar(x))^2 u ) = vxx\n% BC:\n% u(t,-oo) = u(t,+oo) = 0\n% v(t,-oo) = v(t,+oo) = 0\n% IC:\n% u(0,x) = exp ( - (x-5)^2 )\n% v(0,x) = exp ( - (x+5)^2 )\n%\n% Here, ubar(x) is the first component in the solution of the boundary value\n% problem:\n%\n% ubarx = - 2 ( ubar + 2 ) - vbar\n% vbarx = - ( ubar + 2 ) - 2 vbar - ( ubar^3 + 8 )\n% ubar(-oo) = -2, ubar(+oo) = 1\n% vbar(-oo) = 0, vbar(+00) = -6\n%\n% Although the mathematical problem has boundary conditions at infinity,\n% we approximate this by the interval [-25,+25].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% Original formulation by P Howard.\n% This version by John Burkardt.\n%\n% Reference:\n%\n% P Howard,\n% Partial Differential Equations in Matlab 7.0,\n% Spring 2005.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXAMPLE4:\\n' );\n fprintf ( 1, ' A convection-diffusion system:\\n' );\n fprintf ( 1, ' ut - 2 ux - vx = uxx\\n' );\n fprintf ( 1, ' vt - ux - 2 vx - ( 3 (ubar(x))^2 u ) = vxx\\n' );\n fprintf ( 1, ' u(t,-oo) = u(t,+oo) = 0\\n' );\n fprintf ( 1, ' v(t,-oo) = v(t,+oo) = 0\\n' );\n fprintf ( 1, ' u(0,x) = exp ( - (x-5)^2 )\\n' );\n fprintf ( 1, ' v(0,x) = exp ( - (x+5)^2 )\\n' );\n%\n% M defines the coordinate system:\n% 0: cartesian\n% 1: cylindrical\n% 2: spherical\n%\n m = 0;\n%\n% Define the spatial mesh.\n%\n nx = 101;\n xmesh = linspace ( -25.0, +25.0, nx );\n%\n% Define the time mesh.\n%\n nt = 21;\n tspan = linspace ( 0.0, 2.0, nt );\n%\n% Call PDEPE() for the solution.\n%\n sol = pdepe ( m, @pdefun, @icfun, @bcfun, xmesh, tspan );\n%\n% Copy out the two components of the solution.\n%\n u = sol(:,:,1);\n v = sol(:,:,2);\n\n figure ( 1 )\n subplot(2,1,1)\n surf ( xmesh, tspan, u, 'EdgeColor', 'None' );\n title ( 'Example 4: Solution U Over Time', 'Fontsize', 16 );\n xlabel ( '<--- X --->' )\n ylabel ( '<--- T --->' );\n zlabel ( '<---U(X,T)--->' );\n subplot(2,1,2)\n surf ( xmesh, tspan, v, 'EdgeColor', 'None' );\n title ( 'Example 4: Solution V Over Time', 'Fontsize', 16 );\n xlabel ( '<--- X --->' )\n ylabel ( '<--- T --->' );\n zlabel ( '<---V(X,T)--->' );\n filename = 'example4.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved solution plot in file \"%s\"\\n', filename );\n%\n% Plot the initial condition, U at time 0.\n%\n figure ( 2 )\n subplot(2,1,1)\n plot ( xmesh, u(1,:), 'LineWidth', 3 );\n grid on\n title ( 'Example 4: Initial Condition U(X,0)', 'Fontsize', 16 );\n xlabel ( '<--- X --->' )\n ylabel ( '<--- U(X,T0) --->' );\n subplot(2,1,2)\n plot ( xmesh, v(1,:), 'LineWidth', 3 );\n grid on\n title ( 'Example 4: Initial Condition V(X,0)', 'Fontsize', 16 );\n xlabel ( '<--- X --->' )\n ylabel ( '<--- V(X,T0) --->' );\n filename = 'example4_ic.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Saved initial condition plot in file \"%s\"\\n', filename );\n%\n% Plot the solution at a fixed point, with time varying.\n%\n mid = ( nx + 1 ) / 2;\n\n figure ( 3 )\n subplot(2,1,1)\n plot ( tspan, u(:,mid), 'LineWidth', 3 );\n grid on\n title ( 'Example 4: Time evolution of U(0,T)', 'Fontsize', 16 );\n xlabel ( '<--- T --->' )\n ylabel ( '<--- U(0.0,T) --->' );\n subplot(2,1,2)\n plot ( tspan, v(:,mid), 'LineWidth', 3 );\n grid on\n title ( 'Example 4: Time evolution of V(0,T)', 'Fontsize', 16 );\n xlabel ( '<--- T --->' )\n ylabel ( '<--- V(0.0,T) --->' );\n filename = 'example4_profile.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Saved time evolution plot in file \"%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 xprime = degode ( t, x )\n\n%*****************************************************************************80\n%\n%% DEGODE stores an ODE for a standing wave.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T, the current time.\n%\n% Input, real X, the spatial location.\n%\n% Output, real XPRIME(2,1), the right hand side of the differential\n% equation satisfied by ( UBAR, VBAR ).\n%\n xprime(1,1) = - 2.0 * ( x(1) + 2.0 ) - x(2);\n xprime(2,1) = - ( x(1) + 2.0 ) - 2.0 * x(2) - ( x(1)^3 + 8.0 );\n\n return\nend\nfunction ubar = pdegwave ( x )\n\n%*****************************************************************************80\n%\n%% PDEGWAVE determines the value of UBAR in the equation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Output, real UBAR, the value of UBAR at X.\n%\n small = 0.000001;\n\n if ( x < -20.0 )\n ubar = -2.0;\n vbar = 0.0;\n else\n tspan = [ -20, x ];\n x0 = [ -2.0 + small, - small ];\n [ t, x ] = ode45 ( @degode, tspan, x0 );\n ubar = x(end,1);\n vbar = x(end,2);\n end\n\n return\nend\nfunction [ c, f, s ] = pdefun ( x, t, u, dudx )\n\n%*****************************************************************************80\n%\n%% PDEFUN defines the components of the PDE.\n%\n% Discussion:\n%\n% The PDE has the form:\n%\n% c * du/dt = x^(-m) d/dx ( x^m f ) + s\n%\n% where m is 0, 1 or 2,\n% c, f and s are functions of x, t, u, and dudx, \n% and most typically, f = dudx.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Input, real T, the current time.\n%\n% Input, real U(:,1), the estimated solution at T and X.\n%\n% Input, real DUDX(:,1), the estimated spatial derivative of U at T and X.\n%\n% Output, real C(:,1), the coefficients of du/dt.\n%\n% Output, real F(:,1), the flux terms.\n%\n% Output, real S(:,1), the source terms.\n%\n c = [ 1.0; 1.0 ];\n ubar = pdegwave ( x );\n f(1) = dudx(1) + 2.0 * u(1) + u(2);\n f(2) = dudx(2) + u(1) + 2.0 * u(2) + 3.0 * ubar^2 * u(1);\n s = [ 0.0; 0.0 ];\n\n return\nend\nfunction u0 = icfun ( x )\n\n%*****************************************************************************80\n%\n%% ICFUN defines the initial conditions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Output, real U0(:,1), the value of the solution at the initial time, \n% and location X.\n%\n u0(1) = exp ( - ( x - 5.0 )^2 );\n u0(2) = exp ( - ( x + 5.0 )^2 );\n\n return\nend\nfunction [ pl, ql, pr, qr ] = bcfun ( xl, ul, xr, ur, t )\n\n%*****************************************************************************80\n%\n%% BCFUN defines the boundary conditions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real XL, the spatial coordinate of the left boundary.\n%\n% Input, real UL(:,1), the solution estimate at the left boundary.\n%\n% Input, real XR, the spatial coordinate of the right boundary.\n%\n% Input, real UR(:,1), the solution estimate at the right boundary.\n%\n% Output, real PL(:,1), the Dirichlet portion of the left boundary condition.\n%\n% Output, real QL(:,1), the coefficient of the flux portion of the left \n% boundary condition.\n%\n% Output, real PR(:,1), the Dirichlet portion of the right boundary condition.\n%\n% Output, real QR(:,1), the coefficient of the flux portion of the right \n% boundary condition.\n%\n pl = [ ul(1); ul(2) ];\n ql = [ 0.0; 0.0 ];\n pr = [ ur(1); ur(2) ];\n qr = [ 0.0; 0.0 ];\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pdepe/example4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7543009979981954}} {"text": "function [price, stdErr] = Price_MC_Lookback_func(Spath, call, M, mult, disc)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Calculates Looback option price, given the simulatd paths \n% Author: Justin Lars Kirkby\n%\n% -----------------\n% Params\n% -----------------\n% Contract Types\n% Floating Strike (Lookback) Put: max{S_m: 0<=m<=M} - S_T\n% Floating Strike (Lookback) Call: S_T - min{S_m: 0<=m<=M}\n%\n% Spath = paths of underlying, dimension N_sim x M+1, where M = number of time steps (since includes S_0)\n% call = 1 for call (else put)\n% M = number of monitoring points, e.g. 252 for \"daily\" monitoring\n% mult = time partitioning multiplier to reduce bias (e.g. mult = 2 or 5)\n% S_0 = initial price\n% disc = discount factor (e.g. exp(-r*T))\n% T = Time (in years)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nN_sim = size(Spath,1); % number of paths\n\nM_mult = M*mult; %time partitioning to reduce bias\n\n\nif call ~= 1\n curr_max = zeros(N_sim, 1);\n for n = 1:N_sim\n curr_max(n) = max(Spath(n, 1:mult:M_mult+1));\n end\nelse % find_min\n curr_min = zeros(N_sim, 1);\n for n = 1:N_sim\n curr_min(n) = min(Spath(n, 1:mult:M_mult+1));\n end\nend\n\n\nif call ==1 % Floating Strike (Lookback) Call: S_T - min{S_m: 0<=m<=M}\n payoffs = Spath(:, M_mult+1) - curr_min;\n\nelse % Floating Strike (Lookback) Put: max{S_m: 0<=m<=M} - S_T\n payoffs = curr_max - Spath(:,M_mult+1);\nend\nprice = disc*mean(payoffs);\nstdErr = disc*std(payoffs) / sqrt(N_sim);\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Monte_Carlo/Lookback/Price_MC_Lookback_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7543009940521131}} {"text": "function pde = StokesZulehnerdata\n%% STOKESDATA2 data for Stokes equations\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\npde = struct('f', @f, 'exactp', @exactp, 'exactu', @exactu,'g_D',@g_D);\n\n function z = f(p)\n x = p(:,1); y = p(:,2);\n z(:,1) = zeros(size(x));\n z(:,2) = 4*cos(x).*cos(y);\n end\n % exact velocity\n function z = exactu(p)\n x = p(:,1); y = p(:,2);\n z(:,1) = sin(x).*sin(y);\n z(:,2) = cos(x).*cos(y);\n end\n % exact pressure\n function z = exactp(p)\n x = p(:,1); y = p(:,2);\n z = 2*cos(x).*sin(y) - 2*sin(1)*(1-cos(1));\n end\n % Dirichlet boundary condition of velocity\n function z = g_D(p)\n z = exactu(p);\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/data/StokesZulehnerdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7542775207472443}} {"text": "function [trend,cyclic] = beveridgenelson(y,parameters,constant,p,q)\n% Beveridge-Nelson decomposition for a trending time series.\n%\n% USAGE:\n% [TREND,CYCLIC] = beveridgenelson(y,parameters,constant,p,q)\n%\n% INPUTS:\n% Y - T by 1 column of trending data data\n% PARAMETERS - 1 by CONSTANT + length(P) + length(Q) vector of parameters estimated on diff(Y)\n% CONSTANT - Scalar variable: 1 the the fit model included a constant\n% P - Non-negative integer vector representing the AR orders of the fit model\n% Q - Non-negative integer vector representing the MA orders of the fit model\n%\n% OUTPUTS:\n% TREND - T by 1 vector of containing the trend. First max(P)+1 observations are the same as Y\n% CYCLIC - T by 1 vector of containing the cyclic component. First max(P)+1 observations are\n% the same as Y\n%\n% COMMENTS:\n% Uses the exact BN decomposition as presented in\n%\n% Paul Newbold, \"Precise and efficient computation of the Beveridge-Nelson decomposition of\n% economic time series\", Journal of Monetary Economics, Volume 26, Issue 3, December 1990, Pages\n% 453-457.\n%\n% This decomposition is based on a demeaned ARMA model for the short-run dynamics. If CONSTANT = 1,\n% this function will demeand the data using the model implied long-run mean (the constant\n% parameter divided by the sum of the AR coefficients).\n%\n% EXAMPLES:\n% BN decomposition for Real US GDP using an AR(1) for the SR component\n% load GDP\n% parameters = armaxfilter(diff(lnGDP),1,1);\n% [trend,cyclic] = beveridgenelson(lnGDP,parameters,1,1);\n% BN decomposition for Real US GDP using an ARMA(1,4) for the SR component\n% parameters = armaxfilter(diff(lnGDP),1,1,1:4);\n% [trend,cyclic] = beveridgenelson(lnGDP,parameters,1,1,1:4);\n%\n% See also ARMAXFILTER\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 11/1/2009\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n case 3\n p=[];\n q=[];\n case 4\n q=[];\n case 5\n % Nothing\n otherwise\n error('3 to 5 inputs required.');\nend\nif size(y,2)>size(y,1)\n y=y';\nend\nif size(y,2)~=1\n error('Y must be a T by 1 vector.');\nend\nif ~ismember(constant,[0 1])\n error('CONSTANT must be 0 or 1.')\nend\nnp = length(p);\nnq = length(q);\nif np>0\n maxp = max(p);\nelse\n maxp = 0;\nend\nif nq>0\n maxq = max(q);\nelse\n maxq = 0;\nend\nif length(parameters)~=(constant+np+nq)\n error('PARAMETERS must have CONSTANT + length(P) + length(Q) parameters.');\nend\n% Remove the constant, if any\nif constant\n constant = parameters(1);\n parameters = parameters(2:length(parameters));\n if np>0\n longRunMean = constant/(1-sum(parameters(1:np)));\n else\n longRunMean = constant;\n end\nend\ndeltaY = diff(y) - longRunMean;\nif maxp>0\n A = zeros(maxp);\n A(1,p) = parameters(1:np);\n for i=2:maxp\n A(i,i-1) = 1;\n end\n Aeigs = abs(eig(A));\n if max(Aeigs)>=1\n error('The model for the short-run dynamics is not stationary. Stationarity is required for the BN decomposition to be well defined.');\n end\nelse\n A = 0;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\nT = size(deltaY,1);\n% Construct the errors\nm = max(maxp,maxq);\nzerosToPad = max(maxq-maxp,0);\ndeltaYAugmentedForMA = [zeros(zerosToPad,1);deltaY];\nerrors = armaxerrors(parameters,p,q,0,deltaYAugmentedForMA,[],m,ones(size(deltaYAugmentedForMA)));\nerrors = errors(zerosToPad+1:length(errors));\n\n% Initialize the trend and cyclic component\ntrend = zeros(T+1,1);\ntrend(1:maxp+1) = y(1:maxp+1);\ncyclic = zeros(T+1,1);\ndeltaYForecast = zeros(T+m,1);\nerrorsForecast = zeros(1,T+m);\n% Initialize the coefficient needed\ne = [1 zeros(1,maxp-1)];\nlongRunScale = (eye(maxp) - A)^(-1)*A;\nlongRunScale = e*longRunScale;\nfor t = maxp + 1 : T\n % Construct maxq forecasts, then use companion matrix to compute sum\n deltaYForecast(:) = 0;\n errorsForecast(:) = 0;\n deltaYForecast(1:t) = deltaY(1:t);\n errorsForecast(1:t) = errors(1:t);\n for h = 1 : maxq\n for j=1:np\n deltaYForecast(t+h) = deltaYForecast(t+h) + parameters(j) * deltaYForecast(t+h-p(j));\n end\n for j=1:nq\n if (t+h-q(j))>0\n deltaYForecast(t+h) = deltaYForecast(t+h) + parameters(np+j) * errorsForecast(t+h-q(j));\n end\n end\n end\n % Select the correct forecasts\n cumForecast = sum(deltaYForecast(t+1:t+maxq));\n if np>0\n deltaYHat=deltaYForecast(t+maxq-maxp+1:t+maxq);\n cumForecast = cumForecast + longRunScale*deltaYHat;\n end\n trend(t+1) = y(t+1) + cumForecast;\n cyclic(t+1) = -cumForecast;\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/beveridgenelson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7542775190664718}} {"text": "% MULTIPLICITY --> Computing the multiplicity and multiplicity structure\n% of a system of nonlinear equations at an isolated zero.\n%\n% \n% m = Multiplicity(f, variables, zero)\n% m = Multiplicity(f, variables, zero, options)\n% [m, D, H] = Multiplicity(f, variables, zero)\n% [m, D, H] = Multiplicity(f, variables, zero, options)\n%\n% \n% 1. f --> a cell array containing the system of nonlinear\n% equations as strings, e.g.,\n% >> f = { 'x^2 + sin(y) -1', 'x-cos(y)' };\n%\n% 2. variables --> a cell array containing the unknown variables as\n% strings, e.g.,\n% >> variables = { 'x', 'y' };\n%\n% 3. zero --> a vector containing numerical zero (root) of f, e.g.,\n% >> zero = [1, 0];\n%\n% 4. options --> an optional parameter which includes the configuration\n% settings:\n% Display: Set to 2 to have all output (the dual space\n% and Hilbert function) printed to the screen,\n% and set to 1 to have depth and Hilbert\n% function printed to the screen. Otherwise\n% set the default value 0;\n% Tol: The threshold for numerical rank-revealing.\n% Singular values above Tol are counted as\n% nonzero. The default value is 1e-8;\n% EqnType: The equation type for MULTIPLICITY,\n% polynomial system ('Poly') or nonlinear\n% functions ('Nonlinear'). The default value is\n% 'Nonlinear'. By setting the value to 'Poly',\n% MULTIPLICITY will transfer the polynomial\n% system to the matrix representation\n% internally and speed up the computation.\n% MaxInt: Maximum multiplicity allowed in the recursive\n% computation. If a zero is not isolated, the\n% multiplicity will be infinity. The code can\n% be used for identifying a nonisolated zero by\n% setting MaxInt to a known upper bound (e.g.\n% the Bezout number). The default value is 1000.\n%\n% All the configuration settings may be changed by using\n% optset function, i.e.,\n% >> options = optset('para', value);\n% para could be any configuration setting, value is set\n% to para. See OPTSET for details. Any configuration\n% setting that is not changed will be set to its default\n% value.\n%\n% \n% 1. m --> the multiplicity of f at the zero;\n%\n% 2. D --> a basis for the dual space as a cell array with\n% each component being a matrix in the Matlab form of\n% D{i} = [c_1, j_1;\n% c_2, j_2;\n% ...\n% c_n, j_n ];\n% representing a differential functional\n% D_i = c_1*d_{j_1} + ... + c_n*d_{j_n}\n% where d_{j_i}'s are differential monomial functionals\n% (e.g. For a system of equations with variables {x,y,z}\n% at the zero x=a, y=b, z=c, the functional d_{[i,j,k]}\n% applied to any function g is the value of the partial\n% derivative\n%\n% i+j+k\n% 1 d\n% d_{[i,j,k]}(g) = -------- * ----------- g(a,b,c)\n% i! j! k! i j k\n% dx dy dz\n%\n% The dual space is the vector space consists of such\n% differential functionals that vanish on the nonlinear\n% system while satisfying the so-called closedness\n% condition);\n%\n% 3. H --> values of the Hilbert function in a vector.\n%\n% \n% Consider the nonlinear system\n%\n% sin(x)*cos(y)-x = 0\n% sin(y)*sin(x)^2 - y^2 = 0\n%\n% at the zero (x, y) = (0, 0), the multiplicity can be computed by the\n% following statements:\n%\n% >> f = {'sin(x)*cos(y) - x', 'sin(y)*sin(x)^2 - y^2'};\n% >> variables = {'x', 'y'};\n% >> zero = [0, 0];\n% >> m = Multiplicity(f, variables, zero)\n%\n% To create an options structure with Tol = 1e-10, MaxInt = 100:\n% >> options = optset('Tol', 1e-10, 'MaxInt', 100);\n% >> m = Multiplicity(f, variables, zero, options)\n%\n% \n% This code implements a modified closedness subspace method for\n% multiplicity identification with a newly developed equation-by-equation\n% strategy for improving efficiency.\n%\n% \n% [1] An algorithm and software for computing multiplicity structures at\n% zeros of nonlinear systems, W. Hao, A. J. Sommesse and Z. Zeng\n% [2] The closedness subspace method for computing the multiplicity\n% structure of a polynomial system, Z. Zeng.\n%\n% See also optset, cell\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/Multiplicity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7542775186705294}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Author: Eugenio Alcala Baselga\n% Date: 02/06/2018\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ Ac, Bc ] = KinemError_Dyn_LPV_Model (omega_SV,vel_SV,theta_E_SV,delta_SV,alpha_SV) %#codegen\n \n\n % Vamos a empezar usando delta, pero es posible que haya que hhacer un\n % cambio de variable a sigma como se hizo anteriormente.\n\n % Vehicle parameters\n M = 683;\n I = 561;\n a = 0.758;\n b = 1.036;\n g = 9.81; \n ro = 1.2;\n Cf = 15000;\n Cd = 0.5;\n Area = 4;\n mu_roz = 0.1;\n \n epsilon = 10^-8;\n \n %% Model LPV parameters:\n\n F_drag = 0.5*ro*Cd*Area*vel_SV*vel_SV;\n F_rozamiento = mu_roz*M*g;\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Note:\n% This the model used in the MPC-LPV. It has more trigonometric\n% commbinations than the used in the IET paper. It is below.\n\n A1 = -(F_drag+F_rozamiento) / (M*(vel_SV+epsilon));\n\n A2 = Cf*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)-sin(alpha_SV)) / M;\n\n A3 = Cf*(a*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)) - b*sin(alpha_SV)) / (M*(vel_SV+epsilon)); \n\n B1 = Cf*(sin(delta_SV)*cos(alpha_SV)-sin(alpha_SV)*cos(delta_SV)) / M; \n\n B2 = cos(alpha_SV) / M;\n \n\n A4 = -Cf*(cos(alpha_SV)*cos(delta_SV)+sin(alpha_SV)*sin(delta_SV)+cos(alpha_SV)) / (M*(vel_SV+epsilon));\n\n A5 = ( (-Cf*a*(cos(delta_SV)*cos(alpha_SV)+sin(alpha_SV)*sin(delta_SV)) + Cf*b*cos(alpha_SV)) / (M*(vel_SV*vel_SV)) ) - 1; \n \n B3 = Cf*(cos(alpha_SV)*cos(delta_SV)+sin(alpha_SV)*sin(delta_SV)) / (M*(vel_SV+epsilon)); \n \n B4 = -sin(alpha_SV) / (M*(vel_SV+epsilon)); \n \n\n A6 = Cf*(b-a*cos(delta_SV)) / I;\n\n A7 = -Cf*(a*a*cos(delta_SV) + b*b) / (I*(vel_SV+epsilon)); \n\n B5 = (Cf*a*cos(delta_SV)) / I;\n\n% A9 = (v_d * sin(theta_E_SV)) / (theta_E_SV+epsilon);\n A9 = (vel_SV * sin(theta_E_SV)) / (theta_E_SV+epsilon); % This should be the reference\n% A10 = (vel_SV * cos(theta_E_SV)) / (theta_E_SV); % This should be the reference\n% A10 = vel_SV / (theta_E_SV+epsilon);\n% A11 = omega_SV; % This should be the reference\n \n Ac = [ 0 omega_SV 0 -1 0 0;\n -omega_SV 0 A9 0 0 0;\n 0 0 0 0 0 -1;\n 0 0 0 A1 A2 A3;\n 0 0 0 0 A4 A5;\n 0 0 0 0 A6 A7];\n\n Bc = [ 0 0;\n 0 0;\n 0 0;\n B2 B1;\n B4 B3;\n 0 B5];\n \n Bref = [ 1 0;\n 0 0;\n 0 1;\n 0 0;\n 0 0;\n 0 0 ];\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Note:\n% This is the model used as dynamic LPV model in the IET paper.\n% It is a little bit more simplifyied than the used in the MPC-LPV\n% approach.\n% % % % % Cf = 433;\n% % % % % Cr = 367;\n% Cf = 15000;\n% Cr = 15000;\n\n% A1 = -(F_drag+F_rozamiento)/(M*vel_SV);\n% A2 = Cf*sin(delta_SV)/M;\n% A3 = Cf*sin(delta_SV)*a/(M*vel_SV);\n% A4 = -(Cf*cos(delta_SV)+Cr)/(M*vel_SV); %%% Might be a a mistake\n% A5 = -(Cf*a*cos(delta_SV)-Cr*b)/(M*vel_SV*vel_SV) - 1;\n% A6 = (Cr*b-Cf*a*cos(delta_SV))/I;\n% A7 = (-Cf*a*a*cos(delta_SV) + Cr*b*b)/(I*vel_SV);\n% \n% B2 = 1/M;\n% B1 = Cf*sin(delta_SV)/M;\n% B3 = Cf*cos(delta_SV)/(M*vel_SV);\n% B4 = 0;\n% B5 = Cf*a*cos(delta_SV)/I;\n% \n% A9 = (v_d * sin(theta_E_SV))/(theta_E_SV+epsilon); \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\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/KinemError_Dyn_LPV_Model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7542001291704828}} {"text": "function pde = fracLapdata1\n%% FRACLAPDATA1 data for fractional Laplacian problem\n%\n% s a parameter in (0,1)\n% k is given integer\n% u = 2^(1-s)/gamma(s)*(k*pi*y)^s*besselk(s,k*pi*y).*sin(k*pi*x);\n% u|_(y==0) = sin(k*pi*x);\n% g_N = ds*(k*pi)^(2*s)*sin(k*pi*x);\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\npde = struct('f',0,'exactu',@exactu,'g_D',0,'g_N',@g_N,'d',@d,'Du',@Du);\n\n % exact solution\n function u = exactu(p)\n global s\n u = zeros(size(p,1),1);\n k = 3;\n x = p(:,1); y = p(:,2);\n idx = (y>eps);\n sqrtlambda = k*pi;\n z = sqrtlambda*y(idx);\n C = 2^(1-s)/gamma(s);\n u(idx) = C*z.^s.*besselk(s,z).*sin(sqrtlambda*x(idx));\n u(~idx) = sin(sqrtlambda*x(~idx)); % at y = 0. %% NOS 2013 p.31\n end\n function K = d(p) % Diffusion constant\n global s\n alpha = 1-2*s;\n %x = p(:,1); \n y = p(:,2);\n K = y.^alpha;\n end\n function z = g_N(p)\n global s\n k = 3;\n x = p(:,1); %y = p(:,2);\n ds = 2^(1-2*s)*gamma(1-s)/gamma(s); % (2.23) in NOS 2013\n sqrtlambda = k*pi;\n z = ds*sqrtlambda^(2*s)*sin(sqrtlambda*x);\n end\n function uprime = Du(p)\n global s\n k = 3;\n x = p(:,1); y = p(:,2);\n sqrtlambda = k*pi;\n z = sqrtlambda*y;\n uprime(:,1) = 2^(1-s)/gamma(s)*sqrtlambda*z.^s.*besselk(s,z).*cos(sqrtlambda*x);\n uprime(:,2) = -2^(1-s)/gamma(s)*sqrtlambda*z.^s.*besselk(1-s,z).*sin(sqrtlambda*x);\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/data/fracLapdata1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7541962778294895}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Dh=hammingDist(B1, B2)\n%\n% Written by Rob Fergus\n% Compute hamming distance between two sets of samples (B1, B2)\n%\n% Dh=hammingDist(B1, B2);\n%\n% Input\n% B1, B2: compact bit vectors. Each datapoint is one row.\n% size(B1) = [ndatapoints1, nwords]\n% size(B2) = [ndatapoints2, nwords]\n% It is faster if ndatapoints1 < ndatapoints2\n% \n% Output\n% Dh = hamming distance. \n% size(Dh) = [ndatapoints1, ndatapoints2]\n%\n% example query\n% Dhamm = hammingDist(B2, B1);\n% this will give the same result than:\n% Dhamm = distMat(U2>0, U1>0).^2;\n% the size of the distance matrix is:\n% size(Dhamm) = [Ntest x Ntraining]\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% loop-up table:\nbit_in_char = uint16([...\n 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 2 3 ...\n 3 4 2 3 3 4 3 4 4 5 1 2 2 3 2 3 3 4 2 3 3 4 ...\n 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 1 2 ...\n 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 ...\n 3 4 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 ...\n 5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 1 2 2 3 ...\n 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 ...\n 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 ...\n 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 2 3 3 4 3 4 ...\n 4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 ...\n 5 6 6 7 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 4 5 ...\n 5 6 5 6 6 7 5 6 6 7 6 7 7 8]);\n\nn1 = size(B1,1);\n[n2, nwords] = size(B2);\n\nDh = zeros([n1 n2], 'uint16');\nfor j = 1:n1\n for n=1:nwords\n y = bitxor(B1(j,n),B2(:,n));\n Dh(j,:) = Dh(j,:) + bit_in_char(y+1);\n end\nend\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/hammingDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7541962736933316}} {"text": "% TP model transformation based controller design for the parallel-type double inverted pendulum\n% Szabolcs Nagy, Zoltan Petres, Peter Baranyi\n% FUZZ-IEEE 2008 p1374-1380\n\nm_k = 1.0; % kg\nm_1 = 0.3; % kg\nm_2 = 0.1; % kg\ng = 9.8; % m/s^2\nl_1 = 0.6; % m\nl_2 = 0.2; % m\n\nF = @(p)(1-3/4*cos(p(1))^2)*m_1;\nG = @(p)(1-3/4*cos(p(2))^2)*m_2;\nH = @(p)4/3*(m_k+F(p)+G(p));\n\n% state vector: pos, a, b, dpos, da, db\n% parameter vector: a, b, da, db\nLPV = {...\n @(p)0 @(p)0 @(p)0 @(p)1 @(p)0 @(p)0 @(p)0;\n @(p)0 @(p)0 @(p)0 @(p)0 @(p)1 @(p)0 @(p)0;\n @(p)0 @(p)0 @(p)0 @(p)0 @(p)0 @(p)1 @(p)0;\n @(p)0 @(p)-m_1*g*sinc(p(1)/pi)*cos(p(1))/H(p) @(p)-m_2*g*sinc(p(2)/pi)*cos(p(2))/H(p) @(p)0 @(p)4/3*m_1*l_1*p(3)*sin(p(1))/H(p) @(p)4/3*m_2*l_2*p(4)*sin(p(2))/H(p) @(p)4/3/H(p);\n @(p)0 @(p)(m_k+m_1+G(p))*g*sinc(p(1)/pi)/l_1/H(p) @(p)3/4*m_2*g*sinc(p(2)/pi)*cos(p(2))*cos(p(1))/l_1/H(p) @(p)0 @(p)-m_1*p(3)*sin(p(1))*cos(p(1))/H(p) @(p)-m_2*l_2*p(4)*sin(p(2))*cos(p(1))/l_1/H(p) @(p)-cos(p(1))/l_1/H(p);\n @(p)0 @(p)3/4*m_1*g*sinc(p(1)/pi)*cos(p(1))*cos(p(2))/l_2/H(p) @(p)(m_k+m_2+F(p))*g*sinc(p(2)/pi)/l_2/H(p) @(p)0 @(p)-m_1*l_1*p(3)*sin(p(1))*cos(p(2))/l_2/H(p) @(p)-m_2*p(4)*sin(p(2))*cos(p(2))/H(p) @(p)-cos(p(2))/l_2/H(p);\n};\n\n%Parameter relation tensor\ndep = zeros([size(LPV) 4]);\ndep(4,2,:) = [1 1 0 0];\ndep(4,3,:) = [1 1 0 0];\ndep(4,5,:) = [1 1 1 0];\ndep(4,6,:) = [1 1 0 1];\ndep(4,7,:) = [1 1 0 0];\ndep(5,2,:) = [1 1 0 0];\ndep(5,3,:) = [1 1 0 0];\ndep(5,5,:) = [1 1 1 0];\ndep(5,6,:) = [1 1 0 1];\ndep(5,7,:) = [1 1 0 0];\ndep(6,2,:) = [1 1 0 0];\ndep(6,3,:) = [1 1 0 0];\ndep(6,5,:) = [1 1 1 0];\ndep(6,6,:) = [1 1 0 1];\ndep(6,7,:) = [1 1 0 0];\n\nn = 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/25514-tp-tool/tptool/example/pend2/pend2_lpv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661015270469, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7541391333020208}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n%Relationship between FS coefficients \n\n%b(k)=a(k)+a(-k)\n%c(k)=j[a(k)-a(-k)]\nsyms t ; \nx=exp(-t);\nt0=0; \nT=5; \nw=2*pi/T; \nk=-6:6; \nn=1:6 ; \nb=(2/T)*int(x*cos(n*w*t),t,t0,t0+T);\nb=eval(b)\nc=(2/T)*int(x*sin(n*w*t),t,t0,t0+T);\nc=eval(c)\na=(1/T)*int(x*exp(-j*k*w*t), t,t0,t0+T);\na=eval(a);\nfor i=1:6\nbb(7-i)=a(14-i)+a(i);\ncc(7-i)=j*(a(14-i)-a(i));\nend\nbb\ncc \n\n\n\n% a(k)=0.5[b(k)-jc(k)]\nan=(1/2)*(b-j*c)\nak(1:6)=a(8: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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/5/c513.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7541167963023654}} {"text": "function [t,r] = db_index(D, cl, C, p, q)\n \n% DB_INDEX Davies-Bouldin clustering evaluation index.\n%\n% [t,r] = db_index(D, cl, C, p, q)\n%\n% Input and output arguments ([]'s are optional): \n% D (matrix) data (n x dim)\n% (struct) map or data struct\n% cl (vector) cluster numbers corresponding to data samples (n x 1)\n% [C] (matrix) prototype vectors (c x dim) (default = cluster means)\n% [p] (scalar) norm used in the computation (default == 2)\n% [q] (scalar) moment used to calculate cluster dispersions (default = 2)\n% \n% t (scalar) Davies-Bouldin index for the clustering (=mean(r))\n% r (vector) maximum DB index for each cluster (size c x 1) \n% \n% See also KMEANS, KMEANS_CLUSTERS, SOM_GAPINDEX.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% input arguments\n\nif isstruct(D), \n switch D.type,\n case 'som_map', D = D.codebook; \n case 'som_data', D = D.data; \n end\nend\n\n% cluster centroids\n[~, dim] = size(D);\nu = unique(cl); \nc = length(u); \nif nargin <3, \n C = zeros(c,dim); \n for i=1:c, \n me = nanstats(D(cl==u(i),:));\n C(i,:) = me';\n end \nend\n\nu2i = zeros(max(u),1); u2i(u) = 1:c; \nD = som_fillnans(D,C,u2i(cl)); % replace NaN's with cluster centroid values\n\nif nargin <4, p = 2; end % euclidian distance between cluster centers\nif nargin <5, q = 2; end % dispersion = standard deviation\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% action\n\n% dispersion in each cluster\nS = zeros(1, c);\nfor i = 1:c\n ind = find(cl==u(i)); % points in this cluster\n l = length(ind);\n if l > 0\n S(i) = (mean(sqrt(sum((D(ind,:) - ones(l,1) * C(i,:)).^2,2)).^q))^(1/q);\n else\n S(i) = NaN;\n end\nend\n \n% distances between clusters\n%for i = 1:c\n% for j = i+1:c\n% M(i,j) = sum(abs(C(i,:) - C(j,:)).^p)^(1/p);\n% end\n%end\nM = som_mdist(C,p); \n\n% Davies-Bouldin index\nR = NaN * zeros(c);\nr = NaN * zeros(c,1);\nfor i = 1:c\n for j = i+1:c\n R(i,j) = (S(i) + S(j))/M(i,j);\n end\n r(i) = max(R(i,:));\nend\n \nt = mean(r(isfinite(r)));\n \nreturn; \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/db_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7541062510843763}} {"text": "function [ uout, vout ] = triasimp ( x, y )\n\n%*****************************************************************************80\n%\n%% TRIASIMP maps a point from the reference triangle to the simplex.\n%\n% Discussion:\n%\n% Map the reference triangle with vertices\n% (-1,-1/sqrt(3)), (1,-1/sqrt(3)), (0,2/sqrt(3))\n% to the simplex with vertices\n% (0,0), (1,0), (0,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 26 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, real X, Y, the coordinates of a point in the\n% reference triangle.\n%\n% Output, real UOUT, VOUT, the coordinates of the corresponding\n% point in the simplex.\n%\n scale = 1.0 / sqrt ( 3.0 );\n\n uout = 0.5 * ( x + 1.0 ) - 0.5 * scale * ( y + scale );\n\n vout = 1.0 * scale * ( y + scale );\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_symq_rule/triasimp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7541062448351483}} {"text": "function [ o, x, w ] = en_r2_05_2 ( n )\n\n%*****************************************************************************80\n%\n%% EN_R2_05_2 implements the Stroud rule 5.2 for region EN_R2.\n%\n% Discussion:\n%\n% The rule has order O = 2 * N^2 + 1.\n%\n% The rule has precision P = 5.\n%\n% EN_R2 is the entire N-dimensional space with weight function\n%\n% w(x) = exp ( - x1^2 - x2^2 ... - xn^2 ) \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n o = 2 * n * n + 1;\n volume = sqrt ( pi^n );\n\n a = 2 * volume / ( n + 2 );\n b = ( 4 - n ) * volume / 2 / ( n + 2 )^2;\n c = volume / ( n + 2 )^2;\n\n r = sqrt ( ( n + 2 ) / 2 );\n s = sqrt ( ( n + 2 ) / 4 );\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;\n w(k) = a;\n%\n% 2 * N points.\n%\n for i = 1 : n\n k = k + 1;\n x(i,k) = - r;\n w(k) = b;\n k = k + 1;\n x(i,k) = + r;\n w(k) = b;\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) = - s;\n x(j,k) = - s;\n w(k) = c;\n k = k + 1;\n x(i,k) = - s;\n x(j,k) = + s;\n w(k) = c;\n k = k + 1;\n x(i,k) = + s;\n x(j,k) = - s;\n w(k) = c;\n k = k + 1;\n x(i,k) = + s;\n x(j,k) = + s;\n w(k) = c;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/en_r2_05_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7541040676390711}} {"text": "% % Search the elements that are lying within a specified interval.\n% % Search the indexes of all elements in x (sorted vector of n elements) that \n% % lie within the interval.\n% % The algorithm uses binary searches, thus it runs in log(n)\n% %\n% % INPUT:\n% % x: vector of numeric values sorted in ascending order\n% % (e.g. 2,7,20,...120)\n% % ref: numeric value of the reference point (center of the interval)\n% % tol: numeric value corresponding to 1/2 of the width of the interval\n% % The fourth input argument: numeric value (optional). Allows to define the maximum \n% % number of elements of x that can lie within the specified interval. This is useful\n% % in order to speed up the search.\n% %\n% % OUTPUT:\n% % indexes: indexes of elements of x which lie within the interval \n% % [ref-tol ref+tol]\n% % If ref is not found in x then indexes is empty.\n% %\n% % Revisions:\n% % 14-jun-2010: - Added lines 38-55 in order to consider the case in which lower bound \n% % is less than the minimum value of x or the upper bound is more than \n% % the max value of x \n% % - Reinforced the conditions in line 93 and in line 117 in order to avoid \n% % an error when (to-1)==0 or (from+1)>length(x)\n% % 15/apr/2011: - A bug with uint values of input array has been fixed. \n% % Thanks to Igor Varfolomeev\n\n% % % --------------------------------\n% % % Author: Dr. Roberto Olmi\n% % % Email : robertoolmi at gmail.com\n% % % --------------------------------\n\nfunction indexes = BinaryIntervalSearch(x,ref,tol,varargin)\nlbound = ref-tol;\nubound = ref+tol;\nfrom=1;\nto=length(x);\n\nif lbound <= x(1)\n if ubound < x(1)\n indexes=[];\n return\n end\n lindex=1;\nelse\n lindex=0;\nend\nif ubound >= x(end)\n if lbound > x(end)\n indexes=[];\n return\n end\n uindex=length(x);\nelse\n uindex=0;\nend\n\ngo=uindex==0 || lindex==0;\nwhile go\n mid = ceil(from+(to-from)/2);\n %diff = x(mid)-ref; 15/apr/2011\n if x(mid) < ref %diff < 0 15/apr/2011\n if x(mid) >= lbound\n go=false;\n else\n from=mid+1;\n if x(from) >= lbound\n lindex=from;\n go=false;\n end\n end\n else % x(mid) > ref\n if x(mid) <= ubound\n go=false;\n else\n to=mid-1;\n if x(to) <= ubound\n uindex=to;\n go=false;\n end\n end\n end\nend\n\n%remove this if at least one element of x is always in the interval:\nif (lindex > 0 && x(lindex) > ubound)...\n || (uindex > 0 && x(uindex) < lbound)\n indexes=[];\n return\nend\n\n%search upper index\ncfrom=from;\nif from==length(x) || x(from+1) > ubound\n uindex=from;\nend\nif nargin == 4\n to=min([to mid+varargin{1}]);\nend\nwhile uindex == 0\n mid = ceil(from+(to-from)/2);\n if x(mid) <= ubound\n from=mid+1;\n if x(from) > ubound \n uindex=mid;\n end\n else \n to=mid-1;\n if x(to) < ubound\n uindex=to;\n end\n end\nend\n\n%search lower index\nfrom=cfrom;\nto=uindex; \nif to==1 || x(to-1) < lbound\n lindex=to;\nend\nif nargin == 4\n from=max([from uindex-varargin{1}]); \nend\nwhile lindex == 0\n mid = ceil(from+(to-from)/2);\n if x(mid) < lbound\n from=mid+1;\n if x(from) > lbound\n lindex=from;\n end\n else \n to=mid-1;\n if x(to) < lbound\n lindex=mid;\n end\n end\nend\n\nindexes=lindex:uindex;\n\n% % --------------------------------------------\n% % Example code for Testing\n% % tol=2;\n% % ref=12;\n% % maxi=10000;\n% % numel=1000;\n% % for i=1:maxi\n% % x = sort(randint(1,numel,[0,400]));\n% % indexes = BinaryIntervalSearch(x,ref,tol);\n% % if isempty (indexes)\n% % if any(abs(x-ref) < tol)\n% % disp('Doh!')\n% % break\n% % else\n% % continue\n% % end\n% % end\n% % if indexes(1)>1 && ~(x(indexes(1)-1) < x(indexes(1)))...\n% % || indexes(end) tol)\n% % disp('Doh!')\n% % break\n% % end\n% % if i==maxi\n% % disp('OK!!!')\n% % end\n% % end\n% % --------------------------------------------\n\n% % % --------------------------------\n% % % Author: Dr. Roberto Olmi\n% % % Email : robertoolmi at gmail.com\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/26680-binary-search-of-elements-lying-within-an-interval/BinaryIntervalSearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.754098326500629}} {"text": "function output = minmod(a,b)\n% minmod is the minmod function in (2.9b) in the paper\n% m(a,b) = minmod(a,b) = (\\frac{sgn(a)+sgn(b)}{2}) min(|a|,|b|)\n\noutput = (sign(a) + sign(b)) / 2 * min(abs(a), abs(b));", "meta": {"author": "YimianDai", "repo": "Image-Processing-Codes-for-Easier-Understanding", "sha": "874302799e48852624bc3760b58b46bd9360f238", "save_path": "github-repos/MATLAB/YimianDai-Image-Processing-Codes-for-Easier-Understanding", "path": "github-repos/MATLAB/YimianDai-Image-Processing-Codes-for-Easier-Understanding/Image-Processing-Codes-for-Easier-Understanding-874302799e48852624bc3760b58b46bd9360f238/src/(Physica D 1992) Nonlinear Total Variation based noise removal algorithms/version_1/support/minmod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7539749657416849}} {"text": "function [node,face,elem]=meshunitsphere(tsize,maxvol)\n%\n% [node,face,elem]=meshunitsphere(tsize,maxvol)\n%\n% create the surface and/or volumetric mesh of a unit sphere \n% centered at [0 0 0] and radius 1\n%\n% author: Qianqian Fang, \n%\n% input: \n% tsize: maximum size of the surface triangles (from 0 to 1)\n% maxvol: maximum volume of the tetrahedron; if one wants to return\n% elem without specifying maxvol, maxvol=tsize^3\n%\n% output:\n% node: node coordinates, 3 columns for x, y and z respectively\n% face: integer array with dimensions of NB x 3, each row represents\n% a surface mesh face element \n% elem: integer array with dimensions of NE x 4, each row represents\n% a tetrahedron. If ignored, this function only produces the surface\n%\n% example:\n% [node,face]=meshunitsphere(0.05);\n% [node,face,elem]=meshunitsphere(0.05,0.01);\n% plotmesh(node,elem,'x>0'); axis equal;\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n% \n\ndim=60;\nesize=tsize*dim;\nthresh=dim/2-1;\n[xi,yi,zi]=meshgrid(0:0.5:dim,0:0.5:dim,0:0.5:dim);\ndist=thresh-sqrt((xi-30).^2+(yi-30).^2+(zi-30).^2);\ndist(find(dist<0))=0;\nclear xi yi zi;\n\n% extract a level-set at v=thresh, being a sphere with R=thresh\n% the maximum element size of the surface triangles is tsize*dim\n\n[node,face]=vol2restrictedtri(dist,1,[dim dim dim],dim*dim*dim,30,esize,esize,40000);\nnode=(node-0.5)*0.5;\n\n[node,face]=removeisolatednode(node,face);\n\nnode=(node-30)/28;\nr0=sqrt(sum((node.*node)'));\nnode=node.*repmat(1./r0(:),1,3);\n\nif(nargout==3)\n if(nargin==1) maxvol=tsize*tsize*tsize; end\n [node,elem,face]=surf2mesh(node,face,[-1 -1 -1]*1.1,[1 1 1]*1.1,1,maxvol,[],[]);\n elem=elem(:,1:4);\nend\nface=face(:,1:3);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/iso2mesh/meshunitsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7538675485511486}} {"text": "function a = moler4 ( )\n\n%*****************************************************************************80\n%\n%% MOLER4 returns the MOLER4 matrix.\n%\n% Example:\n%\n% 0 2 0 -1\n% 1 0 0 0\n% 0 1 0 0\n% 0 0 1 0\n%\n% Properties:\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is the companion matrix of the polynomial X^4-2X^2+1=0.\n%\n% A has eigenvalues -1, -1, +1, +1.\n%\n% A can cause problems to a standard QR algorithm, which\n% can fail to converge.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real A(4,4), the matrix.\n%\n\n%\n% Note that matrix entries are listed by row.\n%\n a = [ ...\n 0.0, 2.0, 0.0, -1.0; ...\n 1.0, 0.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0, 0.0; ...\n 0.0, 0.0, 1.0, 0.0 ];\n\n return\nend%", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/moler4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675472185368}} {"text": "function [w,fun,time,iter] = gistLogistic(X,y,lambda,theta,varargin)\n\n% Generalized Iterative Shrinkage and Thresholding (GIST) with Logsitic Regression loss\n%\n% Non-convex optimization problem:\n%\n% min_w L(w) + \\sum_i r_i(w)\n%\n% ================================ loss function ==========================\n%\n% L(w) = 1/n \\sum_j log(1 + exp(-y_j*x_j'*w)) (n: number of samples)\n%\n% ================================ regularizer ============================\n%\n% regtype = 1: Capped L1 regularizer (CapL1) (default) \n% r_i(w) = lambda*\\min(|w_i|,theta), (theta > 0, lambda >= 0)\n% \n% regtype = 2: Log Sum Penalty (LSP)\n% r_i(w) = lambda*\\sum_i log(1 + |w_i|/theta), (theta > 0, lambda >= 0)\n% \n% regtype = 3: Smoothly Clipped Absolute Deviation (SCAD)\n% r_i(w) = lambda*|w_i|, if |w_i|<=lambda\n% r_i(w) = (-w_i^2 + 2*theta*lambda*|w_i| - lambda^2)/(2(theta - 1)), if lambda<=|w_i|<=theta*lambda\n% r_i(w) = 0.5*(theta + 1)*lambda^2, if |w_i| > theta*lambda, (theta > 2, lambda >= 0)\n%\n% regtype = 4: Minimax Concave Penalty (MCP)\n% r_i(w) = lambda*|w_i| - 0.5*w_i^2/theta, if |w_i|<=theta*lambda\n% r_i(w) = 0.5*theta*lambda^2, if |w_i| > theta*lambda, (theta >\n% 0, lambda >= 0)\n%\n% ============================ Input ======================================\n%\n% X: data matrix with each row as a sample\n%\n% y: label vector (+1 or -1)\n%\n% lambda: regularization parameter\n%\n% theta: theresholding parameter\n%\n% ======================= varargin: optional settings ====================\n%\n% 'regtype': nonconvex regularization type \n% 1: CapL1 (default) \n% 2: LSP \n% 3: SCAD\n% 4: MCP \n%\n% 'stopcriterion': stopping criterion \n% 1: relative difference of objective functions \n% is less than tol (default)\n% 0: relative difference of iterative weights is less\n% than tol\n%\n% 'startingpoint': starting point (default: zero vector)\n%\n% 'tolerance': stopping tolerance (default: 1e-5)\n%\n% 'maxiteration': number of maximum iteration (default: 1000)\n%\n% 'tinitialization': initialization of t (default: 1)\n%\n% 'tmin': tmin parameter (default: 1e-20)\n%\n% 'tmax': tmax parameter (default: 1e-20)\n%\n% 'eta': eta factor (default: 2)\n%\n% 'sigma': parameter in the line search (default: 1e-5)\n%\n% 'nonmonotone': nonmonotone steps in the line search (default: 5)\n% \n% 'stopnum': number of satisfying stopping criterion (default: 3)\n%\n% 'maxinneriter': number of maximum inner iteration (line search) (default: 20)\n%\n% ============================= Output ====================================\n%\n% w: output weight vector\n%\n% fun: a vector including all function values at each iteration\n%\n% time: a vector including all CPU times at each iteration\n%\n% iter: the number of iterative steps \n%\n% =========================================================================\n%\n% Copyright (C) 2012-2013 Pinghua Gong\n%\n% For any problem, please contact Pinghua Gong via pinghuag@gmail.com\n%\n% Last modified on March 14, 2013.\n%\n% Related papers:\n%\n% [1] Pinghua Gong, Changshui Zhang, Zhaosong Lu, Jianhua Huang, Jieping Ye,\n% A General Iterative Shrinkage and Thresholding Algorithm for Non-convex\n% Regularized Optimization Problems. ICML 2013.\n%\n% ========================================================================\n\nif nargin < 4\n error('Too few input parameters!');\nend\n\nif theta <= 0 || lambda < 0\n error('\\theta must be positive and \\lambda must be nonneagtive!');\nend\n\n% Parse the optional inputs.\nif (mod(length(varargin), 2) ~= 0 ),\n error(['Optional Parameters passed to the function ''' mfilename ''' must be passed in pairs!']);\nend\n\n% default parameter settings\nregtype = 1;\n[n,d] = size(X); \nw0 = zeros(d,1);\nstopcriterion = 1;\ntol = 1e-5; \nmaxiter = 1000;\nM = 5;\nsigma = 1e-5;\n\nt = 1;\ntmin = 1e-20;\ntmax = 1e20;\n\n% % t, tmin and tmax are adaptively estimated\n% Linfnorm = full(max(sum(abs(X),2)))/n; L1norm = full(max(sum(abs(X),1)))/n; Lmaxnorm = full(max(max(abs(X))))/n;\n% t = max([Linfnorm*Linfnorm/d,L1norm*L1norm/n,Lmaxnorm]);\n% tmin = min([Linfnorm*Linfnorm/d,L1norm*L1norm/n,Lmaxnorm]);\n% tmax = min([Linfnorm*L1norm,n*d*Lmaxnorm,n*Linfnorm*Linfnorm,d*L1norm*L1norm])/(1-sigma);\n\neta = 2;\nstopnum = 3;\nmaxinneriter = 20;\n\n% Optional parameter settings\nparameterCount = length(varargin)/2;\n\nfor parameterIndex = 1:parameterCount,\n parameterName = varargin{parameterIndex*2 - 1};\n parameterValue = varargin{parameterIndex*2};\n switch lower(parameterName)\n case 'regtype'\n regtype = parameterValue;\n if regtype == 3 && theta <= 2 \n error('\\theta must be greater than 2!');\n end\n case 'startingpoint'\n w0 = parameterValue;\n case 'stopcriterion'\n stopcriterion = parameterValue;\n case 'tolerance'\n tol = parameterValue;\n case 'maxiteration'\n maxiter = parameterValue;\n case 'nonmonotone'\n M = parameterValue;\n case 'tinitialization'\n t = parameterValue;\n case 'tmin'\n tmin = parameterValue;\n case 'tmax'\n tmax = parameterValue;\n case 'sigma'\n sigma = parameterValue;\n case 'eta'\n eta = parameterValue;\n case 'stopnum'\n stopnum = parameterValue;\n case 'maxinneriter'\n maxinneriter = parameterValue;\n otherwise\n error(['The parameter ''' parameterName ''' is not recognized by the function ''' mfilename '''!']);\n end\nend\n\nw = w0; \nfun = zeros(maxiter+1,1); time = fun;\nlogist = zeros(n,1);\n\n% Initial function value\nZ = sparse(1:n,1:n,y,n,n)*X;\nZw = -Z*w; posind = (Zw > 0);\nlogist(posind) = 1 + exp(-Zw(posind));\nlogist(~posind) = 1 + exp(Zw(~posind));\n\ntemp = logist;\ntemp(posind) = 1./logist(posind);\ntemp(~posind) = (logist(~posind)-1)./logist(~posind);\ngrad = -Z'*temp/n;\n\nfun(1) = (sum(log(logist(~posind))) + sum(Zw(posind) + log(logist(posind))))/n + funRegC(w,d,lambda,theta,regtype);\ntime(1) = 0;\n\ncount = 0;\nfor iter = 1:maxiter\n tic;\n \n w_old = w;\n grad_old = grad;\n t = min(max(t,tmin),tmax);\n \n % line search \n for inneriter = 1:maxinneriter\n w = proximalRegC(w_old - grad_old/t, d, lambda/t, theta,regtype);\n dw = w - w_old;\n Zw = -Z*w; posind = (Zw > 0);\n logist(posind) = 1 + exp(-Zw(posind));\n logist(~posind) = 1 + exp(Zw(~posind));\n fun(iter+1) = (sum(log(logist(~posind))) + sum(Zw(posind) + log(logist(posind))))/n + funRegC(w,d,lambda,theta,regtype); \n if fun(iter+1) <= max(fun(max(iter-M+1,1): iter)) - 0.5*sigma*t*norm(dw)^2\n break;\n else\n t = t*eta;\n end\n end\n time(iter+1) = time(iter) + toc; \n \n % stopping condition\n if stopcriterion\n relativediff = abs(fun(iter) - fun(iter+1))/fun(iter+1);\n else\n relativediff = norm(w - w_old)/norm(w);\n end\n if relativediff < tol\n count = count + 1;\n else\n count = 0;\n end\n if count >= stopnum\n break;\n end\n \n temp = logist;\n temp(posind) = 1./logist(posind);\n temp(~posind) = (logist(~posind)-1)./logist(~posind);\n grad = -Z'*temp/n;\n \n % BB rule\n st = w - w_old;\n rt = grad - grad_old;\n if norm(st)/d < 1e-12 || norm(rt)/d < 1e-12\n break;\n end\n t = st'*rt/(st'*st);\n \nend\nfun = fun(1: min(maxiter,iter)+1);\ntime = time(1: min(maxiter,iter)+1);\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/GIST/gistLogistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7538675373170579}} {"text": "function shape_test ( code )\n\n%*****************************************************************************80\n%\n%% SHAPE_TEST verifies the shape function values at the basis nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character ( len = * ) CODE, identifies the element to be used.\n% Legal values include 'Q4', 'Q8', 'Q9', 'Q12', 'Q16', 'QL',\n% 'T3', 'T4', 'T6' and 'T10'.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SHAPE_TEST: Verify shape functions of type \"%s\"\\n', code );\n\n element_order = order_code ( code );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Element order = %d\\n', element_order );\n\n [ r, s, area ] = node_reference ( code );\n\n fprintf ( 1, ' Basis function values at basis nodes\\n' );\n fprintf ( 1, ' should form the identity matrix.\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : element_order\n [ t, dtdr, dtds ] = shape ( code, r(i), s(i) );\n for j = 1 : element_order\n fprintf ( 1, ' %7f', t(j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The R and S derivatives should sum to 0.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' dTdR sum dTdS sum\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : element_order\n [ t, dtdr, dtds ] = shape ( code, r(i), s(i) );\n rsum = sum ( dtdr(1:element_order) );\n ssum = sum ( dtds(1:element_order) );\n fprintf ( 1, ' %14f %14f\\n', rsum, ssum );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/shape_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7538594310815865}} {"text": "function x = tridisolve ( a, b, c, d )\n\n%*****************************************************************************80\n%\n%% TRIDISOLVE solves a tridiagonal system of linear equations.\n%\n% Discussion:\n%\n% We can describe an NxN tridiagonal matrix by vectors A, B, and C, where\n% A and C are of length N-1. In that case, a linear system can be\n% represented as\n% b(1) * x(1) + c(1) * x(2) = d(1),\n% a(j-1) * x(j-1) + b(j) * x(j) + c(j) * x(j+1) = d(j), j = 2:n-1,\n% a(n-1) * x(n-1) + b(n) * x(n) = d(n)\n%\n% This function produces the solution vector X.\n%\n% This function is derived from Cleve Moler's Matlab suite.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Cleve Moler.\n%\n% Parameters:\n%\n% Input, real A(N-1), B(N), C(N-1), the matrix entries.\n%\n% Input, real D(N), the right hand side.\n%\n% Output, real X(N), the solution.\n%\n x = d;\n n = length ( x );\n bi = zeros ( n, 1 );\n\n for j = 1 : n - 1\n bi(j) = 1.0 / b(j);\n mu = a(j) * bi(j);\n b(j+1) = b(j+1) - mu * c(j);\n x(j+1) = x(j+1) - mu * x(j);\n end\n\n x(n) = x(n) / b(n);\n for j = n - 1 : -1 : 1\n x(j) = ( x(j) - c(j) * x(j+1) ) * bi(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/circle_segment/tridisolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7538312001447941}} {"text": "function [ nf, xf, wf, vf ] = line_fekete_monomial ( m, a, b, n, x )\n\n%*****************************************************************************80\n%\n%% LINE_FEKETE_MONOMIAL computes approximate Fekete points in an interval [A,B].\n%\n% Discussion:\n%\n% We use the uniform weight and the monomial basis:\n%\n% P(j) = x^(j-1)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Alvise Sommariva, Marco Vianello,\n% Computing approximate Fekete points by QR factorizations of Vandermonde \n% matrices,\n% Computers and Mathematics with Applications,\n% Volume 57, 2009, pages 1324-1336.\n% \n% Parameters:\n%\n% Input, integer M, the number of basis polynomials.\n%\n% Input, real A, B, the endpoints of the interval.\n%\n% Input, integer N, the number of sample points.\n% M <= N.\n%\n% Input, real X(N), the coordinates of the sample points.\n%\n% Output, integer NF, the number of Fekete points.\n% If the computation is successful, NF = M.\n%\n% Output, real XF(NF), the coordinates of the Fekete points.\n%\n% Output, real WF(NF), the weights of the Fekete points.\n%\n% Output, real VF(NF,M), the nonsingular Vandermonde submatrix.\n%\n if ( n < m )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_FEKETE_MONOMIAL - Fatal error!\\n' );\n fprintf ( 1, ' N < M.\\n' );\n error ( 'LINE_FEKETE_MONOMIAL - Fatal error!' );\n end\n%\n% Destroy all row vectors!\n%\n x = x(:);\n%\n% Moments of monomials:\n%\n mom = line_monomial_moments ( a, b, m );\n%\n% Form the rectangular Vandermonde matrix V for the polynomial basis.\n%\n v = zeros ( m, n );\n\n v(1,1:n) = 1.0;\n for i = 2 : m\n v(i,1:n) = v(i-1,1:n) .* x(1:n)';\n end\n%\n% Solve the system for the weights W.\n%\n w = v \\ mom;\n%\n% Locate nonzero W's.\n%\n ind = find ( w ~= 0.0 );\n%\n% Retain data associated with nonzero W's.\n%\n nf = length ( ind );\n xf = x ( ind );\n wf = w ( ind );\n vf = v ( :, ind );\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_monomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7538311840767745}} {"text": "function [H] = traditional(f);\n\n% TRADITIONAL creates the homogenous spatial transformation matrix\n% for a 9 parameter traditional \"Talairach-model\" transformation\n%\n% Use as\n% [H] = traditional(f)\n%\n% The transformation vector f should contain the \n% x-shift\n% y-shift\n% z-shift\n% followed by the\n% pitch (rotation around x-axis)\n% roll (rotation around y-axis)\n% yaw (rotation around z-axis)\n% followed by the \n% x-rescaling factor\n% y-rescaling factor\n% z-rescaling factor\n%\n% The order in which the transformations are done is exactly opposite as\n% the list above, i.e. first z-rescale, ... and finally x-shift.\n\n% Copyright (C) 2000-2005, Robert Oostenveld\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% $Log: traditional.m,v $\n% Revision 1.1 2009/01/30 04:02:12 arno\n% *** empty log message ***\n%\n% Revision 1.5 2005/08/15 08:15:33 roboos\n% reimplemented the rotate function, which contained an error (the error is in the AIR technical reference)\n% changed all functions to be dependent on the rotate, translate and scale function\n% all functions now behave consistenly, which also means that they are not compleetly backward compatible w.r.t. the order of the rotations\n%\n% Revision 1.4 2005/08/11 07:57:14 roboos\n% fixed bug in y-rotation\n%\n% Revision 1.3 2005/04/21 08:28:45 roboos\n% fixed bug in rotation matrix (thanks to Arno)\n%\n% Revision 1.2 2004/05/19 09:57:07 roberto\n% added GPL copyright statement, added CVS log item\n%\n\n% compute the homogenous transformation matrix for the translation\nT = translate(f([1 2 3]));\n\n% compute the homogenous transformation matrix for the rotation\nR = rotate(f([4 5 6]));\n\n% compute the homogenous transformation matrix for the scaling\nS = scale(f([7 8 9]));\n\n% compute the homogenous transformation matrix for the combination\nH = T*R*S;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/private/traditional.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.753825236602983}} {"text": "function [t,a,k]=BSplineInterpDeriv(t,a,k,numDerivs)\n%%BSPLINEINTERPDERIV Given a set of b-spline interpolation weights a and\n% knots t for scalar interpolation, compute the weights and\n% knots to interpolate the numDerivs derivative value using\n% b-splines interpolation.\n%\n%INPUTS: t The NX1 or 1XN set of knots for the interpolation function. The\n% first and last k-1 knots are outside of the ends of the region\n% with data or mark the ends of the region with data. These vslues\n% must be real.\n% a The npXnumSets collection of b-spline coefficients for\n% interpolating over a certain region for numSets sets of\n% interpolation problems. Such coefficients could be obtained from\n% the function BSplinePolyCoeffs along with t if one wishes to\n% interpolate over gridded data. These values can be complex.\n% k The order of the B-spline polynomials. The order of the\n% interpolation accuracy is k-numDerivs-1.\n% numDerivs The number of derivatives to take. This must be less than k-1.\n%\n%OUTPUTS: a The (np-numDerivs)XnumSets modified coefficients.\n% t The (N-2*numDerivs)X1 modified knots.\n% k The modified B-spline order.\n%\n%This function implements Equation 12b in Chapter X of [1]. The\n%modifications to t simply reflect the modification to the overall length\n%of a.\n%\n%The first and last elements in t are not used in this function. However,\n%the equations in [1] assume that those elements are present as they end up\n%being used when computing integrals.\n%\n%EXAMPLE 1:\n%Here, we approximate the derivative of a fourth-order function using\n%piecewise third-order b-splines and plot the results.\n% f=@(t)(t.^4-2*t.^2+t);\n% tau=[-2;-1;0;0.5;1;1.5;2];\n% y=f(tau);\n% k=4;%k-1=3 is the order....\n% [a,t]=BSplinePolyFit(tau,y,k);\n% \n% x=linspace(-2,2,500);\n% numDerivs=1;\n% [t,a,k]=BSplineInterpDeriv(t,a,k,numDerivs);\n% ypDeriv=BSplineInterpVal(x,t,a,k);\n% yDeriv=1-4*x+4*x.^3;%First derivative\n% \n% figure(1)\n% clf\n% hold on\n% plot(x,yDeriv,'-k','linewidth',4)\n% plot(x,ypDeriv,'--r','linewidth',2)\n%\n%EXAMPLE 2:\n%This is similar to the previous example, except multiple sets of\n%coefficients are computed and evaluated at once.\n% f1=@(t)(t.^4-2*t.^2+t);\n% f2=@(t)(t.^3-2*t.^2+t);\n% tau=[-2;-1;0;0.5;1;1.5;2];\n% y=[f1(tau),f2(tau)];\n% k=4;%k-1=3 is the order....\n% [a,t]=BSplinePolyFit(tau,y,k);\n% \n% x=linspace(-2,2,500).';\n% numDerivs=1;\n% [t,a,k]=BSplineInterpDeriv(t,a,k,numDerivs);\n% ypDeriv=BSplineInterpVal(x,t,a,k);\n% yDeriv=[1-4*x+4*x.^3,1-4*x+3*x.^2];%First derivative\n% \n% figure(1)\n% clf\n% hold on\n% plot(x,yDeriv(:,1),'-k','linewidth',4)\n% plot(x,ypDeriv(:,1),'--r','linewidth',2)\n% \n% figure(2)\n% clf\n% hold on\n% plot(x,yDeriv(:,2),'-k','linewidth',4)\n% plot(x,ypDeriv(:,2),'--r','linewidth',2)\n%\n%EXAMPLE 3:\n%This is an example where a complex function parameterized by a single real\n%value is differentiated and interpolated.\n% numPoints=300;\n% xMin=0;\n% xMax=5;\n% x=linspace(xMin,xMax,numPoints);\n% f=@(x)exp(-1j*2*x).*(4*x.^3+x.*exp(1j*2*x.^2)+12*x+x.^3.*exp(-1j*2*x.^2));\n% \n% fDx=@(x)exp(-2*1j*x.*(1+x)).*(exp(4*1j*x.^2).*(1+2*1j*x.*(-1+2*x))+x.^2.*(3-2*1j*x.*(1+2*x))+4*exp(2*1j*x.^2).*(3+x.*(-6*1j+(3-2*1j*x).*x)));\n% \n% fx=f(x);\n% k=5;\n% [a,t]=BSplinePolyFit(x,fx(:),k);\n% numDerivs=1;\n% [t,a,k]=BSplineInterpDeriv(t,a,k,numDerivs);\n% \n% %Interpolate on a finer grid.\n% numPoints=2000;\n% x=linspace(xMin,xMax,numPoints);\n% fx=fDx(x);\n% fxInterp=BSplineInterpVal(x,t,a,k);\n% \n% %Plot the function values and the interpolated values for the real and\n% %complex parts.\n% figure(1)\n% clf\n% hold on\n% plot(x,real(fx),'-k','linewidth',2)\n% plot(x,imag(fx),'--k','linewidth',2)\n% plot(x,real(fxInterp),'-r')\n% plot(x,imag(fxInterp),'--r')\n% \n% %Plot the interpolation error.\n% figure(2)\n% clf\n% hold on \n% plot(x,real(fxInterp(:))-real(fx(:)))\n% plot(x,imag(fxInterp(:))-imag(fx(:)))\n%\n%REFERENCES:\n%[1] C. de Boor, A Practical Guide to Splines. New York: Springer-Verlag,\n% 1978.\n%\n%April 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumA=size(a,1);\n\nfor curDeriv=1:numDerivs\n aNext=a;\n for idxA=(curDeriv+1):numA\n denom=(t(idxA+k-curDeriv)-t(idxA))/(k-curDeriv);\n\n if(denom==0)\n aNext(idxA,:)=0;\n else\n aNext(idxA,:)=(a(idxA,:)-a(idxA-1,:))/denom;\n end\n end\n\n a=aNext;\nend\na=a((1+numDerivs):end,:);\nt=t((1+numDerivs):(end-numDerivs));\nk=k-numDerivs;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Interpolation/B-Splines/BSplineInterpDeriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.753825234496798}} {"text": "function [suspicious_index lof] = LOF(A, k)\n%#####################################################################\n%# Local Outlier Factor #\n%# Authors: Markus M. Breunig, Hans-Peter Kriegel, # \n%# Raymond T. Ng, J?rg Sander #\n%# Oringinal paper : #\n%# LOF: Identifying Density-Based Local Outliers #\n%# e-mail : { breunig | kriegel | sander } #\n%# @dbs.informatik.uni-muenchen.de #\n%# rng@cs.ubc.ca #\n%# Programmer: Yi-Ren Yeh(yirenyeh@gmail.com) #\n%# modified by: Zi-Wen Gui(evan176@hotmail.com) #\n%# #\n%# #\n%# Inputs #\n%# A: the data matrix, each row reprent an instance #\n%# k: the number of nearest neighbors #\n%# #\n%# Outputs #\n%# lof: the local outlier factor for each instance #\n%# suspicious_index: the ranking of instances according to their #\n%# suspiciuous score #\n%# For example, suspicious_index(i)=j means the #\n%# ith instance is in jth position in the ranking#\n%#####################################################################\n\n\n%Find the nearest neighbors by \"KDTree\" for each elements \n[k_index, k_dist] = knnsearch(A,A,'k',k+1,'nsmethod','kdtree');\n%Ignore first element(itself) at nearest neighbors \nk_index = k_index(:,2:end);\n%Get k-distance\nk_dist1 = k_dist(:,end);\n%Get row length of matrix A\nn = length(A(:,1));\n%Initializa lrd_value vector\nlrd_value = zeros(n,1);\n%Calculate lrd for each elements\nfor i = 1:n\n lrd_value(i) = lrd(A, i, k_dist1,k_index, k);\nend\n%Initializa lof vector\nlof = zeros(n,1);\n%Calculate LOF\nfor i = 1:n\n lof(i) = sum(lrd_value(k_index(i,:))/lrd_value(i))/k;\nend\n%Sort lof factor\n[non,suspicious_index]=sort(lof,'descend');\n\n\n\n%=========================================================================\nfunction lrd_value = lrd(A, index_p, k_dist,k_index, k)\n%Calculate the reachability distance for nearest neighbors\nTemp = repmat(A(index_p,:),k,1) - A(k_index(index_p,:),:);\nTemp = sqrt(sum(Temp.^2,2));\n%max{k-distance(b), d(a, b)}\nrd_dsit = max([Temp k_dist(k_index(index_p,:))],[],2);\n%Calculate the local reachability density for each elements\nlrd_value = k/sum(rd_dsit);\n\n\n", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/distributionBased/LOF/LOF_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8397339616560073, "lm_q1q2_score": 0.7538252194045467}} {"text": "function [ point_coord, face_order, face_point ] = ...\n tetrahedron_rhombic_shape_3d ( point_num, face_num, face_order_max )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_RHOMBIC_SHAPE_3D describes a rhombic tetrahedron in 3D.\n%\n% Discussion:\n%\n% Call TETRAHEDRON_RHOMBIC_SIZE_3D first, to get dimension information.\n%\n% The tetrahedron is described using 10 nodes. If we label the vertices\n% P0, P1, P2 and P3, then the extra nodes lie halfway between vertices,\n% and have the labels P01, P02, P03, P12, P13 and P23.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Anwei Liu, Barry Joe,\n% Quality Local Refinement of Tetrahedral Meshes Based\n% on 8-Subtetrahedron Subdivision,\n% Mathematics of Computation,\n% Volume 65, Number 215, July 1996, pages 1183-1200.\n%\n% Parameters:\n%\n% Input, integer POINT_NUM, the number of points in the shape.\n%\n% Input, integer FACE_NUM, the number of faces in the shape.\n%\n% Input, integer FACE_ORDER_MAX, the maximum number of vertices per face.\n%\n% Output, real POINT_COORD(3,POINT_NUM), the vertices.\n%\n% Output, integer FACE_ORDER(FACE_NUM), the number of vertices\n% for each face.\n%\n% Output, integer FACE_POINT(FACE_ORDER_MAX,FACE_NUM); FACE_POINT(I,J)\n% contains the index of the I-th point in the J-th face. The\n% points are listed in the counter clockwise direction defined\n% by the outward normal at the face.\n%\n dim_num = 3;\n\n a = 1.0 / sqrt ( 3.0 );\n b = sqrt ( 2.0 ) / sqrt ( 3.0 );\n c = sqrt ( 3.0 ) / 6.0;\n d = 1.0 / sqrt ( 6.0 );\n z = 0.0;\n%\n% Set the point coordinates.\n%\n point_coord(1:dim_num,1) = [ -b, z, z ]';\n point_coord(1:dim_num,2) = [ z, -a, z ]';\n point_coord(1:dim_num,3) = [ z, a, z ]';\n point_coord(1:dim_num,4) = [ z, z, b ]';\n point_coord(1:dim_num,5) = [ -d, -c, z ]';\n point_coord(1:dim_num,6) = [ -d, c, z ]';\n point_coord(1:dim_num,7) = [ -d, z, d ]';\n point_coord(1:dim_num,8) = [ z, z, z ]';\n point_coord(1:dim_num,9) = [ z, -c, d ]';\n point_coord(1:dim_num,10) = [ z, c, d ]';\n%\n% Set the face orders.\n%\n face_order(1:face_num) = [ 6, 6, 6, 6 ];\n%\n% Set faces.\n%\n face_point(1:face_order_max,1:face_num) = [ ...\n 1, 5, 2, 9, 4, 7; ...\n 2, 8, 3, 10, 4, 9; ...\n 3, 6, 1, 7, 4, 10; ...\n 1, 6, 3, 8, 2, 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/geometry/tetrahedron_rhombic_shape_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7538233131615252}} {"text": "% LLE ALGORITHM (using K nearest neighbors)\n%\n% [Y] = lle(X,K,dmax)\n%\n% X = data as D x N matrix (D = dimensionality, N = #points)\n% K = number of neighbors\n% dmax = max embedding dimensionality\n% Y = embedding as dmax x N matrix\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [Y] = lle(X,K,d)\n\n[D,N] = size(X);\nfprintf(1,'LLE running on %d points in %d dimensions\\n',N,D);\n\n\n% STEP1: COMPUTE PAIRWISE DISTANCES & FIND NEIGHBORS \nfprintf(1,'-->Finding %d nearest neighbours.\\n',K);\n\nX2 = sum(X.^2,1);\ndistance = repmat(X2,N,1)+repmat(X2',1,N)-2*X'*X;\n\n[sorted,index] = sort(distance);\nneighborhood = index(2:(1+K),:);\n\n\n\n% STEP2: SOLVE FOR RECONSTRUCTION WEIGHTS\nfprintf(1,'-->Solving for reconstruction weights.\\n');\n\nif(K>D) \n fprintf(1,' [note: K>D; regularization will be used]\\n'); \n tol=1e-3; % regularlizer in case constrained fits are ill conditioned\nelse\n tol=0;\nend\n\nW = zeros(K,N);\nfor ii=1:N\n z = X(:,neighborhood(:,ii))-repmat(X(:,ii),1,K); % shift ith pt to origin\n C = z'*z; % local covariance\n C = C + eye(K,K)*tol*trace(C); % regularlization (K>D)\n W(:,ii) = C\\ones(K,1); % solve Cw=1\n W(:,ii) = W(:,ii)/sum(W(:,ii)); % enforce sum(w)=1\nend;\n\n\n% STEP 3: COMPUTE EMBEDDING FROM EIGENVECTS OF COST MATRIX M=(I-W)'(I-W)\nfprintf(1,'-->Computing embedding.\\n');\n\n% M=eye(N,N); % use a sparse matrix with storage for 4KN nonzero elements\nM = sparse(1:N,1:N,ones(1,N),N,N,4*K*N); \nfor ii=1:N\n w = W(:,ii);\n jj = neighborhood(:,ii);\n M(ii,jj) = M(ii,jj) - w';\n M(jj,ii) = M(jj,ii) - w;\n M(jj,jj) = M(jj,jj) + w*w';\nend;\n\n% CALCULATION OF EMBEDDING\noptions.disp = 0; options.isreal = 1; options.issym = 1; \n[Y,eigenvals] = eigs(M,d+1,0,options);\nY = Y(:,2:d+1)'*sqrt(N); % bottom evect is [1,1,1,1...] with eval 0\n\n\nfprintf(1,'Done.\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% other possible regularizers for K>D\n% C = C + tol*diag(diag(C)); % regularlization\n% C = C + eye(K,K)*tol*trace(C)*K; % regularlization\n", "meta": {"author": "jindongwang", "repo": "activityrecognition", "sha": "33687803886d4a184e0b285e3ec7ab73a8f86355", "save_path": "github-repos/MATLAB/jindongwang-activityrecognition", "path": "github-repos/MATLAB/jindongwang-activityrecognition/activityrecognition-33687803886d4a184e0b285e3ec7ab73a8f86355/code/percom18_stl/base/preprocess/lle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7538233089574611}} {"text": "function Y = spe(X, no_dims, varargin)\n%SPE Perform the Stochastic Proximity Embedding algorithm\n%\n% Y = spe(X, no_dims, 'Global')\n% Y = spe(X, no_dims, 'Local', k)\n%\n% Perform the Stochastic Proximity Embedding algorithm. The SPE algorithm\n% can be compared to the MDS algorithm, although it is much more efficient.\n% The total number of updates necessary after the random initialization is\n% usually less than n^2 (where n is the number of datapoints). X is the set\n% of datapoints on which SPE has to be applied, and no_dims the number of\n% dimensions in the embedding space. If the method is used with the 'Global'\n% switch, a minimization of the traditional MDS raw stress function is \n% performed (the default). Execution with the 'Local' switch only retains \n% Euclidean distances in the local neighborhood of the datapoints. The size\n% of the neighborhood is defined by the variable k (default = 12).\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if nargin <= 2\n variant = 'Global';\n else\n variant = varargin{1};\n end\n if strcmp(variant, 'Local')\n if nargin > 3, k = varargin{2};\n else k = 12; end\n end\n if ~strcmp(variant, 'Global') && ~strcmp(variant, 'Local')\n error('Unknown parameter.');\n end\n if exist('k', 'var') && ischar(k)\n error('Adaptive neighborhood selection is not yet supported in SPE.');\n end\n \n % Initialize parameters\n lambda = 1; % initial learning parameter\n s = 100; % number of updates per iteration\n max_iter = 20000 + round(.04 * size(X, 1) ^ 2); % number of iterations\n tol = 1e-5; % regularlization parameter\n n = size(X, 1); % number of datapoints\n if strcmp(variant, 'Local')\n max_iter = max_iter * 3;\n end\n \n % Compute proximity matrix in original space\n if strcmp(variant, 'Global')\n R = L2_distance(X', X');\n R = R / max(max(R)) * sqrt(2);\n else\n [R, n_ind] = find_nn(X, k);\n end\n \n % Initialize datapoints randomly\n Y = rand(n, no_dims);\n \n % Perform SPE\n for i=1:max_iter\n if rem(i, 10000) == 0\n disp(['Iteration ' num2str(i) ' of ' num2str(max_iter) '...']);\n end\n \n % Select points that should be updated\n J = randperm(n);\n ind1 = J(1:s); \n if strcmp(variant, 'Global')\n ind2 = J(s+1:2*s);\n else\n ind2 = double(n_ind(ind1,:))';\n J = round(rand(1, size(ind2, 2)) * (k - 1)) + 1;\n J = J + ((0:length(J) - 1) * k);\n ind2 = ind2(J);\n end\n \n % Compute distances between points in embedded space\n D = sqrt(sum((Y(ind1,:) - Y(ind2,:)) .^ 2, 2));\n \n % Get corresponding distances in real space\n Rt = R((ind1 - 1) * size(R, 1) + ind2)';\n \n % Update locations of points\n Y(ind1,:) = Y(ind1,:) + lambda * (1/2) * repmat(((Rt - D) ./ (D + tol)), 1, no_dims) .* (Y(ind1,:) - Y(ind2,:));\n Y(ind2,:) = Y(ind2,:) + lambda * (1/2) * repmat(((Rt - D) ./ (D + tol)), 1, no_dims) .* (Y(ind2,:) - Y(ind1,:));\n \n % Update learning parameter\n lambda = lambda - (lambda / max_iter); \n end\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/spe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7538233068554291}} {"text": "function llh=local2llh(xy,origin)\n%local2llh llh=local2llh(xy,origin)\n%\n%Converts from local coorindates to longitude and latitude \n%given the [lon, lat] of an origin. 'origin' should be in \n%decimal degrees. Note that heights are ignored and that \n%xy is in km. Output is [lon, lat, height] in decimal \n%degrees. This is an iterative solution for the inverse of \n%a polyconic projection.\n\n%-------------------------------------------------------------\n% Record of revisions:\n%\n% Date Programmer Description of Change\n% ==== ========== =====================\n%\n% Aug 23, 2001 Jessica Murray Clarification to help.\n%\n% Apr 4, 2001 Peter Cervelli Added failsafe to avoid\n% infinite loop because of\n% covergence failure.\n% Sep 7, 2000 Peter Cervelli\t\tOriginal Code\n%\n%-------------------------------------------------------------\n\n%Set ellipsoid constants (WGS84)\n\n a=6378137.0;\n e=0.08209443794970;\n\n%Convert to radians / meters\n\n% xy=xy*1000;\n% origin=origin*pi/180;\n xy=double(xy)*1000;\n origin=double(origin)*pi/180;\n\n%Iterate to perform inverse projection\n\n M0=a*((1-e^2/4-3*e^4/64-5*e^6/256)*origin(2) - ...\n (3*e^2/8+3*e^4/32+45*e^6/1024)*sin(2*origin(2)) + ...\n (15*e^4/256 +45*e^6/1024)*sin(4*origin(2)) - ...\n (35*e^6/3072)*sin(6*origin(2)));\n\n z=xy(2,:)~=-M0;\n\n A=(M0+xy(2,z))/a;\n B=xy(1,z).^2./a^2+A.^2;\n\n llh(2,z)=A;\n\n delta=Inf;\n\n c=0;\n \n while max(abs(delta))>1e-8\n\n C=sqrt((1-e^2*sin(llh(2,z)).^2)).*tan(llh(2,z));\n\n M=a*((1-e^2/4-3*e^4/64-5*e^6/256)*llh(2,z) - ...\n (3*e^2/8+3*e^4/32+45*e^6/1024)*sin(2*llh(2,z)) + ...\n (15*e^4/256 +45*e^6/1024)*sin(4*llh(2,z)) - ...\n (35*e^6/3072)*sin(6*llh(2,z)));\n\n Mn=1-e^2/4-3*e^4/64-5*e^6/256 - ...\n -2*(3*e^2/8+3*e^4/32+45*e^6/1024)*cos(2*llh(2,z)) + ...\n 4*(15*e^4/256 +45*e^6/1024)*cos(4*llh(2,z)) + ...\n -6*(35*e^6/3072)*cos(6*llh(2,z));\n\n Ma=M/a;\n \n delta=-(A.*(C.*Ma+1)-Ma-0.5*(Ma.^2+B).*C)./ ...\n (e^2*sin(2*llh(2,z)).*(Ma.^2+B-2*A.*Ma)./(4*C)+(A-Ma).*(C.*Mn-2./sin(2*llh(2,z)))-Mn);\n\n llh(2,z)=llh(2,z)+delta;\n\n c=c+1;\n if c>100\n error('Convergence failure.')\n end\n end\n\n llh(1,z)=(asin(xy(1,z).*C/a))./sin(llh(2,z))+origin(1);\n\n%Handle special case of latitude = 0\n\n llh(1,~z)=xy(1,~z)/a+origin(1);\n llh(2,~z)=0;\n\n%Convert back to decimal degrees\n\n llh=llh*180/pi;\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/local2llh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7537913932521566}} {"text": "function [param]=zn2pd(input)\n% [param]=zn2pd(input)\n% Ziegler-Nichols PD controller for processes of 2nd order.\n% Controller uses reference variable (w) just in proportional component.\n% This function computes parameters of the controller (r0, q0, q1, q2, p1, p2).\n% Output of the controller is calculated follows:\n%\n% r0 q0 + q1*z^-1 + q2*z^-2 \n% U(z^-1) = ----------------------- * W(z^-1) - ------------------------ * Y(z^-1)\n% 1 + p1*z^-1 + p2*z^-2 1 + p1*z^-1 + p2*z^-2\n%\n% where p1=0, p2=0, q2=0\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2\n% Gs(z^-1) = -----------------------\n% 1 + a1*z^-1 + a2*z^-2\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... sample time T0\n% Output: param ... controller parameters \n% param(1) ... r0\n% param(2) ... q0\n% param(3) ... q1\n% param(4) ... q2 (0)\n% param(5) ... p1 (0)\n% param(6) ... p2 (0)\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\nT0 = input(5);\n\n% compute ultimate gain and frequency\n[Kpu, Tu] = ultim([b1 b2],[a1 a2],T0);\n\nKp = 0.4*Kpu;\nTd = Tu/20;\n\nr0 = Kp;\nq0 = Kp*(1+Td/T0);\nq1 = -Kp*(Td/T0);\nq2 = 0;\np1 = 0;\np2 = 0;\n\nparam=[r0; q0; q1; q2; p1; p2];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8381-stcsl-standard-version/zn2pd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95041097139764, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7537765928384125}} {"text": "function p = normpdfln(x, m, S, V)\n% NORMPDFLN log of multivariate normal density.\n% See NORMPDF for argument description.\n\nlog2pi = 1.83787706640935;\n[d, n] = size(x);\nif nargin == 1\n dx = x;\nelseif isempty(m)\n dx = x;\nelse\n % m specified\n sz = size(m);\n if sz(1) ~= d\n error('rows(m) ~= rows(x)')\n end\n nm = sz(2);\n if nm == 1\n dx = x - repmat(m,1,n);\n elseif n == 1\n dx = repmat(x,1,nm) - m;\n elseif nm == n\n dx = x - m;\n else\n error('incompatible number of columns in x and m')\n end\nend\nif nargin < 3\n % unit variance\n p = -0.5*(d*log2pi + col_sum(dx.*dx));\n return\nend\nhave_inv = 0;\nif nargin == 3\n % standard deviation given\n if d == 1\n dx = dx./S;\n p = (-log(S) -0.5*log2pi) - 0.5*(dx.*dx);\n return;\n end\n if S(2,1) ~= 0\n error('S is not upper triangular')\n end\n if any(size(S) ~= [d d])\n error('S is not the right size')\n end\nelse\n if ischar(V)\n if strcmp(V,'inv')\n % inverse stddev given\n iS = S;\n have_inv = 1;\n else\n error('unknown directive')\n end\n elseif ischar(S) \n if strcmp(S,'inv')\n % inverse variance given\n if d == 1\n\tiS = sqrt(V);\n else\n\tiS = chol(V);\n end\n have_inv = 1;\n else\n error('unknown directive')\n end\n else\n % variance given\n if d == 1\n S = sqrt(V);\n else\n S = chol(V);\n end\n end\nend\nif have_inv\n if d == 1\n dx = iS .* dx;\n logdetiS = log(iS);\n else\n dx = iS*dx;\n logdetiS = sum(log(diag(iS)));\n end\nelse\n if d == 1\n dx = dx./S;\n logdetiS = -log(S);\n else\n dx = solve_tril(S',dx);\n %dx = S'\\dx;\n logdetiS = -sum(log(diag(S)));\n end\nend\np = (logdetiS -0.5*d*log2pi) -0.5*col_sum(dx.*dx);\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/lightspeed/normpdfln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7537397726315449}} {"text": "function res = polynomialTransform2d(pts, coeffs)\n%POLYNOMIALTRANSFORM2D Apply a polynomial transform to a set of points.\n%\n% RES = polynomialTransform2d(PTS, COEFFS)\n% Transforms the input points PTS given as a N-by-2 array of coordinates\n% using the polynomial transform defined by PARAMS.\n% PARAMS given as [a0 b0 a1 b1 ... an bn]\n%\n% Example\n% coeffs = [0 0 1 0 0 1 0.1 0 0 0 0 0.1];\n% % cte x y x^2 x*y y^2\n% pts = rand(200, 2) * 2 - 1;\n% pts2 = polynomialTransform2d(pts, coeffs);\n% figure; hold on;\n% drawPoint(pts);\n% drawPoint(pts2, 'g');\n%\n% See also \n% transformPoint, fitPolynomialTransform2d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2013-09-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013-2022 INRA - Cepia Software Platform\n\nx = pts(:,1);\ny = pts(:,2);\nnPoints = length(x);\n\n\nxCoeffs = coeffs(1:2:end);\nyCoeffs = coeffs(2:2:end);\nnCoeffs = length(xCoeffs);\n\n% allocate memory for result\nx2 = zeros(nPoints, 1);\ny2 = zeros(nPoints, 1);\n\n% degree from coefficient number\ndegree = sqrt(9/4 - 4*(1 - nCoeffs)/2) - 1.5;\n\n% iterate over degrees\niCoeff = 0;\nfor iDegree = 0:degree\n \n % iterate over binomial coefficients of a given degree\n for k = 0:iDegree\n iCoeff = iCoeff + 1;\n tmp = power(x, iDegree-k) .* power(y, k);\n x2 = x2 + xCoeffs(iCoeff) .* tmp;\n y2 = y2 + yCoeffs(iCoeff) .* tmp;\n end\nend\n\nres = [x2 y2];\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/polynomialTransform2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7536388025225289}} {"text": "function value = wedge01_integral ( e )\n\n%*****************************************************************************80\n%\n%% WEDGE01_INTEGRAL returns the integral of a monomial in the unit wedge in 3D.\n%\n% Discussion:\n%\n% This routine returns the integral of\n%\n% product ( 1 <= I <= 3 ) X(I)^E(I)\n%\n% over the unit wedge.\n%\n% The integration region is:\n%\n% 0 <= X\n% 0 <= Y\n% X + Y <= 1\n% -1 <= Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 August 2014\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 E(3), the exponents.\n%\n% Output, real VALUE, the integral of the monomial.\n%\n value = 1.0;\n\n k = e(1);\n\n for i = 1 : e(2)\n k = k + 1;\n value = value * i / k;\n end\n\n k = k + 1;\n value = value / k;\n\n k = k + 1;\n value = value / k;\n%\n% Now account for integration in Z.\n%\n if ( e(3) == - 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'WEDGE01_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' E(3) = -1 is not a legal input.\\n' );\n error ( 'WEDGE01_INTEGRAL - Fatal error!' );\n elseif ( mod ( e(3), 2 ) == 1 )\n value = 0.0;\n else\n value = value * 2.0 / ( e(3) + 1 );\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/wedge_integrals/wedge01_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7536388002740556}} {"text": "function jac = compute_jacobian(v,u,w)\n%\n% To compute Jacobian determinant for the image deformation field\n% Usage: jac = compute_jacobian(vy,vx,vz);\n%\n[a11,a12,a13] = gradient_3d_by_mask(u); clear u;\n[a21,a22,a23] = gradient_3d_by_mask(v); clear v;\n[a31,a32,a33] = gradient_3d_by_mask(w); clear w;\na11 = a11+1;\na22 = a22+1;\na33 = a33+1;\n\njac = a11.*a22.*a33-a11.*a23.*a32-a21.*a12.*a33+a21.*a13.*a32+a31.*a12.*a23-a31.*a13.*a22;\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/compute_jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768651485396, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.753629485076503}} {"text": "function [lp,dlp] = priorInvGauss(mu,lam,x)\n\n% Univariate Inverse Gaussian hyperparameter prior distribution.\n% Compute log-likelihood and its derivative or draw a random sample.\n% The prior distribution is parameterized as:\n%\n% p(x) = exp(-lam*(x-mu)^2/(2*mu^2*x)) / sqrt(2*pi*x^3/lam)\n%\n% where mu(1x1) is the mean parameter, lam(1x1) is the scale parameter\n% and x(1xN) contains query hyperparameters for prior evaluation.\n%\n% For more help on design of priors, try \"help priorDistributions\".\n%\n% Copyright (c) by Roman Garnett and Hannes Nickisch, 2014-09-08.\n%\n% See also PRIORDISTRIBUTIONS.M.\n\nif nargin<2, error('mu and lam parameters need to be provided'), end\nif ~(isscalar(mu)&&isscalar(lam))\n error('mu and lam parameters need to be scalars'),end\nif nargin<3 % return a sample\n n = randn; y = n*n;\n r = mu + mu*(mu*y-sqrt(4*mu*lam*y+mu^2*y^2))/(2*lam);\n z = rand;\n if z<=mu/(mu+r)\n lp = r;\n else\n lp = mu^2/r;\n end\n return\nend\n\nlp = -lam*(x-mu).^2./(2*mu^2*x) - log(2*pi*x.^3/lam)/2;\nq = (x-mu)./x;\ndlp = -lam*q.*(2-q)/(2*mu^2) - 3./(2*x);\nlp(x<0) = -inf; dlp(x<0) = 0;", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/prior/priorInvGauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069627, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7536294848352911}} {"text": "function val = gamma_multivariate_ln(x,p);\n% function val = gamma_multivariate_ln(x,p);\n%\n% x: array(1,K)\n% p: scalor\n%\n% x must be more than (p-1)/2\n% x should be more than p/2\n%\n% Gamma_p(x) = pi^(p(p-1)/4) prod_(j=1)^p Gamma(x+(1-j)/2)\n% log Gamma_p(x) = p(p-1)/4 log pi + sum_(j=1)^p log Gamma(x+(1-j)/2)\n\nK = length(x);\ngammaln_val = gammaln(repmat(x,p,1)+0.5*(1-repmat([1:p]',1,K))); % p by K\nval = p*(p-1)*0.25 * log(pi) + sum(gammaln_val,1);\n\n\n% Local Variables: ***\n% mode: matlab ***\n% End: ***\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/vdpgm-2010-06-01/gamma_multivariate_ln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.753629481556367}} {"text": "function D = sqdistance(A, B, M)\n% Square Euclidean or Mahalanobis distances between all sample pairs\n% A: d x n1 data matrix\n% B: d x n2 data matrix\n% M: d x d Mahalanobis matrix\n% D: n1 x n2 pairwise square distance matrix\n% Written by Michael Chen (sth4nth@gmail.com). July 2009.\n\nif nargin == 1\n A = bsxfun(@minus,A,mean(A,2));\n S = full(sum(A.^2,1));\n D = full((-2)*(A'*A));\n D = bsxfun(@plus,D,S);\n D = bsxfun(@plus,D,S');\nelseif nargin == 2\n assert(size(A,1)==size(B,1));\n \n m = (sum(A,2)+sum(B,2))/(size(A,2)+size(B,2));\n A = bsxfun(@minus,A,m);\n B = bsxfun(@minus,B,m);\n D = full((-2)*(A'*B));\n D = bsxfun(@plus,D,full(sum(B.^2,1)));\n D = bsxfun(@plus,D,full(sum(A.^2,1)'));\nelseif nargin == 3\n assert(size(A,1)==size(B,1));\n \n m = (sum(A,2)+sum(B,2))/(size(A,2)+size(B,2));\n A = bsxfun(@minus,A,m);\n B = bsxfun(@minus,B,m);\n D = full((-2)*(A'*M*B));\n D = bsxfun(@plus,D,full(sum(B.*(M*B),1)));\n D = bsxfun(@plus,D,full(sum(A.*(M*A),1)'));\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Tools/sqdistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7535452605354548}} {"text": "function [varargout] = wavefilter(wname, type)\n%WAVEFILTER Create wavelet decomposition and reconstruction filters.\n% [VARARGOUT] = WAVEFILTER(WNAME, TYPE) returns the decomposition\n% and/or reconstruction filters used in the computation of the\n% forward and inverse FWT (fast wavelet transform). \n%\n% EXAMPLES:\n% [ld, hd, lr, hr] = wavefilter('haar') Get the low and highpass \n% decomposition (ld, hd) \n% and reconstruction \n% (lr, hr) filters for \n% wavelet 'haar'.\n% [ld, hd] = wavefilter('haar','d') Get decomposition filters\n% ld and hd.\n% [lr, hr] = wavefilter('haar','r') Get reconstruction \n% filters lr and hr.\n%\n% INPUTS:\n% WNAME Wavelet Name\n% ---------------------------------------------------------\n% 'haar' or 'db1' Haar\n% 'db4' 4th order Daubechies\n% 'sym4' 4th order Symlets\n% 'bior6.8' Cohen-Daubechies-Feauveau biorthogonal\n% 'jpeg9.7' Antonini-Barlaud-Mathieu-Daubechies\n%\n% TYPE Filter Type\n% ---------------------------------------------------------\n% 'd' Decomposition filters\n% 'r' Reconstruction filters\n%\n% See also WAVEFAST and WAVEBACK.\n\n% Copyright 2002-2004 R. C. Gonzalez, R. E. Woods, & S. L. Eddins\n% Digital Image Processing Using MATLAB, Prentice-Hall, 2004\n% $Revision: 1.5 $ $Date: 2003/10/13 01:09:39 $\n\n% Check the input and output arguments.\nerror(nargchk(1, 2, nargin));\n\nif (nargin == 1 & nargout ~= 4) | (nargin == 2 & nargout ~= 2)\n error('Invalid number of output arguments.'); \nend\n\nif nargin == 1 & ~ischar(wname)\n error('WNAME must be a string.'); \nend\n\nif nargin == 2 & ~ischar(type)\n error('TYPE must be a string.'); \nend\n \n% Create filters for the requested wavelet.\nswitch lower(wname)\ncase {'haar', 'db1'}\n ld = [1 1]/sqrt(2); hd = [-1 1]/sqrt(2);\n lr = ld; hr = -hd;\n \ncase 'db4'\n ld = [-1.059740178499728e-002 3.288301166698295e-002 ...\n 3.084138183598697e-002 -1.870348117188811e-001 ...\n -2.798376941698385e-002 6.308807679295904e-001 ...\n 7.148465705525415e-001 2.303778133088552e-001];\n t = (0:7);\n hd = ld; hd(end:-1:1) = cos(pi * t) .* ld;\n lr = ld; lr(end:-1:1) = ld;\n hr = cos(pi * t) .* ld;\n \ncase 'sym4'\n ld = [-7.576571478927333e-002 -2.963552764599851e-002 ...\n 4.976186676320155e-001 8.037387518059161e-001 ...\n 2.978577956052774e-001 -9.921954357684722e-002 ...\n -1.260396726203783e-002 3.222310060404270e-002];\n t = (0:7);\n hd = ld; hd(end:-1:1) = cos(pi * t) .* ld;\n lr = ld; lr(end:-1:1) = ld;\n hr = cos(pi * t) .* ld;\n \ncase 'bior6.8'\n ld = [0 1.908831736481291e-003 -1.914286129088767e-003 ...\n -1.699063986760234e-002 1.193456527972926e-002 ...\n 4.973290349094079e-002 -7.726317316720414e-002 ...\n -9.405920349573646e-002 4.207962846098268e-001 ...\n 8.259229974584023e-001 4.207962846098268e-001 ...\n -9.405920349573646e-002 -7.726317316720414e-002 ...\n 4.973290349094079e-002 1.193456527972926e-002 ...\n -1.699063986760234e-002 -1.914286129088767e-003 ...\n 1.908831736481291e-003];\n hd = [0 0 0 1.442628250562444e-002 -1.446750489679015e-002 ...\n -7.872200106262882e-002 4.036797903033992e-002 ...\n 4.178491091502746e-001 -7.589077294536542e-001 ...\n 4.178491091502746e-001 4.036797903033992e-002 ...\n -7.872200106262882e-002 -1.446750489679015e-002 ...\n 1.442628250562444e-002 0 0 0 0];\n t = (0:17);\n lr = cos(pi * (t + 1)) .* hd;\n hr = cos(pi * t) .* ld;\n \ncase 'jpeg9.7'\n ld = [0 0.02674875741080976 -0.01686411844287495 ...\n -0.07822326652898785 0.2668641184428723 ...\n 0.6029490182363579 0.2668641184428723 ...\n -0.07822326652898785 -0.01686411844287495 ...\n 0.02674875741080976];\n hd = [0 -0.09127176311424948 0.05754352622849957 ...\n 0.5912717631142470 -1.115087052456994 ...\n 0.5912717631142470 0.05754352622849957 ...\n -0.09127176311424948 0 0];\n t = (0:9);\n lr = cos(pi * (t + 1)) .* hd;\n hr = cos(pi * t) .* ld;\n \notherwise\n error('Unrecognizable wavelet name (WNAME).');\nend\n\n% Output the requested filters.\nif (nargin == 1)\n varargout(1:4) = {ld, hd, lr, hr};\nelse\n switch lower(type(1))\n case 'd'\n varargout = {ld, hd};\n case 'r'\n varargout = {lr, hr};\n otherwise\n error('Unrecognizable filter TYPE.');\n end\nend\n", "meta": {"author": "61--", "repo": "weiyanmin", "sha": "e15a7789602ec65c7ce1972bd905826ff4851435", "save_path": "github-repos/MATLAB/61---weiyanmin", "path": "github-repos/MATLAB/61---weiyanmin/weiyanmin-e15a7789602ec65c7ce1972bd905826ff4851435/Matlab/wavefilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7535398858239873}} {"text": "function hpdi = hpdi(x, p)\n% HPDI - Estimates the Bayesian HPD intervals\n%\n% Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval\n% for each column of X. P must be a scalar. Y is a 2 row matrix\n% where ith column is HPDI for ith column of X.\n\n% References:\n% [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).\n% Monte Carlo Methods in Bayesian Computation. Springer-Verlag.\n\n% Copyright (C) 2001 Aki Vehtari\n%\n% This software is distributed under the GNU General Public \n% Licence (version 3 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nif nargin < 2\n error('Not enough arguments')\nend\n\nm=size(x,2);\npts=linspace(0.1,99.9-p,20);\npt1=prctile(x,pts);\npt2=prctile(x,p+pts);\ncis=abs(pt2-pt1);\n[foo,hpdpi]=min(cis);\nif m==1\n hpdi=[pt1(hpdpi); pt2(hpdpi)];\nelse\n hpdpi=sub2ind(size(pt1),hpdpi,1:m);\n hpdi=[pt1(hpdpi); pt2(hpdpi)];\nend\n", "meta": {"author": "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/hpdi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7535398652192723}} {"text": "function I = integral2(f, S)\n%INTEGRAL2 Surface integral of a CHEBFUN3.\n% INTEGRAL2(F, S) returns integral of the CHEBFUN3 object F over the \n% parametric surface S defined as a CHEBFUN2V object.\n%\n% I = INTEGRAL2(F) is the same as I = SUM2(F).\n%\n% See also CHEBFUN3/INTEGRAL, CHEBFUN3/INTEGRAL3, CHEBFUN3/SUM,\n% CHEBFUN3/SUM2 and CHEBFUN3/SUM3.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Developer Note: If F = F(x,y,z) is a CHEBFUN3 and \n% S = {(u,v)\\in DOM, s.t. x = x(u,v), y = y(u,v) and z = z(u,v)}, is a\n% parametric surface represented by a CHEBFUN2V object, then\n% \\int \\int_S F(x,y,z) dS = \\int \\int_DOM F(x(u,v), y(u,v), z(u,v))) ...\n% norm(cross(r_u, r_v)) dA.\n% Note that the domain of f should contain the range of S.\n% TODO: Check for this in the code.\n\n% Empty check:\nif ( isempty(f) ) \n I = [];\n return\nend\n\nif ( nargin == 1 )\n % Double definite integral:\n I = sum2(f);\n \n elseif ( nargin == 2 )\n if ( isa(S, 'chebfun2v') )\n % Integral over a parametric surface represented by a CHEBFUN2V.\n % Get the surface:\n S_compon = S.components;\n S1 = S_compon{1};\n S2 = S_compon{2};\n S3 = S_compon{3};\n \n % Surface integral:\n diffCu = diff(S, 1, 2); % Note the Chebfun2 convention to\n diffCv = diff(S, 1, 1); % use 2 for the 1st variable.\n ds = cross(diffCu, diffCv);\n op = @(u,v) feval(f, feval(S1, u, v), feval(S2, u, v), ...\n feval(S3, u, v));\n I = sum2(chebfun2(op, S1.domain).*ds);\n \n elseif ( isvector(S) && numel(S) == 2 )\n % Double definite integral over specified dimensions:\n I = sum2(f, S);\n end\nelse\n error('CHEBFUN:CHEBFUN3:integral2:nargin', ['Incorrect number of '...\n 'input arguments.']);\nend\n\nend\n\nfunction ds = cross(F, G)\nH = [F(2).*G(3) - F(3).*G(2); \n F(3).*G(1) - F(1).*G(3);\n F(1).*G(2) - F(2).*G(1)];\n% Developer note: In principle, here we should use\n% ds = sqrt(H(1).^2 + H(2).^2 + H(3).^2);\n% which uses chebfun2/sqrt. But, that code calls a singleSingTest\n% subroutine which sometimes gives error even in this case where the input\n% to sqrt is always nonnegative. We bypass that code by calling chebfun2\n% constructor as follows:\nds = chebfun2(@(u,v) sqrt(abs(feval(H(1),u,v).^2 + feval(H(2), u, v).^2 +...\n feval(H(3), u, v).^2)), H(1).domain);\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/integral2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7535398626613832}} {"text": "function chud_pi_test ( )\n\n%*****************************************************************************80\n%\n%% CHUD_PI_TEST tests the CHUD_PI function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n clear all\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHUD_PI_TEST\\n' );\n fprintf ( 1, ' CHUD_PI computes the value of pi using the \\n' );\n fprintf ( 1, ' Chudnovsky approach.\\n' );\n%\n% Get pi to 10, 20, 40, 80 decimal digits:\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Request PI to 10, 20, 40, 80 digits.\\n' );\n fprintf ( 1, '\\n' );\n%\n% Trying to print P out neatly using concatenation fails here,\n% although it works in AGM_PI_TEST. \n%\n% The procedure for printing out the D-digit representation of\n% a symbolic variable (if you are not willing to simply name\n% the variable and have its value plop out on the screen) is\n% not apparent to me!\n%\n d = 10;\n\n for i = 1 : 4\n\n p = chud_pi ( d );\n\n fprintf ( 1, ' Request %6d digits:', d );\n p\n d = d * 2;\n\n end\n%\n% Timings.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' How long does it take to compute PI to D digits?\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Digits Seconds\\n' );\n fprintf ( 1, '\\n' );\n d = 2;\n for i = 1 : 13\n tic\n p = chud_pi ( d );\n t = toc;\n fprintf ( 1, ' %2d %10d %14g\\n', i, d, t ); \n d = d * 2;\n end\n\n return\nend\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/vpa/chud_pi_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.7533038857054113}} {"text": "function a = cheby_t_inverse ( n )\n\n%*****************************************************************************80\n%\n%% CHEBY_T_INVERSE returns the inverse of the CHEBY_T matrix.\n%\n%\n% Example:\n%\n% N = 11\n%\n% 1 . . . . . . . . . .\n% . 1 . . . . . . . . .\n% 1 . 1 . . . . . . . . / 2\n% . 3 . 1 . . . . . . . / 4\n% 3 . 4 . 1 . . . . . . / 8\n% . 10 . 5 . 1 . . . . . / 16\n% 10 . 15 . 6 . 1 . . . . / 32\n% . 35 . 21 . 7 . 1 . . . / 64\n% 35 . 56 . 28 . 8 . 1 . . / 128\n% . 126 . 84 . 36 . 9 . 1 . / 256\n% 126 . 210 . 120 . 45 . 10 . 1 / 512\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 20007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n a(1,1) = 1.0;\n\n if ( n == 1 )\n return\n end\n\n a(2,2) = 1.0;\n\n if ( n == 2 )\n return\n end\n\n for i = 3 : n\n for j = 1 : n\n if ( j == 1 )\n a(i,j) = a(i-1,j+1) / 2.0;\n elseif ( j == 2 )\n a(i,j) = ( 2.0 * a(i-1,j-1) + a(i-1,j+1) ) / 2.0;\n elseif ( j < n )\n a(i,j) = ( a(i-1,j-1) + a(i-1,j+1) ) / 2.0;\n else\n a(i,j) = a(i-1,j-1) / 2.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/test_mat/cheby_t_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.7533038737048012}} {"text": "function value = r4_si ( x )\n\n%*****************************************************************************80\n%\n%% R4_SI evaluates the sine integral Si of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VASLUE, the sine integral Si evaluated at X.\n%\n persistent nsi\n persistent sics\n persistent xsml\n\n if ( isempty ( nsi ) )\n\n sics = [ ...\n -0.1315646598184841929, ...\n -0.2776578526973601892, ...\n 0.0354414054866659180, ...\n -0.0025631631447933978, ...\n 0.0001162365390497009, ...\n -0.0000035904327241606, ...\n 0.0000000802342123706, ...\n -0.0000000013562997693, ...\n 0.0000000000179440722, ...\n -0.0000000000001908387, ...\n 0.0000000000000016670, ...\n -0.0000000000000000122 ]';\n\n nsi = r4_inits ( sics, 12, 0.1 * r4_mach ( 3 ) );\n xsml = sqrt ( eps );\n\n end\n\n absx = abs ( x );\n\n if ( absx < xsml )\n\n value = x;\n\n elseif ( absx <= 4.0 )\n\n value = x * ( 0.75 + r4_csevl ( ( x * x - 8.0 ) * 0.125, sics, nsi ) );\n\n else\n\n [ f, g ] = r4_sifg ( absx );\n cosx = cos ( absx );\n\n if ( x < 0.0 )\n value = - 0.5 * pi + f * cosx + g * sin ( x );\n else\n value = 0.5 * pi - f * cosx - g * sin ( x );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_si.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.7533038618449202}} {"text": "function [ vX ] = ProxLogisticLossFunctionGd( vX, vY, vC, paramLambda, numIterations, stopThr )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = ProxLogisticLossFunction( vX, vY, vC, paramLambda, numIterations, stopThr )\n% Calculates the Prox of the Logistic Cost Function using Gradient Descent.\n% Input:\n% - vX - Input Vector.\n% Starting point for the iterative procedure.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vY - Input Vector.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vC - Model Vector.\n% The model vector in the Logsitic Cost Function.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - numIterations - Number of Iterations.\n% Sets the number of iterations for the algorithm to\n% run.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range {1, 2, ...}.\n% - stopTol - Stopping Condition Tolerance.\n% Sets the stopping threshold for the L Inf (Maximum\n% Absolute Value) of the change between 2 iterations\n% of the algorithm.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range [0, inf).\n% Output:\n% - vX - Output Vector.\n% The Prox for the logistic cost function for the\n% input vector 'vY'.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. https://math.stackexchange.com/a/3571521/33.\n% 2. Elementary Numerical Analysis MATH:3800/CS:3700(22M:072/22C:072)\n% (https://homepage.divms.uiowa.edu/~whan/3800.d/3800.html, Section 3.4).\n% Remarks:\n% 1. On some cases it fails to converge (While Newton Method converge to\n% the right solution).\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 06/03/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nvXPrev = vX;\nvG = zeros(size(vX, 1), 1);\n\nhObjFun = @(vX) 0.5 * sum((vX - vY) .^ 2) + (paramLambda * log(1 + exp(-vC.' * vX)));\nstepSizeMax = 2;\nsSolverOptions = optimset('fminbnd');\nsSolverOptions = optimset(sSolverOptions, 'Display', 'off');\n\nfor ii = 1: numIterations\n vXPrev(:) = vX;\n \n valExp = exp(-vC.' * vX);\n vG(:) = vX - vY - (paramLambda * (valExp / (1 + valExp)) * vC);\n \n hStepSizeFun = @(stepSize) hObjFun(vX - (stepSize * vG));\n stepSize = fminbnd(hStepSizeFun, 0, stepSizeMax, sSolverOptions);\n \n vX(:) = vX - (stepSize * vG);\n \n if(max(abs(vX - vXPrev)) < stopThr)\n break;\n end\nend\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q1683654/ProxLogisticLossFunctionGd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7532918515790501}} {"text": "function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin)\n% gridfit: estimates a surface on a 2d grid, based on scattered data\n% Replicates are allowed. All methods extrapolate to the grid\n% boundaries. Gridfit uses a modified ridge estimator to\n% generate the surface, where the bias is toward smoothness.\n% \n% Gridfit is not an interpolant. Its goal is a smooth surface\n% that approximates your data, but allows you to control the\n% amount of smoothing.\n%\n% usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes);\n% usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes);\n% usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...);\n%\n% Arguments: (input)\n% x,y,z - vectors of equal lengths, containing arbitrary scattered data\n% The only constraint on x and y is they cannot ALL fall on a\n% single line in the x-y plane. Replicate points will be treated\n% in a least squares sense.\n%\n% ANY points containing a NaN are ignored in the estimation\n%\n% xnodes - vector defining the nodes in the grid in the independent\n% variable (x). xnodes need not be equally spaced. xnodes\n% must completely span the data. If they do not, then the\n% 'extend' property is applied, adjusting the first and last\n% nodes to be extended as necessary. See below for a complete\n% description of the 'extend' property.\n%\n% If xnodes is a scalar integer, then it specifies the number\n% of equally spaced nodes between the min and max of the data.\n%\n% ynodes - vector defining the nodes in the grid in the independent\n% variable (y). ynodes need not be equally spaced.\n%\n% If ynodes is a scalar integer, then it specifies the number\n% of equally spaced nodes between the min and max of the data.\n%\n% Also see the extend property.\n%\n% Additional arguments follow in the form of property/value pairs.\n% Valid properties are:\n% 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter'\n% 'extend', 'tilesize', 'overlap'\n%\n% Any UNAMBIGUOUS shortening (even down to a single letter) is\n% valid for property names. All properties have default values,\n% chosen (I hope) to give a reasonable result out of the box.\n%\n% 'smoothness' - scalar or vector of length 2 - determines the\n% eventual smoothness of the estimated surface. A larger\n% value here means the surface will be smoother. Smoothness\n% must be a non-negative real number.\n%\n% If this parameter is a vector of length 2, then it defines\n% the relative smoothing to be associated with the x and y\n% variables. This allows the user to apply a different amount\n% of smoothing in the x dimension compared to the y dimension.\n%\n% Note: the problem is normalized in advance so that a\n% smoothness of 1 MAY generate reasonable results. If you\n% find the result is too smooth, then use a smaller value\n% for this parameter. Likewise, bumpy surfaces suggest use\n% of a larger value. (Sometimes, use of an iterative solver\n% with too small a limit on the maximum number of iterations\n% will result in non-convergence.)\n%\n% DEFAULT: 1\n%\n%\n% 'interp' - character, denotes the interpolation scheme used\n% to interpolate the data.\n%\n% DEFAULT: 'triangle'\n%\n% 'bilinear' - use bilinear interpolation within the grid\n% (also known as tensor product linear interpolation)\n%\n% 'triangle' - split each cell in the grid into a triangle,\n% then linear interpolation inside each triangle\n%\n% 'nearest' - nearest neighbor interpolation. This will\n% rarely be a good choice, but I included it\n% as an option for completeness.\n%\n%\n% 'regularizer' - character flag, denotes the regularization\n% paradignm to be used. There are currently three options.\n%\n% DEFAULT: 'gradient'\n%\n% 'diffusion' or 'laplacian' - uses a finite difference\n% approximation to the Laplacian operator (i.e, del^2).\n%\n% We can think of the surface as a plate, wherein the\n% bending rigidity of the plate is specified by the user\n% as a number relative to the importance of fidelity to\n% the data. A stiffer plate will result in a smoother\n% surface overall, but fit the data less well. I've\n% modeled a simple plate using the Laplacian, del^2. (A\n% projected enhancement is to do a better job with the\n% plate equations.)\n%\n% We can also view the regularizer as a diffusion problem,\n% where the relative thermal conductivity is supplied.\n% Here interpolation is seen as a problem of finding the\n% steady temperature profile in an object, given a set of\n% points held at a fixed temperature. Extrapolation will\n% be linear. Both paradigms are appropriate for a Laplacian\n% regularizer.\n%\n% 'gradient' - attempts to ensure the gradient is as smooth\n% as possible everywhere. Its subtly different from the\n% 'diffusion' option, in that here the directional\n% derivatives are biased to be smooth across cell\n% boundaries in the grid.\n%\n% The gradient option uncouples the terms in the Laplacian.\n% Think of it as two coupled PDEs instead of one PDE. Why\n% are they different at all? The terms in the Laplacian\n% can balance each other.\n%\n% 'springs' - uses a spring model connecting nodes to each\n% other, as well as connecting data points to the nodes\n% in the grid. This choice will cause any extrapolation\n% to be as constant as possible.\n%\n% Here the smoothing parameter is the relative stiffness\n% of the springs connecting the nodes to each other compared\n% to the stiffness of a spting connecting the lattice to\n% each data point. Since all springs have a rest length\n% (length at which the spring has zero potential energy)\n% of zero, any extrapolation will be minimized.\n%\n% Note: The 'springs' regularizer tends to drag the surface\n% towards the mean of all the data, so too large a smoothing\n% parameter may be a problem.\n%\n%\n% 'solver' - character flag - denotes the solver used for the\n% resulting linear system. Different solvers will have\n% different solution times depending upon the specific\n% problem to be solved. Up to a certain size grid, the\n% direct \\ solver will often be speedy, until memory\n% swaps causes problems.\n%\n% What solver should you use? Problems with a significant\n% amount of extrapolation should avoid lsqr. \\ may be\n% best numerically for small smoothnesss parameters and\n% high extents of extrapolation.\n%\n% Large numbers of points will slow down the direct\n% \\, but when applied to the normal equations, \\ can be\n% quite fast. Since the equations generated by these\n% methods will tend to be well conditioned, the normal\n% equations are not a bad choice of method to use. Beware\n% when a small smoothing parameter is used, since this will\n% make the equations less well conditioned.\n%\n% DEFAULT: 'normal'\n%\n% '\\' - uses matlab's backslash operator to solve the sparse\n% system. 'backslash' is an alternate name.\n%\n% 'symmlq' - uses matlab's iterative symmlq solver\n%\n% 'lsqr' - uses matlab's iterative lsqr solver\n%\n% 'normal' - uses \\ to solve the normal equations.\n%\n%\n% 'maxiter' - only applies to iterative solvers - defines the\n% maximum number of iterations for an iterative solver\n%\n% DEFAULT: min(10000,length(xnodes)*length(ynodes))\n%\n%\n% 'extend' - character flag - controls whether the first and last\n% nodes in each dimension are allowed to be adjusted to\n% bound the data, and whether the user will be warned if\n% this was deemed necessary to happen.\n%\n% DEFAULT: 'warning'\n%\n% 'warning' - Adjust the first and/or last node in\n% x or y if the nodes do not FULLY contain\n% the data. Issue a warning message to this\n% effect, telling the amount of adjustment\n% applied.\n%\n% 'never' - Issue an error message when the nodes do\n% not absolutely contain the data.\n%\n% 'always' - automatically adjust the first and last\n% nodes in each dimension if necessary.\n% No warning is given when this option is set.\n%\n%\n% 'tilesize' - grids which are simply too large to solve for\n% in one single estimation step can be built as a set\n% of tiles. For example, a 1000x1000 grid will require\n% the estimation of 1e6 unknowns. This is likely to\n% require more memory (and time) than you have available.\n% But if your data is dense enough, then you can model\n% it locally using smaller tiles of the grid.\n%\n% My recommendation for a reasonable tilesize is\n% roughly 100 to 200. Tiles of this size take only\n% a few seconds to solve normally, so the entire grid\n% can be modeled in a finite amount of time. The minimum\n% tilesize can never be less than 3, although even this\n% size tile is so small as to be ridiculous.\n%\n% If your data is so sparse than some tiles contain\n% insufficient data to model, then those tiles will\n% be left as NaNs.\n%\n% DEFAULT: inf\n%\n%\n% 'overlap' - Tiles in a grid have some overlap, so they\n% can minimize any problems along the edge of a tile.\n% In this overlapped region, the grid is built using a\n% bi-linear combination of the overlapping tiles.\n%\n% The overlap is specified as a fraction of the tile\n% size, so an overlap of 0.20 means there will be a 20%\n% overlap of successive tiles. I do allow a zero overlap,\n% but it must be no more than 1/2.\n%\n% 0 <= overlap <= 0.5\n%\n% Overlap is ignored if the tilesize is greater than the\n% number of nodes in both directions.\n%\n% DEFAULT: 0.20\n%\n%\n% 'autoscale' - Some data may have widely different scales on\n% the respective x and y axes. If this happens, then\n% the regularization may experience difficulties. \n% \n% autoscale = 'on' will cause gridfit to scale the x\n% and y node intervals to a unit length. This should\n% improve the regularization procedure. The scaling is\n% purely internal. \n%\n% autoscale = 'off' will disable automatic scaling\n%\n% DEFAULT: 'on'\n%\n%\n% Arguments: (output)\n% zgrid - (nx,ny) array containing the fitted surface\n%\n% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)\n%\n%\n% Speed considerations:\n% Remember that gridfit must solve a LARGE system of linear\n% equations. There will be as many unknowns as the total\n% number of nodes in the final lattice. While these equations\n% may be sparse, solving a system of 10000 equations may take\n% a second or so. Very large problems may benefit from the\n% iterative solvers or from tiling.\n%\n%\n% Example usage:\n%\n% x = rand(100,1);\n% y = rand(100,1);\n% z = exp(x+2*y);\n% xnodes = 0:.1:1;\n% ynodes = 0:.1:1;\n%\n% g = gridfit(x,y,z,xnodes,ynodes);\n%\n% Note: this is equivalent to the following call:\n%\n% g = gridfit(x,y,z,xnodes,ynodes, ...\n% 'smooth',1, ...\n% 'interp','triangle', ...\n% 'solver','normal', ...\n% 'regularizer','gradient', ...\n% 'extend','warning', ...\n% 'tilesize',inf);\n%\n%\n% Author: John D'Errico\n% e-mail address: woodchips@rochester.rr.com\n% Release: 2.0\n% Release date: 5/23/06\n\n% set defaults\nparams.smoothness = 1;\nparams.interp = 'triangle';\nparams.regularizer = 'gradient';\nparams.solver = 'backslash';\nparams.maxiter = [];\nparams.extend = 'warning';\nparams.tilesize = inf;\nparams.overlap = 0.20;\nparams.mask = []; \nparams.autoscale = 'on';\nparams.xscale = 1;\nparams.yscale = 1;\n\n% was the params struct supplied?\nif ~isempty(varargin)\n if isstruct(varargin{1})\n % params is only supplied if its a call from tiled_gridfit\n params = varargin{1};\n if length(varargin)>1\n % check for any overrides\n params = parse_pv_pairs(params,varargin{2:end});\n end\n else\n % check for any overrides of the defaults\n params = parse_pv_pairs(params,varargin);\n\n end\nend\n\n% check the parameters for acceptability\nparams = check_params(params);\n\n% ensure all of x,y,z,xnodes,ynodes are column vectors,\n% also drop any NaN data\nx=x(:);\ny=y(:);\nz=z(:);\nk = isnan(x) | isnan(y) | isnan(z);\nif any(k)\n x(k)=[];\n y(k)=[];\n z(k)=[];\nend\nxmin = min(x);\nxmax = max(x);\nymin = min(y);\nymax = max(y);\n\n% did they supply a scalar for the nodes?\nif length(xnodes)==1\n xnodes = linspace(xmin,xmax,xnodes)';\n xnodes(end) = xmax; % make sure it hits the max\nend\nif length(ynodes)==1\n ynodes = linspace(ymin,ymax,ynodes)';\n ynodes(end) = ymax; % make sure it hits the max\nend\n\nxnodes=xnodes(:);\nynodes=ynodes(:);\ndx = diff(xnodes);\ndy = diff(ynodes);\nnx = length(xnodes);\nny = length(ynodes);\nngrid = nx*ny;\n\n% set the scaling if autoscale was on\nif strcmpi(params.autoscale,'on')\n params.xscale = mean(dx);\n params.yscale = mean(dy);\n params.autoscale = 'off';\nend\n\n% check to see if any tiling is necessary\nif (params.tilesize < max(nx,ny))\n % split it into smaller tiles. compute zgrid and ygrid\n % at the very end if requested\n zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);\nelse\n % its a single tile.\n \n % mask must be either an empty array, or a boolean\n % aray of the same size as the final grid.\n nmask = size(params.mask);\n if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))\n if ((nmask(2)==ny) || (nmask(1)==nx))\n error 'Mask array is probably transposed from proper orientation.'\n else\n error 'Mask array must be the same size as the final grid.'\n end\n end\n if ~isempty(params.mask)\n params.maskflag = 1;\n else\n params.maskflag = 0;\n end\n\n % default for maxiter?\n if isempty(params.maxiter)\n params.maxiter = min(10000,nx*ny);\n end\n\n % check lengths of the data\n n = length(x);\n if (length(y)~=n) || (length(z)~=n)\n error 'Data vectors are incompatible in size.'\n end\n if n<3\n error 'Insufficient data for surface estimation.'\n end\n\n % verify the nodes are distinct\n if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)\n error 'xnodes and ynodes must be monotone increasing'\n end\n\n % do we need to tweak the first or last node in x or y?\n if xminxnodes(end)\n switch params.extend\n case 'always'\n xnodes(end) = xmax;\n case 'warning'\n warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])\n xnodes(end) = xmax;\n case 'never'\n error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])\n end\n end\n if yminynodes(end)\n switch params.extend\n case 'always'\n ynodes(end) = ymax;\n case 'warning'\n warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])\n ynodes(end) = ymax;\n case 'never'\n error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])\n end\n end\n \n % determine which cell in the array each point lies in\n [junk,indx] = histc(x,xnodes); %#ok\n [junk,indy] = histc(y,ynodes); %#ok\n % any point falling at the last node is taken to be\n % inside the last cell in x or y.\n k=(indx==nx);\n indx(k)=indx(k)-1;\n k=(indy==ny);\n indy(k)=indy(k)-1;\n ind = indy + ny*(indx-1);\n \n % Do we have a mask to apply?\n if params.maskflag\n % if we do, then we need to ensure that every\n % cell with at least one data point also has at\n % least all of its corners unmasked.\n params.mask(ind) = 1;\n params.mask(ind+1) = 1;\n params.mask(ind+ny) = 1;\n params.mask(ind+ny+1) = 1;\n end\n \n % interpolation equations for each point\n tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));\n ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));\n % Future enhancement: add cubic interpolant\n switch params.interp\n case 'triangle'\n % linear interpolation inside each triangle\n k = (tx > ty);\n L = ones(n,1);\n L(k) = ny;\n \n t1 = min(tx,ty);\n t2 = max(tx,ty);\n A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ...\n [1-t2,t1,t2-t1],n,ngrid);\n \n case 'nearest'\n % nearest neighbor interpolation in a cell\n k = round(1-ty) + round(1-tx)*ny;\n A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);\n \n case 'bilinear'\n % bilinear interpolation in a cell\n A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...\n [(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...\n n,ngrid);\n \n end\n rhs = z;\n \n % do we have relative smoothing parameters?\n if numel(params.smoothness) == 1\n % it was scalar, so treat both dimensions equally\n smoothparam = params.smoothness;\n xyRelativeStiffness = [1;1];\n else\n % It was a vector, so anisotropy reigns.\n % I've already checked that the vector was of length 2\n smoothparam = sqrt(prod(params.smoothness));\n xyRelativeStiffness = params.smoothness(:)./smoothparam;\n end\n \n % Build regularizer. Add del^4 regularizer one day.\n switch params.regularizer\n case 'springs'\n % zero \"rest length\" springs\n [i,j] = meshgrid(1:nx,1:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n m = nx*(ny-1);\n stiffness = 1./(dy/params.yscale);\n Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ...\n xyRelativeStiffness(2)*stiffness(j(:))*[-1 1], ...\n m,ngrid);\n \n [i,j] = meshgrid(1:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n m = (nx-1)*ny;\n stiffness = 1./(dx/params.xscale);\n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ...\n xyRelativeStiffness(1)*stiffness(i(:))*[-1 1],m,ngrid)];\n \n [i,j] = meshgrid(1:(nx-1),1:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n m = (nx-1)*(ny-1);\n stiffness = 1./sqrt((dx(i(:))/params.xscale/xyRelativeStiffness(1)).^2 + ...\n (dy(j(:))/params.yscale/xyRelativeStiffness(2)).^2);\n \n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ...\n stiffness*[-1 1],m,ngrid)];\n \n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ...\n stiffness*[-1 1],m,ngrid)];\n \n case {'diffusion' 'laplacian'}\n % thermal diffusion using Laplacian (del^2)\n [i,j] = meshgrid(1:nx,2:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n dy1 = dy(j(:)-1)/params.yscale;\n dy2 = dy(j(:))/params.yscale;\n \n Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...\n xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...\n 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);\n \n [i,j] = meshgrid(2:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n dx1 = dx(i(:)-1)/params.xscale;\n dx2 = dx(i(:))/params.xscale;\n \n Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...\n xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...\n 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid);\n \n case 'gradient'\n % Subtly different from the Laplacian. A point for future\n % enhancement is to do it better for the triangle interpolation\n % case.\n [i,j] = meshgrid(1:nx,2:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n dy1 = dy(j(:)-1)/params.yscale;\n dy2 = dy(j(:))/params.yscale;\n \n Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...\n xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...\n 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);\n \n [i,j] = meshgrid(2:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n dx1 = dx(i(:)-1)/params.xscale;\n dx2 = dx(i(:))/params.xscale;\n \n Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...\n xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...\n 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];\n \n end\n nreg = size(Areg,1);\n \n % Append the regularizer to the interpolation equations,\n % scaling the problem first. Use the 1-norm for speed.\n NA = norm(A,1);\n NR = norm(Areg,1);\n A = [A;Areg*(smoothparam*NA/NR)];\n rhs = [rhs;zeros(nreg,1)];\n % do we have a mask to apply?\n if params.maskflag\n unmasked = find(params.mask);\n end\n % solve the full system, with regularizer attached\n switch params.solver\n case {'\\' 'backslash'}\n if params.maskflag\n % there is a mask to use\n zgrid=nan(ny,nx);\n zgrid(unmasked) = A(:,unmasked)\\rhs;\n else\n % no mask\n zgrid = reshape(A\\rhs,ny,nx);\n end\n \n case 'normal'\n % The normal equations, solved with \\. Can be faster\n % for huge numbers of data points, but reasonably\n % sized grids. The regularizer makes A well conditioned\n % so the normal equations are not a terribly bad thing\n % here.\n if params.maskflag\n % there is a mask to use\n Aunmasked = A(:,unmasked);\n zgrid=nan(ny,nx);\n zgrid(unmasked) = (Aunmasked'*Aunmasked)\\(Aunmasked'*rhs);\n else\n zgrid = reshape((A'*A)\\(A'*rhs),ny,nx);\n end\n \n case 'symmlq'\n % iterative solver - symmlq - requires a symmetric matrix,\n % so use it to solve the normal equations. No preconditioner.\n tol = abs(max(z)-min(z))*1.e-13;\n if params.maskflag\n % there is a mask to use\n zgrid=nan(ny,nx);\n [zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...\n A(:,unmasked)'*rhs,tol,params.maxiter);\n else\n [zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);\n zgrid = reshape(zgrid,ny,nx);\n end\n % display a warning if convergence problems\n switch flag\n case 0\n % no problems with convergence\n case 1\n % SYMMLQ iterated MAXIT times but did not converge.\n warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ...\n ' iterations but did not converge.'])\n case 3\n % SYMMLQ stagnated, successive iterates were the same\n warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.')\n otherwise\n warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...\n ' symmlq was too small or too large to continue computing.'])\n end\n \n case 'lsqr'\n % iterative solver - lsqr. No preconditioner here.\n tol = abs(max(z)-min(z))*1.e-13;\n if params.maskflag\n % there is a mask to use\n zgrid=nan(ny,nx);\n [zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);\n else\n [zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);\n zgrid = reshape(zgrid,ny,nx);\n end\n \n % display a warning if convergence problems\n switch flag\n case 0\n % no problems with convergence\n case 1\n % lsqr iterated MAXIT times but did not converge.\n warning('GRIDFIT:solver',['Lsqr performed ', ...\n num2str(params.maxiter),' iterations but did not converge.'])\n case 3\n % lsqr stagnated, successive iterates were the same\n warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.')\n case 4\n warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...\n ' LSQR was too small or too large to continue computing.'])\n end\n \n end % switch params.solver\n \nend % if params.tilesize...\n\n% only generate xgrid and ygrid if requested.\nif nargout>1\n [xgrid,ygrid]=meshgrid(xnodes,ynodes);\nend\n\n% ============================================\n% End of main function - gridfit\n% ============================================\n\n% ============================================\n% subfunction - parse_pv_pairs\n% ============================================\nfunction params=parse_pv_pairs(params,pv_pairs)\n% parse_pv_pairs: parses sets of property value pairs, allows defaults\n% usage: params=parse_pv_pairs(default_params,pv_pairs)\n%\n% arguments: (input)\n% default_params - structure, with one field for every potential\n% property/value pair. Each field will contain the default\n% value for that property. If no default is supplied for a\n% given property, then that field must be empty.\n%\n% pv_array - cell array of property/value pairs.\n% Case is ignored when comparing properties to the list\n% of field names. Also, any unambiguous shortening of a\n% field/property name is allowed.\n%\n% arguments: (output)\n% params - parameter struct that reflects any updated property/value\n% pairs in the pv_array.\n%\n% Example usage:\n% First, set default values for the parameters. Assume we\n% have four parameters that we wish to use optionally in\n% the function examplefun.\n%\n% - 'viscosity', which will have a default value of 1\n% - 'volume', which will default to 1\n% - 'pie' - which will have default value 3.141592653589793\n% - 'description' - a text field, left empty by default\n%\n% The first argument to examplefun is one which will always be\n% supplied.\n%\n% function examplefun(dummyarg1,varargin)\n% params.Viscosity = 1;\n% params.Volume = 1;\n% params.Pie = 3.141592653589793\n%\n% params.Description = '';\n% params=parse_pv_pairs(params,varargin);\n% params\n%\n% Use examplefun, overriding the defaults for 'pie', 'viscosity'\n% and 'description'. The 'volume' parameter is left at its default.\n%\n% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')\n%\n% params = \n% Viscosity: 10\n% Volume: 1\n% Pie: 3\n% Description: 'Hello world'\n%\n% Note that capitalization was ignored, and the property 'viscosity'\n% was truncated as supplied. Also note that the order the pairs were\n% supplied was arbitrary.\n\nnpv = length(pv_pairs);\nn = npv/2;\n\nif n~=floor(n)\n error 'Property/value pairs must come in PAIRS.'\nend\nif n<=0\n % just return the defaults\n return\nend\n\nif ~isstruct(params)\n error 'No structure for defaults was supplied'\nend\n\n% there was at least one pv pair. process any supplied\npropnames = fieldnames(params);\nlpropnames = lower(propnames);\nfor i=1:n\n p_i = lower(pv_pairs{2*i-1});\n v_i = pv_pairs{2*i};\n \n ind = strmatch(p_i,lpropnames,'exact');\n if isempty(ind)\n ind = find(strncmp(p_i,lpropnames,length(p_i)));\n if isempty(ind)\n error(['No matching property found for: ',pv_pairs{2*i-1}])\n elseif length(ind)>1\n error(['Ambiguous property name: ',pv_pairs{2*i-1}])\n end\n end\n p_i = propnames{ind};\n \n % override the corresponding default in params\n params = setfield(params,p_i,v_i); %#ok\n \nend\n\n\n% ============================================\n% subfunction - check_params\n% ============================================\nfunction params = check_params(params)\n\n% check the parameters for acceptability\n% smoothness == 1 by default\nif isempty(params.smoothness)\n params.smoothness = 1;\nelse\n if (numel(params.smoothness)>2) || any(params.smoothness<=0)\n error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.'\n end\nend\n\n% regularizer - must be one of 4 options - the second and\n% third are actually synonyms.\nvalid = {'springs', 'diffusion', 'laplacian', 'gradient'};\nif isempty(params.regularizer)\n params.regularizer = 'diffusion';\nend\nind = find(strncmpi(params.regularizer,valid,length(params.regularizer)));\nif (length(ind)==1)\n params.regularizer = valid{ind};\nelse\n error(['Invalid regularization method: ',params.regularizer])\nend\n\n% interp must be one of:\n% 'bilinear', 'nearest', or 'triangle'\n% but accept any shortening thereof.\nvalid = {'bilinear', 'nearest', 'triangle'};\nif isempty(params.interp)\n params.interp = 'triangle';\nend\nind = find(strncmpi(params.interp,valid,length(params.interp)));\nif (length(ind)==1)\n params.interp = valid{ind};\nelse\n error(['Invalid interpolation method: ',params.interp])\nend\n\n% solver must be one of:\n% 'backslash', '\\', 'symmlq', 'lsqr', or 'normal'\n% but accept any shortening thereof.\nvalid = {'backslash', '\\', 'symmlq', 'lsqr', 'normal'};\nif isempty(params.solver)\n params.solver = '\\';\nend\nind = find(strncmpi(params.solver,valid,length(params.solver)));\nif (length(ind)==1)\n params.solver = valid{ind};\nelse\n error(['Invalid solver option: ',params.solver])\nend\n\n% extend must be one of:\n% 'never', 'warning', 'always'\n% but accept any shortening thereof.\nvalid = {'never', 'warning', 'always'};\nif isempty(params.extend)\n params.extend = 'warning';\nend\nind = find(strncmpi(params.extend,valid,length(params.extend)));\nif (length(ind)==1)\n params.extend = valid{ind};\nelse\n error(['Invalid extend option: ',params.extend])\nend\n\n% tilesize == inf by default\nif isempty(params.tilesize)\n params.tilesize = inf;\nelseif (length(params.tilesize)>1) || (params.tilesize<3)\n error 'Tilesize must be scalar and > 0.'\nend\n\n% overlap == 0.20 by default\nif isempty(params.overlap)\n params.overlap = 0.20;\nelseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)\n error 'Overlap must be scalar and 0 < overlap < 1.'\nend\n\n% ============================================\n% subfunction - tiled_gridfit\n% ============================================\nfunction zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)\n% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries \n% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)\n%\n% Tiled_gridfit is used when the total grid is far too large\n% to model using a single call to gridfit. While gridfit may take\n% only a second or so to build a 100x100 grid, a 2000x2000 grid\n% will probably not run at all due to memory problems.\n%\n% Tiles in the grid with insufficient data (<4 points) will be\n% filled with NaNs. Avoid use of too small tiles, especially\n% if your data has holes in it that may encompass an entire tile.\n%\n% A mask may also be applied, in which case tiled_gridfit will\n% subdivide the mask into tiles. Note that any boolean mask\n% provided is assumed to be the size of the complete grid.\n%\n% Tiled_gridfit may not be fast on huge grids, but it should run\n% as long as you use a reasonable tilesize. 8-)\n\n% Note that we have already verified all parameters in check_params\n\n% Matrix elements in a square tile\ntilesize = params.tilesize;\n% Size of overlap in terms of matrix elements. Overlaps\n% of purely zero cause problems, so force at least two\n% elements to overlap.\noverlap = max(2,floor(tilesize*params.overlap));\n\n% reset the tilesize for each particular tile to be inf, so\n% we will never see a recursive call to tiled_gridfit\nTparams = params;\nTparams.tilesize = inf;\n\nnx = length(xnodes);\nny = length(ynodes);\nzgrid = zeros(ny,nx);\n\n% linear ramp for the bilinear interpolation\nrampfun = inline('(t-t(1))/(t(end)-t(1))','t');\n\n% loop over each tile in the grid\nh = waitbar(0,'Relax and have a cup of JAVA. Its my treat.');\nwarncount = 0;\nxtind = 1:min(nx,tilesize);\nwhile ~isempty(xtind) && (xtind(1)<=nx)\n \n xinterp = ones(1,length(xtind));\n if (xtind(1) ~= 1)\n xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));\n end\n if (xtind(end) ~= nx)\n xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));\n end\n \n ytind = 1:min(ny,tilesize);\n while ~isempty(ytind) && (ytind(1)<=ny)\n % update the waitbar\n waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)\n \n yinterp = ones(length(ytind),1);\n if (ytind(1) ~= 1)\n yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));\n end\n if (ytind(end) ~= ny)\n yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));\n end\n \n % was a mask supplied?\n if ~isempty(params.mask)\n submask = params.mask(ytind,xtind);\n Tparams.mask = submask;\n end\n \n % extract data that lies in this grid tile\n k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...\n (y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));\n k = find(k);\n \n if length(k)<4\n if warncount == 0\n warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.')\n end\n warncount = warncount + 1;\n \n % fill this part of the grid with NaNs\n zgrid(ytind,xtind) = NaN;\n \n else\n % build this tile\n zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);\n \n % bilinear interpolation (using an outer product)\n interp_coef = yinterp*xinterp;\n \n % accumulate the tile into the complete grid\n zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;\n \n end\n \n % step to the next tile in y\n if ytind(end)=ny\n % extend this tile to the edge\n ytind = ytind(1):ny;\n end\n else\n ytind = ny+1;\n end\n \n end % while loop over y\n \n % step to the next tile in x\n if xtind(end)=nx\n % extend this tile to the edge\n xtind = xtind(1):nx;\n end\n else\n xtind = nx+1;\n end\n\nend % while loop over x\n\n% close down the waitbar\nclose(h)\n\nif warncount>0\n warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs'])\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/ThirdPartyToolbox/gridfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7532914928832852}} {"text": "%% Edge Element Discretization of Maxwell Equations\n% We test Maxwell solvers in iFEM.\n\nclear all; close all\nrowNames ={'h=1/2';'h=1/4';'h=1/8'};\ncolHeaders = {'H^curl Error','L^2 Error'};\n\n%% The data of the pde\n%\n% * pde = Maxwelldata1; % zero Neumann boundary condition and curl u = 0\n% * pde = Maxwelldata2; % non-homogenous Neumann boundary condition\n% * pde = Maxwelldata3; % polynomial data and curl u = 0\n% * pde = Maxwelldata4; % zero Dirichlet boundary condition\n% * pde = Maxwelldata5; % linear polynomial data\n% * pde = planewavedataC; % plane wave with complex coefficients\n% * pde = planewavedata1; % plane wave with real coefficients\n\n\n%% Positive Definite Case\n% curl curl E + E = f.\n\nhelp Maxwelldata2\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.25);\npde = Maxwelldata2;\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'cg';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\npde = Maxwelldata2;\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'cg';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned CG\n% converges around 20 steps. \n\n%% Indefinite with real coefficients\n% curl curl E - E = f.\n\nhelp planewavedata1\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\npde = planewavedata1;\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'cg';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\npde = planewavedata1;\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'cg';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned CG\n% converges around 40 steps although the system is indefinite.\n\n%% Indefinite: complex coefficients, real solution\n% curl curl E - (1-i)E = f.\n\nhelp planewavedataC\n%% \n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\npde = planewavedataC;\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'gmres';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\npde = planewavedataC;\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'gmres';\ncubeMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% Optimal first order of convergence is achieved. HX preconditioned GMRES\n% converges around 90 steps although the system is indefinite.\n%\n% Bug: For Neumann boundary condition, the rate of L2 error is not quite right.\n\n%% Indefinite: real coefficents, complex solution\nhelp planewavedata\n%%\n% Dirichlet boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\nbdFlag = setboundary3(node,elem,'Dirichlet');\noption.solver = 'cg';\nplanewaveMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%% \n% Neumann boundary condition\n[node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],1);\nbdFlag = setboundary3(node,elem,'Neumann');\noption.solver = 'cg';\nplanewaveMaxwell2;\n%%\nmakeHtmlTable([energyErr L2Err],[],rowNames,colHeaders);\n\n%%\n% The computation of error can't handle complex functions. So in\n% planewaveMaxwell the error between uI and uh is computed. Therefore\n% slightly better rate of convergence is observed. The rate of L2 error is\n% almost second order.", "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/Maxwell2testdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879432, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7532830087967118}} {"text": "function f = goldstein_price ( x )\n\n%*****************************************************************************80\n%\n%% GOLDSTEIN_PRICE evaluates the Goldstein-Price polynomial.\n%\n% Discussion:\n%\n% The minimizer is\n%\n% X* = [ 0.0, -1.0 ]\n% F(X*) = 3.0\n%\n% Suggested starting point:\n%\n% X init = [ -0.5, 0.25 ] (easy convergence)\n% X init = [ -4.0, 5.00 ] (harder convergence)\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% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, real X(2), the argument of the function.\n%\n% Output, real F, the value of the function at X.\n%\n if ( length ( x ) ~= 2 )\n error ( 'Error: function expects a two dimensional input\\n' );\n end\n\n a = x(1) + x(2) + 1.0;\n\n b = 19.0 - 14.0 * x(1) + 3.0 * x(1) * x(1) - 14.0 * x(2) ...\n + 6.0 * x(1) * x(2) + 3.0 * x(2) * x(2);\n\n c = 2.0 * x(1) - 3.0 * x(2);\n\n d = 18.0 - 32.0 * x(1) + 12.0 * x(1) * x(1) + 48.0 * x(2) ...\n - 36.0 * x(1) * x(2) + 27.0 * x(2) * x(2);\n\n f = ( 1.0 + a * a * b ) * ( 30.0 + c * c * d );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/nelder_mead/goldstein_price.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7532617378599693}} {"text": "function gnss = gnss_m2r (lat, h, gnss)\n% gnss_m2r: converts GPS standard deviation from meters to radians.\n%\n% INPUT\n% gnss, GNSS data structure with fields: \n% lat, 1x1 latitude (radians).\n% h, 1x1 altitude (meters).\n% stdm, 1x3 position error profile (m, m, m).\n%\n% OUTPUT\n% gnss.std, 1x3 position error profile (rad, rad, m).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved. \n% \n% This file is part of NaveGo, an open-source MATLAB toolbox for \n% simulation of integrated navigation systems.\n% \n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL) \n% version 3 as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Lesser General Public \n% License along with this program. If not, see \n% .\n%\n% References: \n%\n% R. Gonzalez, J. Giribet, and H. Patiño. NaveGo: a \n% simulation framework for low-cost integrated navigation systems, \n% Journal of Control Engineering and Applied Informatics, vol. 17, \n% issue 2, pp. 110-120, 2015. Eq. 20.\n%\n% \tR. Gonzalez, J. Giribet, and H. Patiño. An approach to \n% benchmarking of loosely coupled low-cost navigation systems, \n% Mathematical and Computer Modelling of Dynamical Systems, vol. 21, \n% issue 3, pp. 272-287, 2015. Eq. 7.\n%\n% Version: 003\n% Date: 2021/03/09\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego \n\ngnss.std = zeros(1,3);\n\n[RM, RN] = radius(lat);\n\ngnss.std(1) = gnss.stdm(1) / (RM + h); \ngnss.std(2) = gnss.stdm(2) / (RN + h) / cos (lat); \ngnss.std(3) = gnss.stdm(3);\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/conversions/gnss_m2r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856561, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7532567108192829}} {"text": "function [ o, x, w ] = epn_glg_02_xiu ( n, alpha )\n\n%*****************************************************************************80\n%\n%% EPN_GLG_02_XIU implements the Xiu rule for region EPN_GLG.\n%\n% Discussion:\n%\n% The rule has order\n%\n% O = N + 1.\n%\n% The rule has precision P = 2.\n%\n% EPN_GLG is the N-dimensional positive space [0,+oo)^N with generalized\n% Laguerre weight function:\n%\n% w(alpha;x) = product ( 1 <= i <= n ) x(i)^alpha exp ( - x(i) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dongbin Xiu,\n% Numerical integration formulas of degree two,\n% Applied Numerical Mathematics,\n% Volume 58, 2008, pages 1515-1520.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, real ALPHA, the exponent of X in the weight function.\n% -1.0 < ALPHA.\n%\n% Input, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EPN_GLG_02_XIU - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'EPN_GLG_02_XIU - Fatal error!' );\n end\n\n o = n + 1;\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n for j = 1 : o\n\n i = 0;\n for r = 1 : floor ( n / 2 )\n arg = 2 * r * ( j - 1 ) * pi / ( n + 1 );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * cos ( arg );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * sin ( arg );\n end\n\n if ( i < n )\n i = i + 1;\n x(i,j) = r8_mop ( j - 1 );\n end\n\n end\n\n gamma0 = - 1.0;\n delta0 = alpha + 1.0;\n c1 = - alpha - 1.0;\n\n x(1:n,1:o) = ( sqrt ( gamma0 * c1 ) * x(1:n,1:o) - delta0 ) / gamma0;\n\n expon = 0;\n volume_1d = ep1_glg_monomial_integral ( expon, alpha );\n volume = volume_1d ^ n;\n\n w(1:o) = volume / o;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/epn_glg_02_xiu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856561, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7532567090438708}} {"text": "function [pt degen] = line_intersect(p1, p2, p3, p4)\n% function pt = line_intersect(p1, p2, p3, p4)\n% intersection point of line defined by p1 & p2 and line defined by p3 & p4\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/\nx1 = p1(1); y1 = p1(2);\nx2 = p2(1); y2 = p2(2);\nx3 = p3(1); y3 = p3(2);\nx4 = p4(1); y4 = p4(2);\n\nif (y4-y3)*(x2-x1)-(x4-x3)*(y2-y1) == 0\n% \twarning('line_intersect.m degenerate --dclee');\n% \tpt = (p1 + p2 + p3 + p4)/4;\n pt = [];\n degen = 1;\n\treturn;\nend\n\npt = [ ...\n\tx1 + (x2-x1) * ((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/((y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)) ...\n\ty1 + (y2-y1) * ((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/((y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)) ];\ndegen = 0;\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/geometry/line_intersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7532475324022838}} {"text": "function [ x, seed ] = disk01_sample ( n, seed )\n\n%*****************************************************************************80\n%\n%% DISK01_SAMPLE uniformly samples the unit disk.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% 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 x = randn ( 2, n );\n norm = ones ( 1, 2 ) * ( x.^2 );\n norm = sqrt ( norm );\n for i = 1 : 2\n x(i,1:n) = x(i,1:n) ./ norm(1:n);\n end\n\n for j = 1 : n\n r = rand ( 1, 1 );\n x(1:2,j) = sqrt ( r ) * x(1:2,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/disk_integrals/disk01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7532153606727531}} {"text": "function geometry_test061 ( )\n\n%*****************************************************************************80\n%\n%% TEST061 tests PLANE_NORMAL_BASIS_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n test_num = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST061\\n' );\n fprintf ( 1, ' PLANE_NORMAL_BASIS_3D, given a plane in\\n' );\n fprintf ( 1, ' point, normal form (P,N), finds two unit\\n' );\n fprintf ( 1, ' vectors Q and R that \"lie\" in the plane\\n' );\n fprintf ( 1, ' and are mutually orthogonal.\\n' );\n\n for test = 1 : test_num\n\n [ pp(1:3,1), seed ] = r8vec_uniform_01 ( 3, seed );\n\n [ normal(1:3,1), seed ] = r8vec_uniform_01 ( 3, seed );\n t = norm ( normal );\n normal = normal / t;\n\n [ pq, pr ] = plane_normal_basis_3d ( pp, normal );\n\n if ( test == 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Data for test 1:\\n' );\n fprintf ( 1, '\\n' );\n r8vec_print ( 3, pp, ' Point PP:' );\n r8vec_print ( 3, normal, ' Normal vector N:' );\n r8vec_print ( 3, pq, ' Vector PQ:' );\n r8vec_print ( 3, pr, ' Vector PR:' );\n end\n\n b(1,1) = normal(1:3,1)' * normal(1:3,1);\n b(1,2) = normal(1:3,1)' * pq(1:3,1);\n b(1,3) = normal(1:3,1)' * pr(1:3,1);\n\n b(2,1) = pq(1:3,1)' * normal(1:3,1);\n b(2,2) = pq(1:3,1)' * pq(1:3,1);\n b(2,3) = pq(1:3,1)' * pr(1:3,1);\n\n b(3,1) = pr(1:3,1)' * normal(1:3,1);\n b(3,2) = pr(1:3,1)' * pq(1:3,1);\n b(3,3) = pr(1:3,1)' * pr(1:3,1);\n\n r8mat_print ( 3, 3, b, ' Dot product matrix:' );\n\n end\n\n return\nend\n", "meta": {"author": "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_test061.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7531886408054759}} {"text": "function mbasis = basis_matrix_overhauser_uni_r ( )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_OVERHAUSER_UNI_R sets up the right uniform Overhauser spline basis matrix.\n%\n% Discussion:\n%\n% This basis matrix assumes that the data points P(N-2), P(N-1),\n% and P(N) are uniformly spaced in T, and that P(N-1) corresponds to\n% T = 0, and P(N) to T = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real MBASIS(3,3), the basis matrix.\n%\n mbasis(1,1) = 2.0;\n mbasis(1,2) = - 4.0;\n mbasis(1,3) = 2.0;\n\n mbasis(2,1) = - 3.0;\n mbasis(2,2) = 4.0;\n mbasis(2,3) = - 1.0;\n\n mbasis(3,1) = 1.0;\n mbasis(3,2) = 0.0;\n mbasis(3,3) = 0.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/basis_matrix_overhauser_uni_r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7531886345204291}} {"text": "function [f] = psin(n,z)\n%Psin Arbitrary order Polygamma function valid in the entire complex plane.\n%\n% d^(n+1)\n% polygamma(n,z) = --------log(Gamma(z))\n% dz^(n+1)\n%\n%usage: [f] = Psin(n,z)\n%\n% if n is 0 or absent then f will be the Digamma function.\n% if n=1,2,3,4,5 etc then f will be\n% the tri-, tetra-, penta-, hexa-, hepta- etc gamma functon\n% Real(n) must be zero or positive.\n%\n%tested under versions 6.0 and 5.3.1\n%\n% Z may be complex and of any size.\n%\n% This program uses the partial fraction expansion of the\n% derivative of the Log of an excellent Lanczos series approximation\n% for the Gamma function. Accurate to about 12 digits.\n%\n%example: psin(101, -45.6-i*29.4)\n% is near 12.5 + 9*i\n%\n%example: psin(10, -11.5-i*0.577007813568142)\n% is near a root of the decagamma function\n%\n%example: x=[1:0.005:1.250]'; [x gamma(x) log(gamma(x)) psin(0,x) psin(1,x)]\n% recreates Table 6.1 page 267 from A&S\n%\n%example: x=[1:0.01:2.00]'; [x psin(2,x) psin(3,x)]\n% recreates Table 6.2 page 271 from A&S\n%\n%example: x=1; y=[0:0.1:10]'; f=psin(0,x+i*y); [y real(f) imag(f)] \n% recreates Table 6.8 page 288 from A&S\n%\n%example: x=2; y=[0:0.1:10]'; f=psin(0,x+i*y); [y real(f) imag(f)] \n% recreates the last part of Table 6.8 page 293 from A&S\n% \n%References: C. Lanczos, SIAM JNA 1, 1964. pp. 86-96\n% Y. Luke, \"The Special ... approximations\", 1969 pp. 29-31\n% Y. Luke, \"Algorithms ... functions\", 1977\n% J. Spouge, SIAM JNA 31, 1994. pp. 931\n% W. Press, \"Numerical Recipes\"\n% S. Chang, \"Computation of special functions\", 1996\n%\n%\n%see also: GAMMA GAMMALN GAMMAINC\n%see also: mhelp psi\n%see also: mhelp GAMMA\n\n%Paul Godfrey\n%pgodfrey@conexant.com\n%July 22, 2004\n%see gamma for calculation details...\n\n%this routine still works even if n is complex with real(n)>=0\n%don't know what the resulting function is called though\n\n% we have bit of a problem for real(z)<0\n% we could use the reflection formula, eq #6.4.7 in A&S\n% but arbitrary order derivs of cot are cumberson to compute\n% (it generates a polynomial in powers of cot)\n% so instead we will use a modification of eq #6.4.6\n% and call this program recursively to shift z by 500 until real(z)>=0\n\n\nif nargin==1\n z=n;\n n=0;\nend\n\nif n==0\n f=psi(z);\n return\nend\n\nif real(n)<0\n error('Invalid Polygamma order')\nend\n\nsizeofz=size(z);\n\nisneg=find(real(z)< 0);\nisok =find(real(z)>=0);\n\nnegmethod=1;\nif ~isempty(isneg)\n if negmethod==0\n zneg=z(isneg);\n gneg=psin(n,zneg+1); % recurse if to far to the left...\n hneg=-(-1).^n.*gamma(n+1).*zneg.^-(n+1);\n fneg=gneg+hneg;\n else\n zneg=z(isneg);\n %shift by, say, 500, to speed things up.\n m=500;\n gneg=psin(n,zneg+m);\n hneg=0;\n for k=m-1:-1:0\n hneg=hneg+(zneg+k).^-(n+1);\n end\n hneg=-(-1).^n.*gamma(n+1).*hneg;\n fneg=gneg+hneg;\n end\nend\nif ~isempty(isok)\n z=z(isok);\nend\n\n% the zeros of the Lanczos PFE series when g=607/128 are:\n\nr=[ -4.1614709798720630-.14578107125196249*i;\n -4.1614709798720630+.14578107125196249*i;\n -4.3851935502539474-.19149326909941256*i;\n -4.3851935502539474+.19149326909941256*i;\n -4.0914355423005926;\n -5.0205261882982271;\n -5.9957952053472399;\n -7.0024851819328395;\n -7.9981186370233868;\n -9.0013449037361806;\n -9.9992157162305535;\n -11.0003314815563886;\n -11.9999115102434217;\n -13.0000110489923175587];\n\n% the poles of the Lanczos PFE series are:\n%p=[ 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13];\n\ne=exp(1); \ng=607/128; % best results when 4<=g<=5\nh=1/2;\n\n%compute tricky PFE expansion of the deriv of the log\n%of the Lanczos series. The series Lanczos' coeffs manifest\n%themselves in the zero locations. The residues are all +/- 1\n%compare this to A&S page 259, eq# 6.3.16 and page 260, eq# 6.4.10\n\ns=0;\nfor k=length(r)-1:-1:0\n s=s+(1./((z-r(k+1)).^(n+1))-1./((z+k).^(n+1)));\nend\n%what happens if n is not a positive integer?\ns=(-1).^n.*gamma(n+1).*s;\n\nzgh=z+(g-h);\nif n==0\n% s=log(zgh)+(-g./zgh + s);\n% use existing more accurate digamma function if n=0\n% should never reach this code since we trapped it above \n f=psi(z);\n return\nelse\n% do derivs of front end stuff\n s=(-1)^(n+1)*(gamma(n).*zgh.^(-n) + g*gamma(n+1).*zgh.^-(n+1))+s;\nend\n\nif ~isempty(isneg)\n f(isneg)=fneg;\nend\nif ~isempty(isok)\n f(isok)=s;\nend\n\nf=reshape(f,sizeofz);\n\nreturn\n\n%a demo of this program is\n\nwarning off\nx=[-5:1/64:5]';\n\nfigure(1)\naxis([min(x) max(x) -20 20])\ngrid on\nhold on\n\ny=[];\nfor n=0:6\n y(:,n+1)=psin(n,x);\nend\n\nplot(repmat(x,1,size(y,2)),y)\n\n\nfigure(2)\nx=-10:1/16:10;\ny=-5:1/16:5;\n[X,Y]=meshgrid(x,y);\nz=complex(X,Y);\nf=psin(4,z);\ng=log10(abs(f));\nmesh(x,y,g)\nrotate3d on\n\nz=-76+54*i;\n[z psin(98, z)]\n\ndisp('A zero of Psin1')\nz = -0.412134547951937-i*0.597811942320597;\n[z psin(1,z)]\n\nwarning on\nreturn\n\n% Include this complex psi function\n% in case user doesn't have one\n\nfunction [f] = psi(z)\n%Psi Psi (or Digamma) function valid in the entire complex plane.\n%\n% d\n% Psi(z) = --log(Gamma(z))\n% dz\n%\n%usage: [f] = psi(z)\n%\n%tested under versions 6.0 and 5.3.1\n%\n% Z may be complex and of any size.\n%\n% This program uses the analytical derivative of the\n% Log of an excellent Lanczos series approximation\n% for the Gamma function.\n% \n%References: C. Lanczos, SIAM JNA 1, 1964. pp. 86-96\n% Y. Luke, \"The Special ... approximations\", 1969 pp. 29-31\n% Y. Luke, \"Algorithms ... functions\", 1977\n% J. Spouge, SIAM JNA 31, 1994. pp. 931\n% W. Press, \"Numerical Recipes\"\n% S. Chang, \"Computation of special functions\", 1996\n%\n%\n%see also: GAMMA GAMMALN GAMMAINC\n%see also: mhelp psi\n%see also: mhelp GAMMA\n\n%Paul Godfrey\n%pgodfrey@intersil.com\n%July 13, 2001\n%see gamma for calculation details...\n\nsiz = size(z);\nz=z(:);\nzz=z;\n\nf = 0.*z; % reserve space in advance\n\n%reflection point\np=find(real(z)<0.5);\nif ~isempty(p)\n z(p)=1-z(p);\nend\n\n%Lanczos approximation for the complex plane\n \ng=607/128; % best results when 4<=g<=5\n \nc = [ 0.99999999999999709182;\n 57.156235665862923517;\n -59.597960355475491248;\n 14.136097974741747174;\n -0.49191381609762019978;\n .33994649984811888699e-4;\n .46523628927048575665e-4;\n -.98374475304879564677e-4;\n .15808870322491248884e-3;\n -.21026444172410488319e-3;\n .21743961811521264320e-3;\n -.16431810653676389022e-3;\n .84418223983852743293e-4;\n -.26190838401581408670e-4;\n .36899182659531622704e-5];\n\n\nn=0;\nd=0;\nfor k=size(c,1):-1:2\n dz=1./(z+k-2);\n dd=c(k).*dz;\n d=d+dd;\n n=n-dd.*dz;\nend\nd=d+c(1);\ngg=z+g-0.5;\n%log is accurate to about 13 digits...\n\nf = log(gg) + (n./d - g./gg) ;\n\nif ~isempty(p)\n f(p) = f(p)-pi*cot(pi*zz(p));\nend\n\np=find(round(zz)==zz & real(zz)<=0 & imag(zz)==0);\nif ~isempty(p)\n f(p) = Inf;\nend\n\nf=reshape(f,siz);\n\nreturn\n\n%A demo of this routine is:\nclc\nclear all\nclose all\nx=-4:1/16:4.5;\ny=-4:1/16:4;\n[X,Y]=meshgrid(x,y);\nz=X+i*Y;\nf=psi(z);\np=find(abs(f)>10);\nf(p)=10;\n\nmesh(x,y,abs(f),phase(f));\nview([45 10]);\nrotate3d;\n\nfigure(2);\nezplot psi;\ngrid on;\n\nOne=psi(2)-psi(1)\nEulerGamma=-psi(1)\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/978-special-functions-math-library/psin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7531886265781914}} {"text": "%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NACA airfoil generator\n% coded by Manuel Diaz, NTU, 2015.04.27\n%\n% Refs:\n% [1] Geometry for Aerodynamicists, Appendix A. Accessible online at:\n% http://www.dept.aoe.vt.edu/~mason/Mason_f/CAtxtAppA.pdf \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclose all;\n \n%-------------------------------------------------------------------------% \n% Define all the parameters \n%-------------------------------------------------------------------------% \n \nNa = 50;\nM = 30;\nA = 10; %Clustering points near leading edge, inf = no clustering\nB = 2; %Clustering points near the surface, 1 = no clustering\nt = .12;\nc = 1;\nL = 1;\nN = floor(2*c/(2*c+L)*Na);\nx1 = c*ones(1,N+1);\ny1 = zeros(1,N+1);\nx2 = x1;\ny2 = y1;\ny2(1) = c;\ns1 = y1;\ns2 = s1;\nN2 = 250;\n\n%-------------------------------------------------------------------------% \n% Solve Algebraic Method\n%-------------------------------------------------------------------------%\nfor i = 2:N2+1\n x1(i) = c*(1-(i-1)/N2);\n y1(i) = max([t/.2*(.2969*x1(i)^.5-.126*x1(i)-.3516*x1(i)^2+.2843*x1(i)^3-.1015*x1(i)^4) 0]);\n s1(i) = s1(i-1)+sqrt((x1(i)-x1(i-1))^2+(y1(i)-y1(i-1))^2);\n x2(i) = c*(1-2*(i-1)/N2);\n if x2(i) >= 0;\n y2(i) = c;\n else\n y2(i) = sqrt(c^2-(x2(i))^2);\n end\n s2(i) = s2(i-1)+sqrt((x2(i)-x2(i-1))^2+(y2(i)-y2(i-1))^2);\nend\nS1 = s1(end)*(1-exp(-(0:N)/A))/(1-exp(-(N)/A));\nS1(end)/s1(end)\nS2 = (0:N)*s2(end)/N;\nfor i = 1:N+1\n X1(i) = interp1(s1,x1,S1(i));\n Y1(i) = interp1(s1,y1,S1(i));\n X2(i) = interp1(s2,x2,S2(i));\n Y2(i) = interp1(s2,y2,S2(i));\nend\nr = exp(((1:(M+1))-M+1)/((M+1)/B));\nr = r-r(1);\nr = r/max(r);\nfor i = 1:N+1\n for j = 1:M+1\n x(i,j) = X1(i) + r(j)*(X2(i)-X1(i));\n y(i,j) = Y1(i) + r(j)*(Y2(i)-Y1(i));\n end\nend\nN = Na-N;\nx = [((L+c):-L/N:(c+L/N))'*ones(1,M+1); x];\ny = [(c*r'*ones(1,N))'; y];\nx = [x; x(end-1:-1:1,:)];\ny = [y ;-y(end-1:-1:1,:)];\n[n,m] = size(x);\n\n%-------------------------------------------------------------------------% \n% Plot Algebraic Method\n%-------------------------------------------------------------------------%\nmesh(x,y,zeros(n,m))\nview(0,90)\ncolormap([0 0 0])\naxis('equal','tight');\nxlabel('Length [unitless]','FontSize',14);\nylabel('Length [unitless]','FontSize',14);\ntitle('Algebraic Method ','FontSize',18);\n\n%-------------------------------------------------------------------------% \n% Predetermined Constants\n%-------------------------------------------------------------------------%\nde = 1/M;\nde2 = de^2;\ndn = 1/Na;\ndn2 = dn^2;\ndedn = 2/(M*Na);\nP = 100; %number of iterations for the elliptic solver.\n\n%-------------------------------------------------------------------------% \n% Solve Elliptic Method\n%-------------------------------------------------------------------------%\n \nfor k = 1:P\n for i = 2:2*Na-1\n for j = 2:M-1\n xn = (x(i+1,j)-x(i-1,j))/(2*dn);\n yn = (y(i+1,j)-y(i-1,j))/(2*dn);\n xe = (x(i,j+1)-x(i,j-1))/(2*de);\n ye = (y(i,j+1)-y(i,j-1))/(2*de);\n a(i,j) = xn^2+yn^2;\n b(i,j) = xe*xn+ye*yn;\n c(i,j) = xe^2+ye^2;\n end\n end\n for i = 2:2*Na-1\n for j = 2:M-1\n x(i,j) = (a(i,j)/de2*(x(i+1,j)+x(i-1,j))+c(i,j)/dn2*(x(i,j+1)+x(i,j-1))...\n -b(i,j)/dedn*(x(i+1,j+1)-x(i+1,j-1)+x(i-1,j-1)-x(i-1,j+1)))...\n /(2*(a(i,j)/de2+c(i,j)/dn2));\n y(i,j) = (a(i,j)/de2*(y(i+1,j)+y(i-1,j))+c(i,j)/dn2*(y(i,j+1)+y(i,j-1))...\n -b(i,j)/dedn*(y(i+1,j+1)-y(i+1,j-1)+y(i-1,j-1)-y(i-1,j+1)))...\n /(2*(a(i,j)/de2+c(i,j)/dn2));\n end\n end\nend\nxn = ones(Na,M)/0;\nyn = xn;\nxe = xn;\nye = xn;\nfor i = 2:Na-1\n for j = 2:M-1\n xn(i,j) = (x(i+1,j)-x(i-1,j))/(2*dn);\n yn(i,j) = (y(i+1,j)-y(i-1,j))/(2*dn);\n xe(i,j) = (x(i,j+1)-x(i,j-1))/(2*de);\n ye(i,j) = (y(i,j+1)-y(i,j-1))/(2*de);\n J(i,j) = yn(i,j)*xe(i,j)-xn(i,j)*ye(i,j); % Jacobian\n end\nend\nfigure(2)\nmesh(x,y,zeros(n,m))\nxlabel('Length [unitless]','FontSize',14);\nylabel('Length [unitless]','FontSize',14);\ntitle('Elliptic Method ','FontSize',18);\naxis('equal','tight');\n\n%-------------------------------------------------------------------------% \n% Plot Elliptic Method\n%-------------------------------------------------------------------------%\n \nview(0,90)\ncolormap([0 0 0])\n\n%-------------------------------------------------------------------------% \n% Plot Jacobian\n%-------------------------------------------------------------------------%\n \nfigure(3)\nx=2:30; y=2:50; [X,Y]=meshgrid(x,y);\nsurf(X,Y,J);\nview(-45,45)\ntitle('Jacobian ','FontSize',18);\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/NACAairfoil/NACAAirfoilMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7531884233673183}} {"text": "function r=geodistance(ci,cf,m)\n\n%GEODISTANCE: Calculates the distance in meters between two points on earth surface.\n%\n% Usage: r = geodistance( coordinates1 , coordinates2 , method ) ; \n% \n%\t Where coordinates1 = [longitude1,latitude1] defines the\n%\t initial position and coordinates2 = [longitude2,latitude2]\n%\t defines the final position.\n%\t Coordinates values should be specified in decimal degrees.\n%\t Method can be an integer between 1 and 23, default is m = 6. \n% Methods 1 and 2 are based on spherical trigonometry and a \n% spheroidal model for the earth, respectively. \n%\t Methods 3 to 24 use Vincenty's formulae, based on ellipsoid \n% parameters. \n% Here it follows the correspondence between m and the type of \n% ellipsoid:\n%\n% m = 3 -> ANS , m = 4 -> GRS80, m = 5 -> WGS72, \n% m = 6 -> WGS84, m = 7 -> NSWC-9Z2, \n% m = 8 -> Clarke 1866, m = 9 -> Clarke 1880,\n% m = 10 -> Airy 1830,\n% m = 11 -> Bessel 1841 (Ethiopia,Indonesia,Japan,Korea),\n% m = 12 -> Bessel 1841 (Namibia),\n% m = 13 -> Sabah and Sarawak (Everest,Brunei,E.Malaysia),\n% m = 14 -> India 1830, m = 15 -> India 1956, \n% m = 16 -> W. Malaysia and Singapore 1948, \n% m = 17 -> W. Malaysia 1969, \n% m = 18 -> Helmert 1906, m = 19 -> Helmert 1960,\n% m = 20 -> Hayford International 1924, \n% m = 21 -> Hough 1960, m = 22 -> Krassovsky 1940,\n% m = 23 -> Modified Fischer 1960, \n% m = 24 -> South American 1969. \n%\n%\t Important notes:\n%\n%\t 1)South latitudes are negative.\n%\t 2)East longitudes are positive.\n%\t 3)Great circle distance is the shortest distance between two points \n% on a sphere. This coincides with the circumference of a circle which \n% passes through both points and the centre of the sphere.\n%\t 4)Geodesic distance is the shortest distance between two points on a spheroid.\n%\t 5)Normal section distance is formed by a plane on a spheroid containing a \n% point at one end of the line and the normal of the point at the other end. \n% For all practical purposes, the difference between a normal section and a \n% geodesic distance is insignificant.\n%\t 6)The method m=2 assumes a spheroidal model for the earth with an average \n% radius of 6364.963 km. It has been derived for use within Australia. \n% The formula is estimated to have an accuracy of about 200 metres over 50 km, \n% but may deteriorate with longer distances. \n% However, it is not symmetric when the points are exchanged. \n% \n% Examples: A = [150 -30]; B = [150 -31]; L = [151 -80];\n% [geodistance(A,B,1) geodistance(A,B,2) geodistance(A,B,3)]\n% [geodistance(A,L,1) geodistance(A,L,2) geodistance(A,L,3)]\n% geodistance([0 0],[2 3])\n% geodistance([2 3],[0 0])\n% geodistance([0 0],[2 3],1)\n% geodistance([2 3],[0 0],1)\n% geodistance([0 0],[2 3],2)\n% geodistance([2 3],[0 0],2)\n% for m = 1:24\n% r(m) = geodistance([150 -30],[151 -80],m);\n% end\n% plot([1:m],r), box on, grid on\n%\n%***************************************************************************************\n% Second version: 07/11/2007\n% Third version: 03/08/2010\n% \n% Contact: orodrig@ualg.pt\n% \n% Any suggestions to improve the performance of this \n% code will be greatly appreciated. \n% \n% Reference: Geodetic Calculations Methods\n% Geoscience Australia\n% (http://www.ga.gov.au/geodesy/calcs/)\n%\n%***************************************************************************************\n% Changed a little bit by Mao,\n% So, it works in vector computaiton now.\n%\n% Contact: argansos@hotmail.com\n% Ganquan Mao, 15/09/2011\n%\n%***************************************************************************************\n\nif size(ci,2)~=2 || size(cf,2)~=2\n error('ci cf must be a n*2 matrix!')\nend\n\nif size(ci,1)~=size(cf,1)\n error('ci cf must have same size!')\nend\n\nr=[];%for convergence\n\nif nargin==2\n m=6;\nend \n\nlambda1=ci(:,1)*pi/180; \n phi1=ci(:,2)*pi/180;\n\nlambda2=cf(:,1)*pi/180; \n phi2=cf(:,2)*pi/180; \n\nL=lambda2-lambda1;\n\nif m==1%great circle distance, based on spherical trigonometry\n r=180*1.852*60*acos(sin(phi1).*sin(phi2)...\n +cos(phi1).*cos(phi2).*cos(lambda2-lambda1))./pi;\n r=1000*abs(r);\n\nelseif m==2%spheroidal model for the earth\n term1=111.08956*(ci(:,2)-cf(:,2)+0.000001);\n term2=cos(phi1+((phi2-phi1)/2));\n term3=(cf(:,1)-ci(:,1)+0.000001)/(cf(:,2)-ci(:,2)+0.000001);\n r=1000*abs(term1./cos(atan(term2.*term3)));\n\nelse%apply Vincenty's formulae (as long as the points are not coincident)\n alla=[0,0,6378160,6378137,6378135,6378137,6378145,6378206.4,...\n 6378249.145,6377563.396,6377397.155,6377483.865,6377298.556,...\n 6377276.345,6377301.243,6377304.063,6377295.664,6378200,...\n 6378270,6378388,6378270,6378245,6378155,6378160];\n\n allf=[0,0,1/298.25,1/298.257222101,1/298.26,1/298.257223563,...\n 1/298.25,1/294.9786982,1/293.465,1/299.3249646,1/299.1528128,...\n 1/299.1528128,1/300.8017,1/300.8017,1/300.8017,1/300.8017,...\n 1/300.8017,1/298.3,1/297,1/297,1/297,1/298.3,1/298.3,1/298.25];\n\n a=alla(m);\n f=allf(m);\n\n b=a*(1-f);\n\n axa=a^2;\n bxb=b^2;\n\n U1=atan((1-f)*tan(phi1));\n U2=atan((1-f)*tan(phi2));\n\n lambda=L;\n lambda_old=sqrt(-1);%there is no way a complex number is going to coincide with a real number!\n\n ntrials=0;%just in case...\n\n while any(abs(lambda-lambda_old)>1e-9)\n \n ntrials=ntrials+1;\n\n lambda_old=lambda;\n sin_sigma=sqrt((cos(U2).*sin(lambda)).^2+(cos(U1).*sin(U2)...\n -sin(U1).*cos(U2).*cos(lambda)).^2);\n cos_sigma=sin(U1).*sin(U2)+cos(U1).*cos(U2).*cos(lambda);\n sigma=atan2(sin_sigma,cos_sigma);\t\t \t\n sin_alpha=cos(U1).*cos(U2).*sin(lambda)./sin_sigma;\n cos2_alpha=1-sin_alpha.^2;\n cos_2sigmam=cos_sigma-2*sin(U1).*sin(U2)./cos2_alpha;\n\n C=(f/16)*cos2_alpha.*(4+f*(4-3*cos2_alpha));\n\n lambda=L+f*(1-C).*sin_alpha.*(sigma+C.*sin_sigma.*(cos_2sigmam...\n +C.*cos_sigma.*(-1+2*(cos_2sigmam).^2)));\n\n % stop the function if convergence is not achieved\n if ntrials>1000\n disp('Convergence failure...')\n return\n end\n\n end\n\n % convergence achieved? get the distance\n uxu=cos2_alpha*(axa-bxb)/bxb;\n A=1+(uxu/16384).*(4096+uxu.*(-768+uxu.*(320-175*uxu)));\n B=(uxu/1024).*(256+uxu.*(-128+uxu.*(74-47*uxu)));\n delta_sigma=B.*sin_sigma.*(cos_2sigmam+(B/4).*(cos_sigma.*(-1+...\n 2*cos_2sigmam.^2)-(B/6).*cos_2sigmam.*(-3+...\n 4*sin_sigma.^2).*(-3+4*cos_2sigmam.^2)));\n r=b*A.*(sigma-delta_sigma);\n\nend\n\nr(isnan(r))=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/thirdParty/geodDistance/geodistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7531884211077987}} {"text": "function circle_segment_test08 ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_TEST08 tests CIRCLE_SEGMENT_CONTAINS_POINT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n n = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_TEST08\\n' );\n fprintf ( 1, ' CIRCLE_SEGMENT_CONTAINS_POINT reports whether\\n' );\n fprintf ( 1, ' a circle segment contains a point.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Pick a circle segment at random.\\n' );\n fprintf ( 1, ' Compute %d sample points in the surrounding box.\\n', n );\n fprintf ( 1, ' Compare the area of the segment to the percentage of points\\n' );\n fprintf ( 1, ' contained in the circle segment.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Omega1 Omega2 Area Estimate\\n' );\n fprintf ( 1, '\\n' );\n\n r = 1.0;\n c = [ 0.0; 0.0 ];\n\n for test = 1 : 5\n\n [ u1, seed ] = r8_uniform_01 ( seed );\n [ u2, seed ] = r8_uniform_01 ( seed );\n omega1 = 2.0 * pi * u1;\n omega2 = 2.0 * pi * u2;\n \n if ( omega2 < omega1 )\n omega2 = omega2 + 2.0 * pi;\n end\n\n [ xy, seed ] = r8mat_uniform_01 ( 2, n, seed );\n xy = 2.0 * xy - 1.0;\n\n inout = zeros ( n, 1 );\n for j = 1 : n\n inout(j) = circle_segment_contains_point ( r, c, omega1, omega2, xy(1:2,j) );\n end\n\n theta = circle_segment_angle_from_chord_angles ( omega1, omega2 );\n area = circle_segment_area_from_angle ( r, theta );\n area_est = 4.0 * sum ( inout(1:n) ) / n;\n\n fprintf ( 1, ' %6d %14g %14g %14g %14g\\n', n, omega1, omega2, area, area_est );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/circle_segment_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7531774147105824}} {"text": "function aList=genAllBinCombinations(n,t,algorithm)\n%%GENALLBINARYCOMBINATIONS Generate all combinations of t items chosen from\n% a set of n items, presenting the results as binary strings.\n%\n%INPUTS: n The number of items from which t items are chosen .\n% t The number of items chosen, t<=n.\n% algorithm An optional parameter affecting which algorithm is used (and\n% thus the ordering of the codes). Possible values are:\n% 0 (The default if omitted or an empty matrix is passed). Use\n% Algorithm C in Chapter 7.2.1.3 of [1]. The combinations are\n% given in the order of Chase's sequence.\n% 1 Use Algorithm 2 in [2]. The combinations are given as a gray\n% code. Consecutive combinations differ in only 2 bits.\n%\n%OUTPUTS: aList An nXnumCombos list of all of the binary strings of n bits\n% choosing t of them to be 1. \n%\n%There is a total of numCombos=binomial(n,t) combinations.\n%\n%EXAMPLE:\n% aList0=genAllBinCombinations(4,2,0)\n% aList1=genAllBinCombinations(4,2,1)\n%One will find that\n% aList0=[0, 1, 0, 0, 1, 1;\n% 0, 0, 1, 1, 0, 1;\n% 1, 0, 0, 1, 1, 0;\n% 1, 1, 1, 0, 0, 0];\n% aList1=[1, 0, 1, 0, 0, 1;\n% 1, 1, 0, 0, 1, 0;\n% 0, 1, 1, 1, 0, 0;\n% 0, 0, 0, 1, 1, 1];\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%[2] J. R. Bitner, G. Ehrlich, and E. M. Reingold, \"Efficient generation of\n% the binary reflected gray code and its applications,\" Communications\n% of the ACM, vol. 19, no. 9, pp. 517-521, Sep. 1976.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(algorithm))\n algorithm=0;\nend\n\nswitch(algorithm)\n case 0\n aList=genAllBinCombinationsKnuth(n,t);\n case 1\n aList=genAllBinCombinationsGray(n,t);\n otherwise\n error('Unknown algorithm specified.')\nend\n\nend\n\nfunction aList=genAllBinCombinationsKnuth(n,t)\n%%GENALLBINARYCOMBINATIONS Generate all combinations of t items chosen from\n% a set of n items, presenting the results as binary strings.\n%\n%INPUTS: n The number of items from which t items are chosen.\n% t The number of items chosen, t<=n.\n%\n%OUTPUTS: aList An nXnumCombos list of all of the binary strings of n bits\n% choosing t of them to be 1. \n%\n%There is a total of numCombos=binomial(n,t) combinations. Algorithm C in\n%Chapter 7.2.1.3 of [1] is used to generate the strings in the order of\n%Chase's sequence.\n%\n%EXAMPLE:\n% aList=genAllBinCombinations(4,2)\n%One will find that\n% aList=[0,1,0,0,1,1;\n% 0,0,1,1,0,1;\n% 1,0,0,1,1,0;\n% 1,1,1,0,0,0];\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(t==n)\n aList=ones(n,1);\n return\nelseif(t==0)\n aList=zeros(n,1);\n return\nend\n\ns=n-t;\n\nnumCombos=binomial(n,t);\naList=zeros(n,numCombos);\n\n%Step C1. a and w are indexed from 0 in [1].\na=[zeros(s,1);ones(t,1)];%\nw=ones(n+1,1);\nr=s;\n\nfor curCombo=1:numCombos\n %Step C1\n aList(:,curCombo)=a;\n \n %Step C3\n j=r;\n while(w(j+1)==0)\n w(j+1)=1;\n j=j+1;\n if(j==n)\n return;\n end\n end\n \n w(j+1)=0;\n if(mod(j,2)==1)%j is odd\n if(a(j+1)~=0)\n %Step C4 \n a(j-1+1)=1;\n a(j+1)=0;\n if(r==j&&j>1)\n r=j-1;\n elseif(r==j-1)\n r=j;\n end\n else\n %Step C7\n if(a(j-1+1)~=0)\n %Step C6\n a(j+1)=1;\n a(j-1+1)=0;\n if(r==j&&j>1)\n r=j-1;\n elseif(r==j-1)\n r=j;\n end\n else\n a(j+1)=1;\n a(j-2+1)=0;\n if(r==j-2)\n r=j;\n elseif(r==j-1)\n r=j-2;\n end\n end\n end\n else%j is even\n if(a(j+1)~=0)\n %Step C5\n if(a(j-2+1)~=0)\n %Step C4\n a(j-1+1)=1;\n a(j+1)=0;\n if(r==j&&j>1)\n r=j-1;\n elseif(r==j-1)\n r=j;\n end\n else\n a(j-2+1)=1;\n a(j+1)=0;\n if(r==j)\n r=max(j-2,1); \n elseif(r==j-2)\n r=j-1;\n end\n end\n else\n %Step C6\n a(j+1)=1;\n a(j-1+1)=0;\n if(r==j&&j>1)\n r=j-1;\n elseif(r==j-1)\n r=j;\n end\n end\n end\n\nend\n\nend\n\nfunction theCodes=genAllBinCombinationsGray(n,k)\n%%GENALLBINCOMBINATIONSGRAY Generate all combinations of k items chosen\n% from a set of n items, presenting the results as binary\n% strings. Subsequent combinations differ by 2 bits.\n%\n%INPUTS: n The number of items from which k items are chosen.\n% t The number of items chosen, t<=n.\n%\n%OUTPUTS: aList An nXnumCombos list of all of the binary strings of n bits\n% choosing k of them to be 1. \n%\n%There is a total of numCombos=binomial(n,t) combinations. Algorithm 2 in\n%[1] is used to generate all combinations are a gray code. Subsequent\n%combinations differ in only 2 bits.\n%\n%REFERENCES:\n%[1] J. R. Bitner, G. Ehrlich, and E. M. Reingold, \"Efficient generation of\n% the binary reflected gray code and its applications,\" Communications\n% of the ACM, vol. 19, no. 9, pp. 517-521, Sep. 1976.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(k==0)\n theCodes=zeros(n,1);\n return;\nend\n\nnumCodes=binomial(n,k);\ntheCodes=zeros(n,numCodes);\n\ng=[ones(k,1);zeros(n-k+2,1)];\ntau=2:(n+2);\nt=k;\ntau(1)=k+1;\ni=0;\n\ncurGrayCode=1;\nwhile(i tol\n warning('DualQuaternion:dquat2rot:wrongFormat',...\n 'At least one dual quaternion is not a rotation dual quaternion (tol = %.1e).\\n Indices of max values: %d \\n Max value = %.2e',...\n tol,imax,maxval);\nend\nnormDQ = sqrt(sum(dq(1:4,:).^2));\n[maxval2,imax2] = max(abs(normDQ-1));\nif maxval2 > tol \n warning('DualQuaternion:dquat2rot:wrongFormatForRotation',...\n 'At least one dual quaternion is not a rotation dual quaternion (is it a rotation dual quaternion?) (tol = %.1e).\\n Indices of max values: %d \\n Max value = %.2e',...\n tol,imax2,maxval2);\nend\n\nindpos = find(dq(1,:) > 1);\ndq(1,indpos) = ones(1,length(indpos));\nindneg = find(dq(1,:) < -1);\ndq(1,indneg) = ones(1,length(indneg));\n\n% Extraction of the rotation parameters\ntheta = 2*acosd(dq(1,:)); % acosd: [-1,1] --> [0,180]\ntheta = mod(theta,360);\nindthetaOK = find(theta > 0);\naxis = [ones(1,n) ; zeros(2,n)];\nif length(indthetaOK > 0)\n repsin = repmat(sind(theta(indthetaOK)/2),3,1);\n axis(:,indthetaOK) = dq(2:4,indthetaOK)./repsin;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/dquat2rot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.753137662380576}} {"text": "function area = trimeshSurfaceArea(v, e, f)\n%TRIMESHSURFACEAREA Surface area of a triangular mesh.\n%\n% S = trimeshSurfaceArea(V, F)\n% S = trimeshSurfaceArea(V, E, F)\n% Computes the surface area of the mesh specified by vertex array V and\n% face array F. Vertex array is a NV-by-3 array of coordinates. \n% Face array is a NF-by-3, containing vertex indices of each face.\n%\n% Example\n% % Compute area of an octahedron (equal to 2*sqrt(3)*a*a, with \n% % a = sqrt(2) in this case)\n% [v f] = createOctahedron;\n% trimeshSurfaceArea(v, f)\n% ans = \n% 6.9282\n%\n% % triangulate a compute area of a unit cube\n% [v f] = createCube;\n% f2 = triangulateFaces(f);\n% trimeshSurfaceArea(v, f2)\n% ans =\n% 6\n%\n% See also\n% meshes3d, meshSurfaceArea, trimeshMeanBreadth, triangulateFaces\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-08-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% check input number\nif nargin == 2\n f = e;\nend\n\n% compute two direction vectors, using first vertex of each face as origin\nv1 = v(f(:, 2), :) - v(f(:, 1), :);\nv2 = v(f(:, 3), :) - v(f(:, 1), :);\n\n% area of each triangle is half the cross product norm\nvn = vectorNorm3d(crossProduct3d(v1, v2));\n\n% sum up and normalize\narea = sum(vn) / 2;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/trimeshSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7531220291427932}} {"text": "function cube_plots ( )\n\n%*****************************************************************************80\n%\n%% CUBE_PLOTS plots the surface and the R(Theta) function for a cube.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CUBE_PLOTS:\\n' );\n fprintf ( 1, ' For a 3D cube defined by a 0/1 characteristic function,\\n' );\n fprintf ( 1, ' plot the surface, and R(Theta),\\n' );\n fprintf ( 1, ' using a centered point, and then an offcentered point.\\n' );\n%\n% 1): Plot the surface, using a centered base point.\n%\n n1 = 31;\n n2 = 61;\n theta1 = linspace ( 0.0, pi, n1 );\n theta2 = linspace ( 0.0, 2.0 * pi, n2 );\n\n [ t1, t2 ] = meshgrid ( theta2, theta1 );\n r = zeros ( n1, n2 );\n\n x0 = [ 0.0, 0.0, 0.0 ];\n for i = 1 : n1\n for j = 1 : n2 \n r(i,j) = bisect_characteristic ( x0, [ t1(i,j); t2(i,j) ], @cube_characteristic );\n end\n end\n\n x1 = r .* cos ( t1 );\n x2 = r .* sin ( t1 ) .* cos ( t2 );\n x3 = r .* sin ( t1 ) .* sin ( t2 );\n\n figure ( 1 )\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 filename = 'cube_centered_surface.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 2): Plot R as a function of Theta for a centered base point.\n%\n figure ( 2 )\n mesh ( t1, t2, r, 'FaceColor', 'Interp' );\n axis ( [0, 2.0 * pi, 0.0, pi, 0.0, 1.5 ] ); \n xlabel ( '<---Theta2--->', 'FontSize', 16 )\n ylabel ( '<---Theta1--->', 'FontSize', 16 );\n zlabel ( '<---R(Theta1,Theta2)--->', 'FontSize', 16 )\n title ( 'R(*,*) from base point to surface', 'FontSize', 24 )\n grid on\n filename = 'cube_centered_plot.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 3): Plot the surface, using an offcentered base point.\n%\n n1 = 31;\n n2 = 61;\n theta1 = linspace ( 0.0, pi, n1 );\n theta2 = linspace ( 0.0, 2.0 * pi, n2 );\n\n [ t1, t2 ] = meshgrid ( theta2, theta1 );\n r = zeros ( n1, n2 );\n\n x0 = [ +0.7, -0.2, -0.5 ];\n for i = 1 : n1\n for j = 1 : n2 \n r(i,j) = bisect_characteristic ( x0, [ t1(i,j); t2(i,j) ], @cube_characteristic );\n end\n end\n\n x1 = r .* cos ( t1 );\n x2 = r .* sin ( t1 ) .* cos ( t2 );\n x3 = r .* sin ( t1 ) .* sin ( t2 );\n\n figure ( 3 )\n c = zeros ( n1, n2 );\n colormap ( 'gray' )\n mesh ( x3, x2, x1, c );\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 filename = 'cube_offcentered_surface.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 4): Plot R as a function of Theta for an offcentered base point.\n%\n figure ( 4 )\n mesh ( t1, t2, r, 'FaceColor', 'Interp' );\n xlabel ( '<---Theta2--->', 'FontSize', 16 )\n ylabel ( '<---Theta1--->', 'FontSize', 16 );\n zlabel ( '<---R(Theta1,Theta2)--->', 'FontSize', 16 )\n title ( 'R(*,*) from base point to surface', 'FontSize', 24 )\n grid on\n filename = 'cube_offcentered_plot.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Note variation in R for the offcenter case:\\n' );\n fprintf ( 1, ' Min R = %g\\n', min ( min ( r ) ) );\n fprintf ( 1, ' Max R = %g\\n', max ( max ( r ) ) );\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hypersphere_surface/cube_plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7531220163867456}} {"text": "function [model, llh] = hmmEm(x, init)\n% EM algorithm to fit the parameters of HMM model (a.k.a Baum-Welch algorithm)\n% Input:\n% x: 1 x n integer vector which is the sequence of observations\n% init: model or k\n% Output:s\n% model: trained model structure\n% llh: loglikelihood\n% Written by Mo Chen (sth4nth@gmail.com).\nn = size(x,2);\nX = sparse(x,1:n,1);\nd = size(X,1);\nif isstruct(init) % init with a model\n A = init.A;\n E = init.E;\n s = init.s;\nelseif numel(init) == 1 % random init with latent k\n k = init;\n s = normalize(rand(k,1),1); \n A = normalize(rand(k,k),2);\n E = normalize(rand(k,d),2);\nend\ntol = 1e-4;\nmaxIter = 1000;\nllh = -inf(1,maxIter);\nfor iter = 2:maxIter\n M = E*X;\n% E-step\n [gamma,alpha,beta,c] = hmmSmoother(M,A,s);\n llh(iter) = mean(log(c));\n if abs(llh(iter)-llh(iter-1)) < tol*abs(llh(iter-1)); break; end % check likelihood for convergence\n% M-step \n s = gamma(:,1); % 13.18\n A = normalize(A.*(alpha(:,1:n-1)*(beta(:,2:n).*M(:,2:n)./c(2:n))'),2); % 13.19 13.43 13.65\n E = (gamma*X')./sum(gamma,2); % 13.23\nend\nmodel.s = s;\nmodel.A = A;\nmodel.E = E;\nllh = llh(2:iter);\n\nfunction [gamma, alpha, beta, c] = hmmSmoother(M, A, s)\n[K,T] = size(M);\nAt = A';\nc = zeros(1,T);\nalpha = zeros(K,T);\n[alpha(:,1),c(1)] = normalize(s.*M(:,1),1);\nfor t = 2:T\n [alpha(:,t),c(t)] = normalize((At*alpha(:,t-1)).*M(:,t),1); % 13.59\nend\nbeta = ones(K,T);\nfor t = T-1:-1:1\n beta(:,t) = A*(beta(:,t+1).*M(:,t+1))/c(t+1); % 13.62\nend\ngamma = alpha.*beta; % 13.64\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter13/HMM/hmmEm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7531220150610265}} {"text": "function fx = p43_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P43_FUN evaluates the integrand for problem 43.\n%\n% Discussion:\n%\n% The problem has a parameter ALPHA that can be set by calling\n% P43_PARAM_SET.\n%\n% The suggested parameter range is 0.1 <= ALPHA <= 2.0.\n%\n% The integrand has an algebraic endpoint singularity at X = 1\n% times a singular factor.\n%\n% Interval:\n%\n% 0 <= x <= 1\n%\n% Integrand:\n%\n% ( ln ( 1 / x ) )^( alpha - 1 )\n%\n% Exact Integral:\n%\n% Gamma(alpha)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Piessens, Elise de Doncker-Kapenga,\n% Christian Ueberhuber, David Kahaner,\n% QUADPACK: A Subroutine Package for Automatic Integration,\n% Springer, 1983, page 84.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n alpha = p43_param_get ( );\n\n fx(1:n) = ( log ( 1.0 ./ x(1:n) ) ).^( alpha - 1.0 );\n\n i = find ( x == 0.0 | x == 1.0 );\n fx(i) = 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_int/p43_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7530509329809185}} {"text": "function A=vech2Mat(theVec,isSymmetric,offDiagScalFact)\n%%VECH2MAT Given the main diagonal and lower-triangular elements of a\n% matrix stacked column-wise, obtain the original\n% symmetric or lower-triangular matrix. This function is\n% essentially the inverse of the vech function when applied to a\n% symmetric or lower-triangular matrix with the proper\n% parameterization.\n%\n%INPUTS: theVect An nX1 or 1Xn vector holding the diagonal and\n% lower-triangular components of a symmetric matrix stacked\n% column-wise.\n% isSymmetric An optional boolean parameter specifying whether the\n% matrix being recreated is symmetric. If false, a lower-\n% triangular matrix is formed. The default if this parameter\n% is omitted or an empty matrix is passed is true.\n% offDiagScalFact An optional scalar factor by which the off-diagonal\n% elements are scaled. If this parameter is omitted or an\n% empty matrix is passed, then the default value of 1 is\n% used.\n%\n%OUTPUTS: A The matrix impled by theVec and isSymmetric. This is a dXd\n% matrix, where n=d*(d+1)/2.\n%\n%The opposite of this function is vech.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(offDiagScalFact))\n offDiagScalFact=1;\nend\n\nif(nargin<2||isempty(isSymmetric))\n isSymmetric=true; \nend\n\nn=length(theVec);\ntheVec=theVec(:);\n\nd=(1/2)*(-1+sqrt(1+8*n));\nA=zeros(d,d);\n\ncurStart=1;\nif(isSymmetric)\n for curCol=1:d\n %The diagonal element\n A(curCol,curCol)=theVec(curStart);\n span=(curStart+1):(curStart+d-curCol);\n \n %The lower-triangular part\n A((curCol+1):end,curCol)=theVec(span)*offDiagScalFact;\n %The upper triangular part.\n A(curCol,(curCol+1):end)=theVec(span)'*offDiagScalFact;\n curStart=curStart+d-curCol+1;\n end\nelse\n for curCol=1:d\n %The diagonal element\n A(curCol,curCol)=theVec(curStart);\n span=(curStart+1):(curStart+d-curCol);\n \n %The lower-triangular part\n A((curCol+1):end,curCol)=theVec(span)*offDiagScalFact;\n\n %The upper-triangular part is just zero.\n curStart=curStart+d-curCol+1;\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/vech2Mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.7530509247841992}} {"text": "function varargout = createCube()\n%CREATECUBE Create a 3D mesh representing the unit cube\n%\n% [V, E, F] = createCube \n% Create a unit cube, as a polyhedra representation.\n% c has the form [V E F], where V is a 8-by-3 array with vertices\n% coordinates, E is a 12-by-2 array containing indices of neighbour\n% vertices, and F is a 6-by-4 array containing vertices array of each\n% face.\n%\n% [V, F] = createCube;\n% Returns only the vertices and the face vertex indices.\n%\n% MESH = createCube;\n% Returns the data as a mesh structure, with fields 'vertices', 'edges'\n% and 'faces'.\n%\n% Example\n% [n, e, f] = createCube;\n% drawMesh(n, f);\n% \n% See also\n% meshes3d, drawMesh\n% createOctahedron, createTetrahedron, createDodecahedron\n% createIcosahedron, createCubeOctahedron\n%\n\n% ---------\n% author : David Legland \n% e-mail: david.legland@inra.fr\n% INRA - TPV URPOI - BIA IMASTE\n% created the 10/02/2005.\n\n\n% HISTORY\n% 04/01/2007: remove unused variables\n\nx0 = 0; dx= 1;\ny0 = 0; dy= 1;\nz0 = 0; dz= 1;\n\nnodes = [...\n x0 y0 z0; ...\n x0+dx y0 z0; ...\n x0 y0+dy z0; ...\n x0+dx y0+dy z0; ...\n x0 y0 z0+dz; ...\n x0+dx y0 z0+dz; ...\n x0 y0+dy z0+dz; ...\n x0+dx y0+dy z0+dz];\n\nedges = [1 2;1 3;1 5;2 4;2 6;3 4;3 7;4 8;5 6;5 7;6 8;7 8];\n\n% faces are oriented such that normals point outwards\nfaces = [1 3 4 2;5 6 8 7;2 4 8 6;1 5 7 3;1 2 6 5;3 7 8 4];\n\n% format output\nvarargout = formatMeshOutput(nargout, nodes, edges, faces);\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/createCube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8615382023207901, "lm_q1q2_score": 0.7530509242213812}} {"text": "function Y = sym_sne(X, d, perplexity)\n%SNE Implementation of symmetric Stochastic Neighbor Embedding\n%\n% mappedX = sym_sne(X, no_dims, perplexity)\n%\n% Runs the symmetric Stochastic Neighbor Embedding algorithm. The \n% high-dimensional datapoints are specified by X. The target dimensionality\n% is specified in no_dims (default = 2), and the perplexity of the Gaussian\n% kernel is specified in perplexity (default = 30). \n% The function returns the embedded points in mappedX.\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\n if ~exist('d', 'var') || isempty(d)\n d = 2;\n end\n if ~exist('perplexity', 'var') || isempty(perplexity)\n perplexity = 30;\n end\n\n % Initialize some variables\n n = size(X, 1); % number of instances\n eta = .05; % learning rate\n max_iter = 2000; % maximum number of iterations\n jitter = 0.3; % initial jitter\n jitter_decay = 0.99; % jitter decay\n momentum = 0.5; % initial momentum\n final_momentum = 0.8; % final momentum\n mom_switch_iter = 750; % iteration where momentum changes\n \n % Initialize embedding coordinates randomly (close to origin)\n Y = 0.0001 * rand(n, d);\n dC = zeros(n, d);\n y_incs = zeros(n, d);\n \n % Compute Gaussian kernel for high-dimensional data representation\n P = x2p(X, perplexity, 1e-5); % use fixed perplexity\n P = P + P';\n P = P ./ sum(P(:));\n P = max(P, eps);\n \n % Iterating loop\n for iter=1:max_iter\n\n % Compute Gaussian kernel for low-dimensional data representation\n sum_Y = sum(Y .^ 2, 2); % precomputation for pairwise distances\n Q = exp(-bsxfun(@plus, sum_Y, bsxfun(@plus, sum_Y', -2 * Y * Y')) ./ 2); % Gaussian probabilities\n Q = Q ./ repmat(sum(Q, 2), [1 n]);\n Q = max(Q, eps);\n \n % Compute cost function between P and Q\n if ~rem(iter, 20)\n costs = sum(P .* log((P + eps) ./ (Q + eps)), 2) ./ n; % division by n corrects for # of datapoints\n cost = sum(costs);\n disp(['Iteration ' num2str(iter) ': error is ' num2str(cost)]);\n end\n \n % Compute gradient\n PQ = P - Q;\n for i=1:n\n dC(i,:) = sum(bsxfun(@times, bsxfun(@minus, Y(i,:), Y), PQ(i,:)'), 1);\n end\n \n % Perform the gradient search\n y_incs = momentum * y_incs - eta * dC;\n Y = Y + y_incs;\n\t\tY = Y + jitter * randn(size(Y));\n Y = bsxfun(@minus, Y, mean(Y, 1));\n \n % Reduce jitter over time and change momentum\n jitter = jitter * jitter_decay;\n if iter == mom_switch_iter\n momentum = final_momentum;\n end\n end\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/sym_sne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7530071528703364}} {"text": "function [ x, seed ] = quasigeometric_sample ( a, b, seed )\n\n%*****************************************************************************80\n%\n%% QUASIGEOMETRIC_SAMPLE samples the Quasigeometric PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the probability of 0 successes.\n% 0.0 <= A <= 1.0.\n%\n% Input, real B, the depreciation constant.\n% 0.0 <= B < 1.0.\n%\n% Input, integer SEED, a seed for the random \n% number generator.\n%\n% Output, integer X, a sample of the PDF.\n%\n% Output, integer SEED, a seed for the random \n% number generator.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = quasigeometric_cdf_inv ( cdf, a, b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/quasigeometric_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8311430562234878, "lm_q1q2_score": 0.7530071524402838}} {"text": "function ref = physical_to_reference_tet4 ( t, n, phy )\n\n%*****************************************************************************80\n%\n%% PHYSICAL_TO_REFERENCE_TET4 maps physical points to reference points.\n%\n% Discussion:\n%\n% Given the vertices of an order 4 physical tetrahedron and a point \n% (X,Y,Z) in the physical tetrahedron, the routine computes the value \n% of the corresponding point (R,S,T) in the reference tetrahedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(3,4), the coordinates of the vertices of the\n% physical tetrahedron. The vertices are assumed to be the images of\n% (1,0,0), (0,1,0), (0,0,1) and (0,0,0) respectively.\n%\n% Input, integer N, the number of points to transform.\n%\n% Input, real PHY(3,N), the coordinates of physical points\n% to be transformed.\n%\n% Output, real REF(3,N), the coordinates of the corresponding\n% points in the reference tetrahedron.\n%\n a(1:3,1:3) = t(1:3,1:3);\n for i = 1 : 3\n a(i,1:3) = a(i,1:3) - t(i,4);\n end\n\n for i = 1 : 3\n ref(i,1:n) = phy(i,1:n) - t(i,4);\n end\n\n ref(1:3,1:n) = a(1:3,1:3) \\ ref(1:3,1:n);\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem3d_pack/physical_to_reference_tet4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7530071486509039}} {"text": "function B=autocorr2d(H)\n\n% Compute the 2D autocorrelation of matrix ( Image )\n% Algorithm based on Wiener - Khintchine Theorem*.\n%\n% * :http://mathworld.wolfram.com/Wiener-KhinchinTheorem.html\n%\n% Special Case : \n% 2D zero mean Gaussian process with variance=1:\n% ==========================\n% | P=randn(400,600); |\n% | CorrFunc=autocorr2d(H);|\n% ==========================\n% CorrFunc is symmetric with Dirac impulsion in the center.\n% with max(CorrFunc(:))=1\n% July, 24, 2012\n% KHMOU Youssef\n\n[n m]=size(H);\n% Divide by the size for normalization\n\nB=abs(fftshift(ifft2(fft2(H).*conj(fft2(H)))))./(n*m);\nfigure, surf(B);\nshading interp;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37624-2d-autocorrelation-function/New folder/autocorr2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7530071330633311}} {"text": "function [ w, x ] = line_o05 ( )\n\n%*****************************************************************************80\n%\n%% LINE_O05 returns a 5 point quadrature rule for the unit line.\n%\n% Discussion:\n%\n% The integration region is:\n%\n% - 1.0 <= X <= 1.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Output, real W(5), the weights.\n%\n% Output, real X(5), the abscissas.\n%\n w(1:5) = [ ...\n 0.118463442528095, ...\n 0.239314335249683, ...\n 0.284444444444444, ...\n 0.239314335249683, ...\n 0.118463442528095 ];\n\n x(1:5) = [ ...\n -0.90617984593866399280, ...\n -0.53846931010568309104, ...\n 0.00000000000000000000, ...\n 0.53846931010568309104, ...\n 0.90617984593866399280 ];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wedge_felippa_rule/line_o05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7528141440596067}} {"text": "function [x,tspan] = eulermaruyama(f,L,tspan,x0,Q)\n%% EULERMARUYAMA - Numerical SDE solver: The Euler-Maruyama method\n%\n% Syntax:\n% [x,tspan] = eulermaruyama(f,L,tspan,x0,Q)\n%\n% In:\n% f - Drift function, f(x,t)\n% L - Diffusion function, L(x,t)\n% tspan - Time steps to simulate, [t0,...,tend]\n% x0 - Initial condition\n% Q - Spectral density (default: standard Brownian motion)\n%\n% Out:\n% x - Solved values\n% tspan - Time steps\n% \n% Description:\n% Integrates the system of stochatic differential equations\n% dx = f(x,t) dt + L(x,t) dbeta, for x(0) = x0\n% over the time interval defined in tspan.\n%\n% Copyright: \n% 2018 - Simo Särkkä and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%%\n\n % Check if Q given\n if nargin<5 || isempty(Q), Q = eye(size(L(x0,tspan(1)),2)); end \n\n % Cholesky factor of Q\n cQ = chol(Q,'lower');\n \n % Number of steps\n steps = numel(tspan);\n \n % Allocate space\n x = zeros(size(x0,1),steps);\n\n % Initial state\n x(:,1) = x0;\n \n % Iterate\n for k=2:steps\n\n % Time discretization\n dt = tspan(k)-tspan(k-1);\n\n % Increment\n db = sqrt(dt)*cQ*randn(size(Q,1),1);\n\n % Step\n x(:,k) = x(:,k-1) + ...\n f(x(:,k-1),tspan(k-1))*dt + ...\n L(x(:,k-1),tspan(k-1))*db;\n \n end\n\n\n", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/eulermaruyama.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7528141407746252}} {"text": "%computes the lag of the average magnitude difference function\n%> called by ::ComputePitch\n%>\n%> @param x: audio signal\n%> @param iBlockLength: block length in samples\n%> @param iHopLength: hop length in samples\n%> @param f_s: sample rate of audio data \n%>\n%> @retval f_0 amdf lag (in Hz)\n%> @retval t time stamp of f_0 estimate (in s)\n% ======================================================================\nfunction [f_0, t] = PitchTimeAmdf(x, iBlockLength, iHopLength, f_s)\n\n % blocking\n [x_b, t] = ToolBlockAudio(x, iBlockLength, iHopLength, f_s);\n iNumOfBlocks = size(x_b, 1);\n \n % allocate memory\n f_0 = zeros(1, iNumOfBlocks);\n\n % initialization\n f_max = 2000;\n f_min = 50;\n eta_min = round(f_s/f_max);\n eta_max = round(f_s/f_min);\n\n for n = 1:iNumOfBlocks\n \n if (sum(abs(x_b(n, :))) == 0)\n f_0(n) = 0;\n continue;\n end\n \n % calculate the amdf_I minimum\n afAMDF = amdf_I(x_b(n, :), eta_max);\n [fDummy, T_0(n)] = min(afAMDF(1+eta_min:end));\n \n % convert to Hz\n f_0(n) = f_s ./ (T_0(n) + eta_min);\n end\nend\n\nfunction [AMDF] = amdf_I(x, eta_max)\n K = length(x);\n \n AMDF = ones(1, K);\n \n for eta=0:min(K-1,eta_max-1)\n AMDF(eta+1) = sum(abs(x(1:K-1-eta) - x(eta+2:end))) / K;\n end\nend", "meta": {"author": "alexanderlerch", "repo": "ACA-Code", "sha": "85d7258d5fcee1ca52bac52f651d26b665717687", "save_path": "github-repos/MATLAB/alexanderlerch-ACA-Code", "path": "github-repos/MATLAB/alexanderlerch-ACA-Code/ACA-Code-85d7258d5fcee1ca52bac52f651d26b665717687/PitchTimeAmdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.752814140774625}} {"text": "function julia(arg1,arg2)\n%\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%\n% Julia Fractals Using Matlab\n% Written By Sridharan, Mithun Aiyswaryan\n% Christian Albrechts Universität zu Kiel, Germany\n% Mail Your Comments At: s.mithun@indiatimes.com\n%\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% Help :\n% This program takes two arguments and computes the \n% Julia sets using the provided values.\n% For the best viewing results, varhoose the arguments such that:\n%\n% Argument 1 > 10 & Argument 2 > 100 \n% \n% Note : The generation of fractals is computationally \n% very intensive and it may take you a while before\n% you observe the results on the screen!\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nxaxis=0;\nyaxis=0;\nl=1.5;\nx=linspace(xaxis-l,xaxis+l,arg2);\ny=linspace(yaxis-l,yaxis+l,arg2);\n[xtrans,ytrans]=meshgrid(x,y);\nvar= -.745429;\nztrans=xtrans+i*ytrans;\nfor k=1:arg1;\nztrans=ztrans.^2+var;\nt=exp(-abs(ztrans));\nend\ncolormap prism(256)\npcolor(t);\nshading flat;\naxis('square','equal','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/3196-julia-sets/julia.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7527788289473479}} {"text": "function [x, infos] = alternating_onmf(V, rank, in_options)\n% Orthogonal two-block coordinate descent (2-BCD) for non-negative matrix factorization (Alt-Orth-NMF).\n%\n% The problem of interest is defined as\n%\n% min || V - WH ||_F^2,\n% where \n% {V, W, H} >= 0, and W or H is orthogonal, i.e., HH^T = I_r. \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% F. Pompili, N. Gillis, P.-A. Absil and F. Glineur, \n% \"Two Algorithms for Orthogonal Nonnegative Matrix Factorization\n% with Application to Clustering,\" \n% Neurocomputing 141, pp. 15-25, 2014. \n% \n%\n% This file is part of NMFLibrary.\n%\n% This file has been ported from \n% alternatingONMF.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 14, 2022 (Hiroyuki Kasai): Ported initial version \n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = []; \n local_options.orth_h = true;\n local_options.delta = 0;\n local_options.special_stop_condition = @(epoch, infos, options, stop_options) alt_nmf_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 factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W; % use only W\n \n % initialize\n method_name = 'ALT-ONMF'; \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 % Xn: normalized version of X, ||Xn(:,j)||_2 1 for all j\n norm2x = sqrt(sum(V.^2,1)); \n Vn = V .* repmat(1./(norm2x+1e-16), m, 1); \n normV2 = sum(V(:).^2); \n stop_options.normV2 = normV2;\n H = nnls_orth(V, W, Vn);\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 orth_val = norm(H*H' - eye(rank), 'fro');\n [infos.orth] = orth_val;\n infos.prev_error = Inf; \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 while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag, infos] = check_stop_condition(epoch, infos, options, stop_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 % H = argmin_H ||X-WH||_F, H >= 0, rows H orthogonal up to a scaling of the rows of H\n H = nnls_orth(V, W, Vn); \n\n % normalize rows of H \n norm2h = sqrt(sum(H'.^2, 1)) + 1e-16;\n H = repmat(1./norm2h', 1, n) .* H; \n\n % update W\n W = V * H';\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 infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time); \n orth_val = norm(H*H' - eye(rank), 'fro');\n [infos.orth] = [infos.orth orth_val];\n \n % display info\n display_info(method_name, epoch, infos, options);\n\n % check convergence (by original code)\n e = sqrt( (normV2-sum(sum(W.^2)))/normV2 ); \n if (epoch > 2) && (abs(e_prev-e) < options.delta)\n %break;\n else\n e_prev = e;\n end\n end\n \n x.W = W;\n x.H = H;\n\nend\n\n\nfunction [stop_flag, reason, infos] = alt_nmf_stop_func(epoch, infos, options, stop_options)\n\n stop_flag = false;\n reason = [];\n\n normV2 = stop_options.normV2;\n W = infos.final_W;\n \n error = sqrt( (normV2-sum(sum(W.^2)))/normV2 ); \n if (epoch > 2) && (abs(infos.prev_error - error) < options.delta)\n stop_flag = true;\n reason = sprintf('Relative solution change tolerance reached: %.4e < %.4e\\n', abs(infos.prev_error - error), options.delta);\n else\n infos.prev_error = error;\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/orthogonal/alternating_onmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7527431537332618}} {"text": "% Copyright (C) 2000 Paul Kienzle \n% Copyright (C) 2007 Peter L. Soendergaard\n%\n% This program is free software; you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation; either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program; if not, see .\n\n% -*- texinfo -*-\n% @deftypefn {Function File} {@var{h} =} hilbert (@var{f}, @var{N}, @var{dim})\n% Analytic extension of real valued signal.\n%\n% @code{@var{h} = hilbert (@var{f})} computes the extension of the real\n% valued signal @var{f} to an analytic signal. If @var{f} is a matrix,\n% the transformation is applied to each column. For N-D arrays,\n% the transformation is applied to the first non-singleton dimension.\n%\n% @code{real (@var{h})} contains the original signal @var{f}.\n% @code{imag (@var{h})} contains the Hilbert transform of @var{f}.\n%\n% @code{hilbert (@var{f}, @var{N})} does the same using a length @var{N}\n% Hilbert transform. The result will also have length @var{N}.\n%\n% @code{hilbert (@var{f}, [], @var{dim})} or\n% @code{hilbert (@var{f}, @var{N}, @var{dim})} does the same along\n% dimension @var{dim}.\n% @end deftypefn\n\nfunction f = oc_hilbert(f, N, dim)\n\n% ------ PRE: initialization and dimension shifting ---------\n\nif (nargin<1 || nargin>3)\n error('Invalid call');\nend\nif (nargin < 3)\n dim = [];\nend\nif (nargin < 2)\n N = [];\nend\n\nif ~isreal(f)\n warning ('HILBERT: ignoring imaginary part of signal');\n f = real (f);\nend\n\nD=ndims(f);\n\n% Dummy assignment.\norder=1;\n\nif isempty(dim)\n dim=1;\n \n if sum(size(f)>1)==1\n % We have a vector, find the dimension where it lives.\n dim=find(size(f)>1);\n end\n \nelse\n if (numel(dim)~=1 || ~isnumeric(dim))\n error('HILBERT: dim must be a scalar.');\n end\n if rem(dim,1)~=0\n error('HILBERT: dim must be an integer.');\n end\n if (dim<1) || (dim>D)\n error('HILBERT: dim must be in the range from 1 to %d.',D);\n end\n \nend\n\nif (numel(N)>1 || ~isnumeric(N))\n error('N must be a scalar.');\nelseif (~isempty(N) && rem(N,1)~=0)\n error('N must be an integer.');\nend\n\nif dim>1\n order=[dim, 1:dim-1,dim+1:D];\n \n % Put the desired dimension first.\n f=permute(f,order);\n \nend\n\nLs=size(f,1);\n\n% If N is empty it is set to be the length of the transform.\nif isempty(N)\n N=Ls;\nend\n\n% Remember the exact size for later and modify it for the new length\npermutedsize=size(f);\npermutedsize(1)=N;\n\n% Reshape f to a matrix.\nf=reshape(f,size(f,1),numel(f)/size(f,1));\nW=size(f,2);\n\nif ~isempty(N)\n f = oc_postpad(f,N);\nend\n\n% ------- actual computation -----------------\nif N>2\n f=fft(f);\n \n if rem(N,2)==0\n f=[f(1,:);\n 2*f(2:N/2,:);\n f(N/2+1,:);\n zeros(N/2-1,W)];\n else\n f=[f(1,:);\n 2*f(2:(N+1)/2,:);\n zeros((N-1)/2,W)];\n end\n \n f=ifft(f);\nend\n\n% ------- POST: Restoration of dimensions ------------\n\n% Restore the original, permuted shape.\nf=reshape(f,permutedsize);\n\nif dim>1\n % Undo the permutation.\n f=ipermute(f,order);\nend\n\nend\n\n%!demo\n%! % notice that the imaginary signal is phase-shifted 90 degrees\n%! t=linspace(0,10,256);\n%! z = hilbert(sin(2*pi*0.5*t));\n%! grid on; plot(t,real(z),';real;',t,imag(z),';imag;');\n\n%!demo\n%! % the magnitude of the hilbert transform eliminates the carrier\n%! t=linspace(0,10,1024);\n%! x=5*cos(0.2*t).*sin(100*t);\n%! grid on; plot(t,x,'g;z;',t,abs(hilbert(x)),'b;|hilbert(z)|;');\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/external/octave/oc_hilbert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7527372817185272}} {"text": "function r = tenRank( A, tol )\n%TENRANK Calculates the multilinear rank.\n% R = TENRANK( A, TOL ) calculates the multilinear rank R of the\n% given tensor A. All singular values below the specified tolerance\n% TOL are considered to be zero.\n% \n% R = TENRANK( A ) calculates the multilinear rank R of the given \n% tensor A. The default tolerance 1e-5 is chosen for the cutoff.\n%\n\n% GeomCG Tensor Completion. Copyright 2013 by\n% Michael Steinlechner\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\n \n if ~exist('tol','var')\n tol = 1e-5;\n end\n\n r = zeros( 1, ndims( A ) );\n\n for i = 1:ndims( A )\n r(i) = rank( double( tenmat( A, i ) ), tol);\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/geomCG/tenRank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7527372761099032}} {"text": "function moment = truncated_normal_ab_moment ( order, mu, s, a, b )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_AB_MOMENT returns a moment of the truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Phoebus Dhrymes,\n% Moments of Truncated Normal Distributions,\n% May 2005.\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the moment.\n% 0 <= ORDER.\n%\n% Input, real MU, S, the mean and standard deviation of the\n% parent Normal distribution.\n% 0 < S.\n%\n% Input, real A, B, the lower and upper truncation limits.\n% A < B.\n%\n% Output, real MOMENT, the moment of the PDF.\n%\n if ( order < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' ORDER < 0.\\n' );\n error ( 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n end\n\n if ( s <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' S <= 0.0.\\n' );\n error ( 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n end\n\n if ( b <= a )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' B <= A.\\n' );\n error ( 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n end\n\n a_h = ( a - mu ) / s;\n a_pdf = normal_01_pdf ( a_h );\n a_cdf = normal_01_cdf ( a_h );\n\n if ( a_cdf == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' PDF/CDF ratio fails, because A_CDF is too small.\\n' );\n fprintf ( 1, ' A_PDF = %g\\n', a_pdf );\n fprintf ( 1, ' A_CDF = %g\\n', a_cdf );\n error ( 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n end\n\n b_h = ( b - mu ) / s;\n b_pdf = normal_01_pdf ( b_h );\n b_cdf = normal_01_cdf ( b_h );\n\n if ( b_cdf == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' PDF/CDF ratio fails, because B_CDF too small.\\n' );\n fprintf ( 1, ' B_PDF = %g\\n', b_pdf );\n fprintf ( 1, ' B_CDF = %g\\n', b_cdf );\n error ( 'TRUNCATED_NORMAL_AB_MOMENT - Fatal error!\\n' );\n end\n\n moment = 0.0;\n irm2 = 0.0;\n irm1 = 0.0;\n\n for r = 0 : order\n\n if ( r == 0 )\n ir = 1.0;\n elseif ( r == 1 )\n ir = - ( b_pdf - a_pdf ) / ( b_cdf - a_cdf );\n else\n ir = ( r - 1 ) * irm2 ...\n - ( b_h ^ ( r - 1 ) * b_pdf - a_h ^ ( r - 1 ) * a_pdf ) ...\n / ( b_cdf - a_cdf );\n end\n\n moment = moment + r8_choose ( order, r ) ...\n * mu ^ ( order - r ) ...\n * s ^ r * ir;\n\n irm2 = irm1;\n irm1 = ir;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadmom/truncated_normal_ab_moment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7527372761099032}} {"text": "function r=rot4x(theta)\n % r = rot4x(theta)\n %\n % rotx produces a 4x4 rotation matrix representing\n % a rotation by theta radians about the x axis.\n %\n %\tArgument definitions:\n %\n %\ttheta = rotation angle in radians\n c = cos(theta);\n s = sin(theta);\n r = [1 0 0 0;\n 0 c -s 0;\n 0 s c 0;\n 0 0 0 1];\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/eztool/rot4x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.752684313149789}} {"text": "function value = pyramid_unit_volume_3d ( )\n\n%*****************************************************************************80\n%\n%% PYRAMID_UNIT_VOLUME_3D returns the volume of a unit pyramid in 3D.\n%\n% Integration region:\n%\n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% Discussion:\n%\n% A pyramid with square base can be regarded as the upper half of a\n% 3D octahedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, the volume of the pyramid.\n%\n value = 4.0 / 3.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/pyramid_unit_volume_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7526127205338096}} {"text": "function a = bab ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% BAB returns the BAB matrix.\n%\n% Example:\n%\n% N = 5\n% ALPHA = 5, BETA = 2\n%\n% 5 2 . . .\n% 2 5 2 . .\n% . 2 5 2 .\n% . . 2 5 2\n% . . . 2 5\n%\n% Properties:\n%\n% A is banded, with bandwidth 3.\n%\n% A is tridiagonal.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is Toeplitz: constant along diagonals.\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% CM da Fonseca, J Petronilho,\n% Explicit Inverses of Some Tridiagonal Matrices,\n% Linear Algebra and Its Applications,\n% Volume 325, 2001, pages 7-21.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real ALPHA, BETA, the parameters.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n a(i,i) = alpha;\n end\n\n for i = 1 : n - 1\n a(i,i+1) = beta;\n a(i+1,i) = beta;\n end\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/bab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7526127187364577}} {"text": "function [cm, cSq] = DiscreteFrechetDist(P,Q,dfcn)\n% Calculates the discrete Frechet distance between curves P and Q\n%\n% [cm, cSq] = DiscreteFrechetDist(P,Q)\n% [cm, cSq] = DiscreteFrechetDist(...,dfcn)\n%\n% P and Q are two sets of points that define polygonal curves with rows of\n% vertices (data points) and columns of dimensionality. The points along\n% the curves are taken to be in the order as they appear in P and Q.\n%\n% Returned in cm is the discrete Frechet distance, aka the coupling\n% measure, which is zero when P equals Q and grows positively as the curves\n% become more dissimilar.\n%\n% The optional dfcn argument allows the user to specify a function with\n% which to calculate distance between points in P and Q. If not provided,\n% the L2 norm is used.\n%\n% The secondary output, cSq, is the coupling sequence, that is, the\n% sequence of steps along each curve that must be followed to achieve the\n% minimum coupling distance, cm. The output is returned in the form of a\n% matrix with column 1 being the index of each point in P and column 2\n% being the index of each point in Q. (NOTE: the coupling sequence is not\n% unique in general)\n%\n% Explanation:\n% The Frechet distance is a measure of similarity between to curves, P and\n% Q. It is defined as the minimum cord-length sufficient to join a point\n% traveling forward along P and one traveling forward along Q, although the\n% rate of travel for either point may not necessarily be uniform.\n%\n% The Frechet distance, FD, is not in general computable for any given\n% continuous P and Q. However, the discrete Frechet Distance, also called\n% the coupling measure, cm, is a metric that acts on the endpoints of\n% curves represented as polygonal chains. The magnitude of the coupling\n% measure is bounded by FD plus the length of the longest segment in either\n% P or Q, and approaches FD in the limit of sampling P and Q.\n%\n% This function implements the algorithm to calculate discrete Frechet\n% distance outlined in:\n% T. Eiter and H. Mannila. Computing discrete Frechet distance. Technical\n% Report 94/64, Christian Doppler Laboratory, Vienna University of\n% Technology, 1994.\n% \n%\n%\n% EXAMPLE:\n% % create data\n% t = 0:pi/8:2*pi;\n% y = linspace(1,3,6);\n% P = [(2:7)' y']+0.3.*randn(6,2);\n% Q = [t' sin(t')]+2+0.3.*randn(length(t),2);\n% [cm, cSq] = DiscreteFrechetDist(P,Q);\n% % plot result\n% figure\n% plot(Q(:,1),Q(:,2),'o-r','linewidth',3,'markerfacecolor','r')\n% hold on\n% plot(P(:,1),P(:,2),'o-b','linewidth',3,'markerfacecolor','b')\n% title(['Discrete Frechet Distance of curves P and Q: ' num2str(cm)])\n% legend('Q','P','location','best')\n% line([2 cm+2],[0.5 0.5],'color','m','linewidth',2)\n% text(2,0.4,'dFD length')\n% for i=1:length(cSq)\n% line([P(cSq(i,1),1) Q(cSq(i,2),1)],...\n% [P(cSq(i,1),2) Q(cSq(i,2),2)],...\n% 'color',[0 0 0]+(i/length(cSq)/1.35));\n% end\n% axis equal\n% % display the coupling sequence along with each distance between points\n% disp([cSq sqrt(sum((P(cSq(:,1),:) - Q(cSq(:,2),:)).^2,2))])\n%\n%\n% \n% %%% ZCD June 2011 %%%\n% %%% edits ZCD May 2013: 1) remove excess arguments to internal functions\n% and persistence for speed, 2) added example, 3) allowed for user defined\n% distance function, 4) added aditional output option for coupling sequence\n%\n\n\n% size of the data curves\nsP = size(P);\nsQ = size(Q);\n\n% check validity of inputs\nif sP(2)~=sQ(2)\n error('Curves P and Q must be of the same dimension')\nelseif sP(1)==0\n cm = 0;\n return;\nend\n\n% initialize CA to a matrix of -1s\nCA = ones(sP(1),sQ(1)).*-1;\n\n% distance function\nif nargin==2\n dfcn = @(u,v) sqrt(sum( (u-v).^2 ));\nend\n\n% final coupling measure value\ncm = c(sP(1),sQ(1));\n\n% obtain coupling measure via backtracking procedure\nif nargout==2\n cSq = zeros(sQ(1)+sP(1)+1,2); % coupling sequence\n CApad = [ones(1,sQ(1)+1)*inf; [ones(sP(1),1)*inf CA]]; % pad CA\n Pi=sP(1)+1; Qi=sQ(1)+1; count=1; % counting variables\n while Pi~=2 || Qi~=2\n % step down CA gradient\n [v,ix] = min([CApad(Pi-1,Qi) CApad(Pi-1,Qi-1) CApad(Pi,Qi-1)]);\n if ix==1\n cSq(count,:) = [Pi-1 Qi];\n Pi=Pi-1;\n elseif ix==2\n cSq(count,:) = [Pi-1 Qi-1];\n Pi=Pi-1; Qi=Qi-1;\n elseif ix==3\n cSq(count,:) = [Pi Qi-1];\n Qi=Qi-1;\n end\n count=count+1;\n end\n % format output: remove extra zeroes, reverse order, subtract off\n % padding value, and add in the last point\n cSq = [flipud(cSq(1:find(cSq(:,1)==0,1,'first')-1,:))-1; sP(1) sQ(1)];\nend\n\n\n% debug\n% assignin('base','CAw',CA)\n\nfunction CAij = c(i,j)\n % coupling search function\n if CA(i,j)>-1\n % don't update CA in this case\n CAij = CA(i,j);\n elseif i==1 && j==1\n CA(i,j) = dfcn(P(1,:),Q(1,:)); % update the CA permanent\n CAij = CA(i,j); % set the current relevant value\n elseif i>1 && j==1\n CA(i,j) = max( c(i-1,1), dfcn(P(i,:),Q(1,:)) );\n CAij = CA(i,j);\n elseif i==1 && j>1\n CA(i,j) = max( c(1,j-1), dfcn(P(1,:),Q(j,:)) );\n CAij = CA(i,j);\n elseif i>1 && j>1\n CA(i,j) = max( min([c(i-1,j), c(i-1,j-1), c(i,j-1)]),...\n dfcn(P(i,:),Q(j,:)) );\n CAij = CA(i,j);\n else\n CA(i,j) = inf;\n end\nend % end function, c\n\nend % end main function\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/31922-discrete-frechet-distance/DiscreteFrechetDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7526127176770794}} {"text": "% Chapter 17 - Neural Networks.\n% Programs_17e - Bifurcation Diagram for a Simple Bistable Neuromodule.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Bifurcation diagram for a two-neuron module. (See Figure 17.15).\n% Vary bias b1.\nclear all\nformat long;\nhalfN=1000;N=2*halfN+1;N1=1+halfN;Max=10;a=1;alpha=0.3;\nx=zeros(1,N);y=zeros(1,N);\nb2=3;w11=7;w12=-4;w21=5;start=-5;\nx(1)=-10;y(1)=-3;\n\n% Ramp the power up\nfor n=1:halfN\n b1=(start+n*Max/halfN);\n x(n+1)=b1+w11*(exp(a*x(n))-exp(-a*x(n)))/(exp(a*x(n))+exp(-a*x(n)))+w12*(exp(alpha*y(n))-exp(-alpha*y(n)))/(exp(alpha*y(n))+exp(-alpha*y(n)));\n y(n+1)=b2+w21*(exp(a*x(n))-exp(-a*x(n)))/(exp(a*x(n))+exp(-a*x(n)));\nend\n\n% Ramp the power down\nfor n=N1:N\n b1=(start+2*Max-n*Max/halfN);\n x(n+1)=b1+w11*(exp(a*x(n))-exp(-a*x(n)))/(exp(a*x(n))+exp(-a*x(n)))+w12*(exp(alpha*y(n))-exp(-alpha*y(n)))/(exp(alpha*y(n))+exp(-alpha*y(n)));\n y(n+1)=b2+w21*(exp(a*x(n))-exp(-a*x(n)))/(exp(a*x(n))+exp(-a*x(n)));\nend\n\n% Plot the bifurcation diagrams\nfsize=14;\nsubplot(2,1,1)\nhold on\nset(gca,'XTick',0:halfN/2:N,'FontSize',fsize);\nset(gca,'YTick',-Max:5:Max,'FontSize',fsize);\nplot(x(1:N),'-','MarkerSize',1,'color','k')\nxlabel('Number of Iterations','FontSize',fsize);\nylabel('x_n','FontSize',fsize);\nhold off\nx1=zeros(1,N);w=zeros(1,N);\n\nfor n=1:halfN\n x1(n)=x(N+1-n);\n w(n)=start+n*Max/halfN;\nend\n\nsubplot(2,1,2)\nhold on\nset(gca,'XTick',start:5:start+Max,'FontSize',fsize);\nset(gca,'YTick',-Max:5:Max,'FontSize',fsize);\nplot(w(1:halfN),x(1:halfN),'-','MarkerSize',1,'color','k');\nplot(w(1:halfN),x1(1:halfN),'-','MarkerSize',1,'color','k');\nxlabel('b_1','FontSize',fsize);\nylabel('x_n','FontSize',fsize);\nhold off\n\n% End of Programs_17e.\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/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Programs_17e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7526127097496973}} {"text": "% EASY12 Detailed explanations of a Matlab implementation \n% of the Lambda method. The notation follows the one\n% introduced in Strang and Borre, pages 495--499\n\n%Kai Borre 30-06-2008\n%Copyright (c) by Kai Borre\n%$Revision: 1.0 $ $Date: 2008/06/30 $\n\nfprintf('\\n')\necho on\n% Test example\nhat_I = [5.45;3.1;2.97];\n%hat_I =[0; 1];\nn = size(hat_I,1);\nQ_hat_I = [6.29 5.978 .544; 5.978 6.292 2.34; .544 2.34 6.288];\n%Q_hat_I = [53.40 38.40;38.40 28.00];\necho off\n\n% Given float ambiguities\nfprintf('\\nFloat ambiguities hat_I')\nfor i = 1:n\n fprintf('\\n%12.3f', hat_I(i,1))\nend\n\n% Original covariance matrix for hat_I\nfprintf('\\n\\nCovariance matrix for hat_I') \nfor i = 1:n\n fprintf('\\n')\n for j = 1:n\n fprintf('%12.3f', Q_hat_I(i,j))\n end\nend\n\nfprintf('\\n\\n')\necho on\n% Shift of hat_I in order to secure that -1 < hat_I <= +1\necho off\n\nshifts = hat_I-rem(hat_I,1);\nfprintf('\\n\\nInteger shifts of hat_I')\nfor i = 1:n\n fprintf('\\n%12.0f', shifts(i,1))\nend\n\n% Remainders of hat_I\nhat_I_r = rem(hat_I,1);\nfprintf('\\n\\nRemainders of hat_I')\nfor i = 1:n\n fprintf('\\n%12.3f', hat_I_r(i,1))\nend\n\n% L^T*D*L factorization of Q_hat_I\n% For consistency we do not use the Matlab ldl function\n[L,D] = ldldecom(Q_hat_I);\nfprintf('\\n\\nQ_hat_I is factorized into L^T*D*L')\nfprintf('\\n\\nThe lower triangular L')\nfor i = 1:n\n fprintf('\\n')\n for j = 1:n\n fprintf('%12.3f',L(i,j))\n end\nend\nfprintf('\\n\\nThe diagonal matrix D\\n')\nfor i = 1:n\n fprintf('%12.3f',D(i))\nend\n\n% Computing the size of the search volume\nchi2 = chistart(D,L,hat_I_r,1);\nfprintf('\\n\\nchi^2 = %5.3f\\n',chi2)\n\n% Doing the decorrelation\n[Q_bar_I,Z,L_t,D_t] = decorrel(Q_hat_I,hat_I_r);\nfprintf('\\nInteger transformation matrix Z')\nfor i = 1:n\n fprintf('\\n')\n for j = 1:n\n fprintf('%12.0f',Z(i,j))\n end\nend\n\n% hat_I transformed: I_s = Z'*hat_I_r\nfprintf('\\n\\nTransformed, shifted ambiguities I_s = Z^T*hat_I_r')\nI_s = Z'*hat_I_r;\nfor i = 1:n\n fprintf('\\n%12.3f',I_s(i))\nend\n\n% The transformed, decorrelated covariance matrix: Q_bar_I = Z^T*Q_hat_I*Z\nfprintf('\\n\\nThe transformed, decorrelated covariance matrix Q_bar_I = Z^T*Q_hat_I*Z.')\nfprintf('\\n\\nQ_bar_I = Z^T*Q_hat_I*Z')\nfor i = 1:n\n fprintf('\\n')\n for j = 1:n\n fprintf('%12.3f',Q_bar_I(i,j))\n end\nend\nfprintf('\\nNote the deminished off-diagonal terms!')\nfprintf('\\n\\nThe lower triangular L_t used in the search')\nfor i = 1:n\n fprintf('\\n')\n for j = 1:n\n fprintf('%12.3f',L_t(i,j))\n end\nend\nfprintf('\\n\\nThe diagonal matrix D_t used in the seach\\n')\nfor i = 1:n\n fprintf('%12.3f',D_t(i))\nend\n\nfprintf('\\n\\n')\necho on\n% Determining the size of the search volume for the transformed L_t and D_t\necho off\n\nchi2 = chistart(D_t,L_t,I_s,1); \nfprintf('\\n\\nchi^2 for the transformed problem = %5.3f\\n',chi2)\n\nfprintf('\\nThe search domain is defined as')\nfprintf('\\n(I-hat_I_r)^T*(Z^T*Q_hat_I*Z)*(I-hat_I_r) < chi^2, for I integer')\n\n[bar_I,sqnorm,ierr] = lsearch(I_s,L_t,D_t,chi2,1);\n%bar_I = (bar_I' * inv(Z))'+shifts;\nbar_I = (bar_I'/Z)' + shifts; \nfprintf('\\n\\nFixed ambiguities bar_I')\nfor i = 1:n\n fprintf('\\n%12.0f', bar_I(i,1))\nend\nfprintf('\\n\\n')\n%%%%%%%%%%%%%%%%%%%%%%%%%%% end easy12.m %%%%%%%%%%%%\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/easy12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7525949764744702}} {"text": "u0 = double(imread('58468899e2951a4b87b00897.png'));\nu0 = mean(u0,3);\n\n[M N] = size(u0);\nMN = M*N;\nI=reshape([1:M*N],M,N);\neast=[I(:,2:end), I(:,end)];\nnorth=[I(2:end,:); I(end,:)];\nD1 = sparse(I,east,1,MN,MN) -speye(MN,MN);\nD2 = sparse(I,north,1,MN,MN) -speye(MN,MN);\nD = [D1 ; D2];\n\nh0 = [ 1 2 1 ];\nh = h0\nfor i=1:5 %% level of blur\n h = conv(h0,h);\nend\nsize(h)\nh = h'*h;\nh = h/sum(sum(h));\n\nstddev=5;\ng = filter2(h,u0,'valid');\n[Ms Ns]=size(g);\ng = g + stddev*randn(Ms,Ns);\n\nfigure(1);\nimagesc(u0); colormap(gray); %drawnow();\nfigure(2);\nimagesc(g); colormap(gray); drawnow();\n\nu=zeros(size(u0));\nL2 = 8;\ntau = 1; %% max value for tau = 1;\nsig = 1/tau/L2;\nlambda = .2;\n\np = zeros(2*MN,1);\n%% primal-dual\nfor i=1:1000\n um = u;\n u = u-tau*(conv2(h,filter2(h,u,'valid')-g,'full') + reshape(D'*p,M,N));\n um = 2*u-um;\n p = p + sig*D*um(:);\n no= max(1,hypot(p(1:MN),p(MN+1:end))/lambda);\n p = p./[no;no]; \n if mod(i,20)==0\n i\n figure(3);\n imagesc(u);\n colormap(gray); drawnow();\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/ImageProcessing/Old/Deblurr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7525811076867646}} {"text": "function [M, H, noiseFractions] = hyperNacp(M, h, w)\n% HYPERMNF Performs the noise adjusted principal component transform (NACP)\n% hyperMnf performs the noise adjust principal component transform on the \n% data and uses spatial (row) offsets of the data to estimate the \n% covariance matrix of the data.\n%\n% Usage\n% M = hyperNacp(M, h, w)\n% Inputs\n% M - 2D matrix (p x N)\n% h - height of image in pixels\n% w - width of image in pixels\n% Outputs\n% M - 2D transformed data\n% H - 2D transformation matrix\n% noiseFractions - Estimates of the noise fraction for each band\n%\n% References\n% C-I Change and Q Du, \"Interference and Noise-Adjusted Principal \n% Components Analysis,\" IEEE TGRS, Vol 36, No 5, September 1999.\n\n[p, N] = size(M);\n\n% Remove mean from data\nu = mean(M.').';\nfor k=1:N\n M(:,k) = M(:,k) - u;\nend\n\n% Compute to rotation of the signal+noise\nsigmaZ = hyperCov(M);\nM = hyperConvert3d(M, h, w, p);\n\n% Estimate the covariance of the noise.\ndX = zeros(h-1, w, p);\nfor i=1:(h-1)\n dX(i, :, :) = M(i, :, :) - M(i+1, :, :);\nend\ndX = hyperConvert2d(dX);\n\n% Compute the covariance of the noise signal estimate.\nsigmaN = hyperCov(dX);\n\n% Orthonormalize the noise subspace.\n[U,deltaN,E] = svd(sigmaN);\nF = E*inv(sqrt(deltaN)); % Rotation components of noise orthonormalized\n% F now whitens the noise.\n\n% Rotates the signal+noise cov so that the noise is whitened (all noise\n% powers are equal)\nsigmaAdj = F'*sigmaZ*F;\n\n[U,gammaAdj,G] = svd(sigmaAdj);\nH = G*F;\n\n% Compute noise fractions\nnoiseFractions = diag(gammaAdj);\n\n% Perform transform\nM = H*hyperConvert2d(M);\n\n", "meta": {"author": "isaacgerg", "repo": "matlabHyperspectralToolbox", "sha": "26955b0abb442d06009c220980e974461e419bf8", "save_path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox", "path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox/matlabHyperspectralToolbox-26955b0abb442d06009c220980e974461e419bf8/hyperspectralToolbox/hyperNapc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7525811009484475}} {"text": "function glscf = CO_glscf(y,alpha,beta,tau)\n% CO_glscf The generalized linear self-correlation function of a time series.\n%\n% This function was introduced in Queiros and Moyano in Physica A, Vol. 383, pp.\n% 10--15 (2007) in the paper \"Yet on statistical properties of traded volume:\n% Correlation and mutual information at different value magnitudes\"\n% https://www.sciencedirect.com/science/article/pii/S0378437107004645\n%\n% The function considers magnitude correlations.\n%\n%---INPUTS:\n% y, the input time series\n% alpha and beta are real and nonzero parameters\n% tau is the time-delay (can also be 'tau' to set to first zero-crossing of the ACF)\n%\n% When alpha = beta estimates how values of the same order of magnitude are\n% related in time\n% When alpha ~= beta, estimates correlations between different magnitudes of the\n% time series.\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check inputs and set defaults\n% ------------------------------------------------------------------------------\nif nargin < 4 || isempty(tau)\n tau = 'tau';\nend\n\n% Set tau to first zero-crossing of the autocorrelation function with the input 'tau'\nif strcmp(tau,'tau')\n tau = CO_FirstCrossing(y,'ac',0,'discrete');\nend\n\n% Take magnitudes of time-delayed versions of the time series:\ny1 = abs(y(1:end-tau));\ny2 = abs(y(1+tau:end));\n\nglscf = (mean((y1.^alpha).*(y2.^beta)) - mean(y1.^alpha)*mean(y2.^beta)) / ...\n \t\t (sqrt(mean(y1.^(2*alpha)) - mean(y1.^alpha)^2) ...\n \t\t * sqrt(mean(y2.^(2*beta)) - mean(y2.^beta)^2));\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/CO_glscf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7525810973986766}} {"text": "function [H_o_j, A_j, H_x_j] = calcHoj(p_f_G, msckfState, camStateIndices)\n%CALCHOJ Calculates H_o_j according to Mourikis 2007\n% Inputs: p_f_G: feature location in the Global frame\n% msckfState: the current window of states\n% camStateIndex: i, with camState being the ith camera pose in the window \n% Outputs: H_o_j, A\n\n\nN = length(msckfState.camStates);\nM = length(camStateIndices);\nH_f_j = zeros(2*M, 3);\nH_x_j = zeros(2*M, 12 + 6*N);\n\n\nc_i = 1;\nfor camStateIndex = camStateIndices\n camState = msckfState.camStates{camStateIndex};\n\n C_CG = quatToRotMat(camState.q_CG);\n %The feature position in the camera frame\n p_f_C = C_CG*(p_f_G - camState.p_C_G);\n\n X = p_f_C(1);\n Y = p_f_C(2);\n Z = p_f_C(3);\n\n J_i = (1/Z)*[1 0 -X/Z; 0 1 -Y/Z];\n\n H_f_j((2*c_i - 1):2*c_i, :) = J_i*C_CG;\n\n H_x_j((2*c_i - 1):2*c_i,12+6*(camStateIndex-1) + 1:12+6*(camStateIndex-1) + 3) = J_i*crossMat(p_f_C);\n H_x_j((2*c_i - 1):2*c_i,(12+6*(camStateIndex-1) + 4):(12+6*(camStateIndex-1) + 6)) = -J_i*C_CG;\n\n c_i = c_i + 1;\nend\n\n\nA_j = null(H_f_j');\nH_o_j = A_j'*H_x_j;\n\nend\n\n", "meta": {"author": "utiasSTARS", "repo": "msckf-swf-comparison", "sha": "ad9566ef35c3e4792a89b04623e1fa2f99238435", "save_path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison", "path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison/msckf-swf-comparison-ad9566ef35c3e4792a89b04623e1fa2f99238435/msckf/calcHoj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7524915149931697}} {"text": "function [H]=hessianScalar(varargin)\n\n% function [H]=hessianScalar(U,v,cellOpt)\n% ------------------------------------------------------------------------\n%\n% This function computes the Hessian matrix of the scalar function U for\n% each point in U. U may be a vector, a 2D matrix or a 3D matrix. The\n% vector v denotes the points spacing between the data entries in U. If v\n% is not supplied the spacing is assumed to be homogeneous and unity. If\n% the input is n dimensional array consisting of m entries then the output\n% is a matrix (if cellOpt==0) the size of mx(n^2) (whereby the colum\n% entries define the entries in a Hessian matrix and row entries relate to\n% elements in the input array). If cellOpt==1 then the output is reformed\n% into a cell array that matches the size of the input aray. Each cell\n% entry then contains the nxn Hessian matrix. \n%\n% See also: |gradient|,|hessian|,|jacobian|,|cellEig|\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2014/10/10 Updated\n%------------------------------------------------------------------------\n\n%% Parse input\n\nswitch nargin\n case 1\n U=varargin{1};\n v=[];\n cellOpt=0;\n case 2\n U=varargin{1};\n v=varargin{2};\n cellOpt=0;\n case 3\n U=varargin{1};\n v=varargin{2};\n cellOpt=varargin{3};\nend\n%%\n\nnDims=ndims(U);\nif isvector(U)\n nDims=1;\nend\n\nif isempty(v)\n v=ones(1,nDims); %Use default\nend\n\nif nDims<=3 \n switch nDims\n case 1\n %Compute first order derivative\n [dUdx] = gradient(U,v);\n \n %Compute second order derivatives\n [dUdxdx] = gradient(dUdx,v);\n \n H_mat=dUdxdx(:);\n case 2\n %Compute first order derivative\n [dUdx,dUdy] = gradient(U,v(1),v(2));\n \n %Compute second order derivatives\n [dUdxdx,dUdxdy] = gradient(dUdx,v(1),v(2));\n [dUdydx,dUdydy] = gradient(dUdy,v(1),v(2));\n \n H_mat=[dUdxdx(:) dUdxdy(:)...\n dUdydx(:) dUdydy(:)]; \n case 3 \n %Compute first order derivative\n [dUdx,dUdy,dUdz] = gradient(U,v(1),v(2),v(3));\n \n %Compute second order derivatives\n [dUdxdx,dUdxdy,dUdxdz] = gradient(dUdx,v(1),v(2),v(3));\n [dUdydx,dUdydy,dUdydz] = gradient(dUdy,v(1),v(2),v(3));\n [dUdzdx,dUdzdy,dUdzdz] = gradient(dUdz,v(1),v(2),v(3));\n \n H_mat=[dUdxdx(:) dUdxdy(:) dUdxdz(:)...\n dUdydx(:) dUdydy(:) dUdydz(:)...\n dUdzdx(:) dUdzdy(:) dUdzdz(:)];\n end\n \n if cellOpt==1\n H_mat=reshape(H_mat',nDims,nDims,size(H_mat,1));\n \n %Cell array of Hessian matrices\n H=reshape(mat2cell(H_mat,nDims,nDims,ones(size(H_mat,3),1)),size(U));\n else\n H=H_mat;\n end\nelse \n warning('Function only defined for 1D, 2D or 3D scalar valued arrays');\nend\n\n\n\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/hessianScalar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7524915105071482}} {"text": "% Test script for solving the 2D advection\nGlobals2D;\n\n% Set polynomial order to use\nN = 7;\n\n% Read and initiate circular mesh\nfilename = 'circA01.neu';\n[Nv, VX, VY, K, EToV, BCType] = MeshReaderGambitBC2D(filename);\n\nStartUp2D;\nBuildBCMaps2D;\n\n% Push all boundary faces to unit cylinder\n[k,f] = find(BCType); \ncurved = sort(unique(k));\nMakeCylinder2D([k,f], 1, 0, 0);\n\n% Set initial conditions\n% First 6 modes of eigenmodes with 6 azimuthal periods\nalpha = [9.936109524217684,13.589290170541217,17.003819667816014,...\n 20.320789213566506,23.586084435581391,26.820151983411403];\n\n% choose radial mode\nalpha0 = alpha(2);\ntheta = atan2(y,x);\nrad = sqrt(x.^2+y.^2);\n\nEz = besselj(6, alpha0*rad).*cos(6*theta);\nHx = zeros(Np, K); Hy = zeros(Np, K);\n\n% Solve Problem for exactly one period\nFinalTime = .5;\n[Hx,Hy,Ez,time] = MaxwellCurved2D(Hx,Hy,Ez,FinalTime);\n\nexactEz = besselj(6, alpha0*rad).*cos(6*theta)*cos(alpha0*time(end));\nmaxabserror = max(max(abs(Ez-exactEz)))\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/MaxwellCurvedDriver2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7524767450873429}} {"text": "function K = exponential_correlation ( s, t )\n\n%*****************************************************************************80\n%\n%% EXPONENTIAL_CORRELATION evaluates the exponential correlation function.\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, real S(*), T(*), pairs of argument values.\n%\n% Output, real K(*), the correlation function values\n%\n K = exp ( - abs ( s - 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/correlation_chebfun/exponential_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7524187763617575}} {"text": "function I = intersectionHull(varargin)\n%intersectionHull - computes a bounded convex polyhedron resulting from the\n%intersection of other convex polyhedra. The other polyhedra need not individually\n%be bounded. Only the final intersection resulting from them must be bounded. \n%Any number of polyhedra can be input to the intersection operation. They can\n%be expressed using either vertices or linear in/equalities, according to\n%the input scheme,\n%\n%\n% I = intersectionHull('vert', V1, 'lcon', A2,b2, 'lcon', A3,b3,Aeq3,,beq3,...)\n%\n%The arguments specifying different polyhedra are separated using labels\n%'vert' and 'lcon'. The label 'vert' signifies that an input polyhedron will\n%be expressed using vertices and is to be followed by any string of input arguments \n%accepted by vert2lcon(). The label 'lcon' signifies that an input polyhedron will\n%be expressed using linear constraints and is to be followed by any string of \n%input arguments accepted by lcon2vert().\n%\n%The output, I, is a struct containing fields\n%\n% I.vert: A matrix whose rows are the vertices of the polyhedron formed from \n% the intersection.\n% I.lcon: The quadruplet of linear constraint data {A,b,Aeq,beq}\n% describing the polyhedral intersection.\n%\n%EXAMPLE 1: This example computes the intersection of a unit square and an \n%oblique 2D line segment, both expressed in terms of their vertices.\n% \n% V1=dec2bin(0:2^2-1,2)-'0'; %vertices of unit square\n% \n% V2=[1,1;0,-1]; %vertices of 2D line segment\n% \n% I=intersectionHull('vert',V1,'vert',V2); %compute intersection\n%\n%The intersection is another line segment with vertices\n%\n% >> I.vert \n% \n% ans =\n% \n% 0.5000 0\n% 1.0000 1.0000 \n% \n%EXAMPLE 2: This example computes the intersection of a unit cube, expressed in\n%terms of its vertices, and an infinite oblique 3D line, expressed in terms of linear equalities. \n%Note that the line is an unbounded polyhedron. This is okay, since we know in advance \n%that the final polyhedron formed from the intersection is bounded.\n% \n% V=dec2bin(0:2^3-1,3)-'0'; %vertices of unit cube\n% \n% Aeq=[1 -1 0; 0 1 -1]; beq=[0;0]; %oblique line in 3D\n% \n% I=intersectionHull('vert',V,'lcon',[],[],Aeq,beq); %compute intersection\n% \n%Once again, the intersection is a line segment. Its vertices are\n%\n% >> I.vert %vertices of line segment of intersection\n%\n% ans =\n% \n% 0.0000 0.0000 0.0000\n% 1.0000 1.0000 1.0000\n\n\n%%%%begin parsing\n\nif isnumeric(varargin{1})\n TOL=varargin{1};\n varargin(1)=[];\nelse\n TOL=[];\nend\n\nN=length(varargin);\nidxType = [find(cellfun(@ischar,varargin)),N+1];\n\nL=length(idxType)-1;\nS(L).type=[];\nS(L).args={};\nS(L).A=[];\nS(L).b=[];\nS(L).Aeq=[];\nS(L).beq=[];\n\nfor i=1:L\n \n j=idxType(i);\n k=idxType(i+1);\n S(i).type=varargin{j};\n S(i).args=varargin(j+1:k-1);\n \n if isempty(S(i).args)\n error 'Syntax error - arguments missing' \n end\n \n lcon=cell(1,4);\n \n switch S(i).type\n \n case 'vert'\n \n [lcon{1:4}] = vert2lcon(S(i).args{:}); \n \n case 'lcon'\n \n lcon(1:k-j-1) = S(i).args;\n \n case 'qlcon' %deliberately undocumented - no point in using this\n \n lcon(1:k-j-1) = S(i).args(2:end);\n \n otherwise\n \n error(['Unrecognized representation label of polyhedron ' num2str(i)]);\n \n end\n\n \n [S(i).A, S(i).b, S(i).Aeq, S(i).beq] = deal(lcon{:});\n \nend\n\n\n%%%%end parsing\n\n\n A=vertcat(S.A);\n b=vertcat(S.b); \n Aeq=vertcat(S.Aeq);\n beq=vertcat(S.beq); \n \n [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL);\n \n I.vert=V;\n I.lcon={A(nr,:),b(nr,:), Aeq(nre,:),beq(nre,:)};\n\n \n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/polytopes_2017_10_04_v1.9/intersectionHull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7523778209668731}} {"text": "%VL_NNBNORM CNN batch normalisation.\n% Y = VL_NNBNORM(X,G,B) applies batch normalization to the input\n% X. Batch normalization 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% sigma2(k) = mean_ijt (X(i,j,k,t) - mu(k))^2,\n% sigma(k) = sqrt(sigma2(k) + EPSILON)\n%\n% are respectively the per-channel mean, variance, and standard\n% deviation of each feature channel in the data X. The parameters\n% G(k) and B(k) are multiplicative and additive constants use to\n% scale each data channel.\n%\n% Means and variances are accumulated across all the data items\n% (images) stored in the 4D tensor X (from which the name batch\n% normalization is derived). The constant EPSILON is used to \n% regularize the computation of sigma(k) and to avoid division by \n% zero.\n%\n% [DZDX,DZDG,DZDB] = VL_NNBNORM(X,G,B,DZDY) computes the derviatives\n% of the block projected onto DZDY. DZDX, DZDG, DZDB and DZDY have\n% the same dimensions as X, G, B, and Y respectivey.\n%\n% Optionally, [Y,MOMENTS] = VL_NNBNORM(...) and\n% [DZDX,DZDG,DZDB,MOMENTS] = VL_NNBNORM(...,DZDY) return the values\n% of the vectors mu and sigma in the formulas above. Here, MOMENTS\n% is a DEPTH x 2 array [MU, SIGMA].\n%\n% VL_NNBNROM(..., 'Option', value) takes the following options:\n%\n% `Epsilon`:: 1e-4\n% Specifies the constant EPSILON in the formuals above.\n%\n% `Moments`:: unspecified\n% Specifies an array MOMENTS with the values of mu and sigma to\n% use instead of computing them according to the equations\n% above. This is useful to disable batch normalization during\n% testing.\n%\n% `CuDNN`:: specified\n% If specified, turns on CuDNN. CuDNN is on by default. This\n% option can be useful to undo the effect of a previous\n% `NoCuDNN` option in the argument list.\n%\n% `NoCuDNN`:: not specified\n% If specified, turns off CuDNN.\n%\n% See also: VL_NNNORMALIZE().\n\n% Copyright (C) 2015 Sébastien Ehrhardt, 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", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/libs/matconvnet/matlab/vl_nnbnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7523778165061104}} {"text": "function x = exponential_01_cdf_inv ( cdf )\n\n%*****************************************************************************80\n%\n%% EXPONENTIAL_01_CDF_INV inverts the Exponential 01 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 CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXPONENTIAL_01_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'EXPONENTIAL_01_CDF_INV - Fatal error!' );\n end\n\n x = - log ( 1.0 - cdf );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/exponential_01_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7523209057857585}} {"text": "function circular_arc ( xcenter, ycenter, radius, angmin, angmax )\n\n%*****************************************************************************80\n%\n%% CIRCULAR_ARC draws a circular arc of a given angular size and radius.\n%\n% Discussion:\n%\n% It is assumed that a plot has already been begun.\n%\n% Example:\n%\n% r = rand ( 100, 1 );\n% t = pi * rand ( 100, 1 );\n% plot ( r .* cos ( t ), r .* sin ( t ), 'b*' );\n% axis equal\n% axis square\n% circular_arc ( 0.0, 0.0, 1.0, 0, 180 );\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real XCENTER, YCENTER, the X and Y coordinates of\n% the center of the circle on which the arc lies.\n%\n% Input, real RADIUS, the radius of the circle on which the arc lies.\n%\n% Input, real ANGMIN, ANGMAX, the minimum and maximum\n% angles of the circle. ANGMIN and ANGMAX are both\n% measured in degrees. ANGMIN and ANGMAX determine the\n% portion of the circle to be drawn. If ANGMIN=0.0 and\n% ANGMAX=90.0, for instance, an arc of 90 degrees will be drawn.\n%\n color = [ 0.75, 0.75, 0.75 ];\n\n nval = 65;\n\n if ( radius == 0.0 )\n return\n end\n%\n% Set up the data defining the circular arc, using NVAL equally\n% spaced points along the circumference.\n%\n if ( nval == 1 )\n angle(1) = 0.5 * ( angmax + angmin );\n else\n angle(1:nval) = linspace ( angmin, angmax, nval );\n end\n\n xval(1:nval) = xcenter + radius * cos ( angle * pi / 180 );\n yval(1:nval) = ycenter + radius * sin ( angle * pi / 180 );\n\n line ( xval, yval, 'Color', color );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/gridlines/circular_arc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7522688824241623}} {"text": "% ir_denoise_test_sep1\n% Examine denoising with ordinary vs separable finite differences\n% i.e. |Ch X|_1 + |Cv X|_1 vs |Ch X Cv|_1\n% Uses ADMM algorithm to optimize denoising cost function.\n\nif ~isvar('yi'), printm 'generate noisy image'\n\txt = ellipse_im(2^7);\n\txt = zeros(2^6); xt(20:60,20:48) = 9;\n\tsig = 2^0; clim = [0 9];\n\n\tsnr = @(x) -20*log(norm(x(:)-xt(:)) / norm(xt(:)));\n\n\trng(7)\n\tyi = xt + sig * randn(size(xt));\n\n\tim plc 2 4\n\tim(1, xt, clim, 'True')\n\tim(2, yi, clim, 'Noisy')\n\txlabelf('SNR = %4.1f dB', snr(yi))\nend\n\n\nif ~isvar('Cs'), printm 'C2 and Cs'\n\targ.Ch = Cdiffs(size(xt,1), 'type_diff', 'circshift', 'offsets', 1);\n\targ.Cv = Cdiffs(size(xt,2), 'type_diff', 'circshift', 'offsets', 1);\n\tCs = fatrix2('arg', arg, 'idim', size(xt), 'odim', size(xt), ...\n\t\t'forw', @(arg, x) arg.Ch * x * arg.Cv, ... % separable!\n\t\t'back', @(arg, y) arg.Ch' * y * arg.Cv'); \n\tC2 = Cdiffs(size(xt), 'type_diff', 'circshift', 'offsets', '2d:hv');\n\n\tim(3, 'col', 1, C2 * xt, 'Usual'), cbar\n\tim(4, Cs * xt, 'Separable'), cbar\n\tdrawnow\nend\n\n\nif ~isvar('x2'), printm 'run admm with usual 2d finite differences'\n\t[x2s snr2] = ir_denoise_admm1(yi, 'beta', 2^+1, ...\n\t\t'stop_diff_tol', 1e-4, 'chat', 0, ...\n\t\t'isave', 'all', ...\n\t\t'userfun', @(x, iter) snr(x), ...\n\t\t'niter', 2^5, 'shrink', [], 'rho', 1);\n\tx2 = x2s(:,:,end);\nend\n\nif ~isvar('x1'), printm 'run admm with separable finite differences'\n\t[x1s snr1] = ir_denoise_admm1(yi, 'beta', 2^+1, ...\n\t\t'stop_diff_tol', 1e-4, 'chat', 0, ...\n\t\t'C', 'sep1', ...\n\t\t'isave', 'all', ...\n\t\t'userfun', @(x, iter) snr(x), ...\n\t\t'niter', 2^5, 'shrink', [], 'rho', 1);\n\tx1 = x1s(:,:,end);\nend\n\n\nif 1 % figures\n\tim(7, x2, clim, 'Denoised usual')\n\txlabelf('SNR = %4.1f dB', snr(x2))\n\tim(8, x1, clim, 'Denoised separ.')\n\txlabelf('SNR = %4.1f dB', snr(x1))\n\n%\tim subplot 5\n\tsubplot(223)\n\titers = 0:numel(snr1)-1;\n\tplot(iters, snr2, '-o', iters, snr1, '-x')\n\tsnr_lim = [floor(min([snr1; snr2])) ceil(max([snr1; snr2]))];\n\taxis([0 numel(iters) snr_lim])\n\tytick(snr_lim)\n\txlabelf 'ADMM iteration'\n\tylabelf 'SNR (dB)'\n\tlegend('usual', 'separable', 'location', 'southeast')\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/ir_denoise_test_sep1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7522688745532599}} {"text": "function [R, singular_values, determinants] = round_solution(Yopt, problem_data)\n%function [R, singular_values, determinants] = round_solution(Yopt, problem_data)\n%\n% Given an element Yopt in St(d, r)^n, this function rounds Yopt to an\n% element of SO(d)^n\n\n% Copyright (C) 2016 by David M. Rosen\n\n\nr = size(Yopt, 1);\n\n[U, Xi, V] = svd(Yopt, 'econ');\nsingular_values = diag(Xi)';\n\nXi_d = Xi(1:problem_data.d, 1:problem_data.d); %Xi_d is the upper-left dxd submatrix of Xi\nV_d = V(:, 1:problem_data.d); %V_d contains the first d columns of V\n\nR = Xi_d*V_d';\n\n\ndeterminants = zeros(1, problem_data.n);\n\nfor k = 1:problem_data.n\n determinants(k) = det(R(:, problem_data.d*(k-1) + 1 : problem_data.d*(k-1) + problem_data.d));\nend\nng0 = sum(determinants > 0);\n\nreflector = diag([ones(1, problem_data.d - 1), -1]); % Orthogonal matrix that we can use for reversing the orientations of the orthogonal matrix subblocks of R\n\nif ng0 == 0\n % This solution converged to a reflection of the correct solution\n R = reflector*R;\n determinants = -determinants;\nelseif ng0 < problem_data.n\n disp('WARNING: SOLUTION HAS INCONSISTENT ORIENTATIONS!');\n \n % If more than half of the determinants have negative sign, reverse\n % them\n if ng0 < problem_data.n / 2\n determinants = -determinants;\n R = reflector * R;\n end\nend\n\n% Finally, project each element of R to SO(d)\nfor i = 1:problem_data.n\n R(:, problem_data.d * (i-1) + 1 : problem_data.d *i) = project_to_SOd( R(:, problem_data.d * (i-1) + 1 : problem_data.d *i) );\nend\n\nend\n\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/lib/round_solution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7522688725855342}} {"text": "% laplac2d() - generate a 2 dimensional gaussian matrice\n%\n% Usage :\n% >> [ gaussmatrix ] = laplac2d( rows, columns, sigma, ...\n% meanR, meanC, cut)\n%\n% Example :\n% >> laplac2d( 5, 5)\n%\n% Inputs:\n% rows - number of rows \n% columns - number of columns \n% sigma - standart deviation (default: rows/5)\n% meanR - mean for rows (default: center of the row)\n% meanC - mean for columns (default: center of the column)\n% cut\t - percentage (0->1) of the maximum value for removing \n% values in the matrix (default: 0) \n%\n% Note: this function implements a simple laplacian for exploratory\n% research. For a more rigorous validated approach use the freely \n% available Current Source Density Matlab toolbox.\n%\n% See also: eeg_laplac()\n%\n% Author: Arnaud Delorme, CNL, Salk Institute, 2001\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction mat = laplac2d( sizeX, sizeY, sigma, meanX, meanY, cut);\n\nif nargin < 2\n\thelp laplac2d\n\treturn; \nend;\nif nargin < 3\n\tsigma = sizeX/5;\nend;\nif nargin < 4\n\tmeanX = (sizeX+1)/2;\nend;\nif nargin < 5\n\tmeanY = (sizeY+1)/2;\nend;\nif nargin < 6\n\tcut = 0;\nend;\n\nX = linspace(1, sizeX, sizeX)'* ones(1,sizeY);\nY = ones(1,sizeX)' \t\t * linspace(1, sizeY, sizeY);\n%[-sizeX/2:sizeX/2]'*ones(1,sizeX+1);\n%Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2];\n\nr2 = (X-meanX).*(X-meanX) + (Y-meanY).*(Y-meanY);\nsigma2 = sigma*sigma;\n\nmat = - exp(-0.5*r2/sigma2) .* ((r2 - sigma2)/(sigma2*sigma2)); \n% zeros crossing at r = -/+ sigma;\n% mat = r2;\nif cut > 0\n\tmaximun = max(max(mat))*cut;\n\tI = find(mat < maximun);\n\tmat(I) = 0;\nend;\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/eeglab14_0_0b/functions/miscfunc/laplac2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.824461919906883, "lm_q1q2_score": 0.7522688647330334}} {"text": "\n% Program_3c - The Mandelbrot Set in Color.\n% Program supplied by Steve Lord from The MathWorks.\n% Copyright Birkhauser 2013.\n\n% Define parameters\nNmax = 50; scale = 0.005;\nxmin = -2.4; xmax = 1.2;\nymin = -1.5; ymax = 1.5;\n\n% Generate X and Y coordinates and Z complex values\n[x,y]=meshgrid(xmin:scale:xmax, ymin:scale:ymax);\nz = x+1i*y;\n\n% Generate w accumulation matrix and k counting matrix\nw = zeros(size(z));\nk = zeros(size(z));\n\n% Start off with the first step ...\nN = 0;\n\n% While N is less than Nmax and any k's are left as 0 \nwhile N4 at this iteration and no\n % previous iteration get assigned the value of N\n k(~k & abs(w)>4) = N;\nend\n\n% If any k's are equal to 0 (i.e. the corresponding w's never blew up) set\n% them to the final iteration number\nk(k==0) = Nmax;\n\n% Open a new figure\nfigure\n\n% Display the matrix as a surface\ns=pcolor(x,y,k);\n\n% If you truly want the Mandelbrot curve in B&W, comment the above line and\n% uncomment these two\n% s = pcolor(x, y, mod(k, 2));\n% colormap([0 0 0;1 1 1])\n\n% Turn off the edges of the surface (because the cells are so small, the\n% edges would drown out any useful information if we left them black)\nset(s,'edgecolor','none')\n\n% Adjust axis limits, ticks, and tick labels\naxis([xmin xmax -ymax ymax])\nfontsize=15;\nset(gca,'XTick',xmin:0.4:xmax,'FontSize',fontsize)\nset(gca,'YTick',-ymax:0.5:ymax,'FontSize',fontsize)\nxlabel('Re z','FontSize',fontsize)\nylabel('Im z','FontSize',fontsize)\n\nkeyboard\nfigure\n\n% End of Probgram_3c.", "meta": {"author": "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_3c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7522216129830636}} {"text": "function sim = ImageSimilarity (im1, im2)\n% This function computes the \"similarity score\" between two images. You\n% should use the value for the similarity factor value when the two images\n% are assigned the same character.\n%\n% Input:\n% im1, im2: Two images from the provided dataset (they should be 16x8\n% matrices of 0s and 1s).\n%\n% Output:\n% sim: The similarity score of those images.\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\na = im1(:);\nb = im2(:);\n\nmeanSim = 0.283; % Avg sim score computed over held-out data.\n\ncosDist = (a' * b) / (norm(a) * norm(b));\n\ndiff = (cosDist - meanSim) ^ 2;\n\nif (cosDist > meanSim)\n sim = 1 + 5*diff;\nelse\n sim = 1 / (1 + 5*diff);\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/3.Markov Networks for OCR/ImageSimilarity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7522216109046544}} {"text": "function varargout = minimax(f, varargin)\n%MINIMAX Best polynomial or rational approximation for real valued\n% continuous functions. This code supersedes REMEZ. \n%\n% P = MINIMAX(F, M) computes the minimax polynomial approximation of\n% degree M to the real function F using the Remez algorithm. F can\n% be either a CHEBFUN, a function handle or a string representation\n% of the function to approximate. P is a CHEBFUN.\n%\n% [P, Q] = MINIMAX(F, M, N) computes the minimax rational approximation\n% P/Q of type (M, N). P and Q are CHEBFUNs, but in difficult cases\n% working with P/Q is numerically unstable.\n% \n% [P, Q, R_HANDLE] = MINIMAX(F, M, N) additionally returns a numerically\n% stable function handle for evaluating P/Q (based on a barycentric\n% representation).\n%\n% [...] = MINIMAX(..., [A, B]) takes the approximation domain to be\n% [A, B]. If a domain is not specified and F is a CHEBFUN, then the\n% domain of F is used. In all other cases, [-1, 1] is used.\n%\n% [...] = MINIMAX(..., 'tol', TOL) uses the value TOL as the termination\n% tolerance on the relative equioscillation error. The default is \n% approximately 1e-12 for polynomial approximation and 1e-4 for\n% rational approximation.\n%\n% [...] = MINIMAX(..., 'display', 'iter') displays output at each\n% iteration.\n%\n% [...] = MINIMAX(..., 'maxiter', MAXITER) sets the maximum number of\n% allowable iterations to MAXITER.\n%\n% [...] = MINIMAX(..., 'init', XK) allows the user to specify the vector\n% XK as the starting reference.\n%\n% [...] = MINIMAX(..., 'plot', 'on'), or equivalently \n% [...] = MINIMAX(..., 'plotfcns', 'error') plots the error after each\n% iteration while the algorithm executes.\n%\n% [...] = MINIMAX(..., 'silent') turns off all messages regarding the\n% execution of the algorithm.\n%\n% [P, ERR] = MINIMAX(...) and [P, Q, R_HANDLE, ERR] = MINIMAX(...)\n% return the maximum error estimate ERR.\n%\n% [P, ERR, STATUS] = MINIMAX(...) and [P, Q, R_HANDLE, ERR, STATUS] =\n% MINIMAX(...) return a structure array STATUS with the following fields:\n% STATUS.DELTA - Tolerance obtained.\n% STATUS.ITER - Number of iterations performed.\n% STATUS.DIFFX - Maximum correction in last trial reference.\n% STATUS.XK - Last trial reference on which the error\n% equioscillates.\n% In case we are doing rational approximation (denominator degree >=1),\n% two extra fields are computed:\n% STATUS.POL - Poles of the minimax approximation.\n% STATUS.ZER - Zeros of the minimax approximation.\n%\n% This code is highly reliable for polynomial approximation but may\n% sometimes have difficulties in the rational case, though we believe\n% it is the most powerful rational minimax code available.\n%\n% Examples:\n% x = chebfun('x'); f = abs(x);\n% p = minimax(f, 20); plot(f-p)\n% [p, q, rh] = minimax(f, 10, 10);\n% xx = linspace(-1,1,10000); plot(xx, f(xx)-rh(xx))\n%\n% References:\n%\n% [1] B. Beckermann, S. Filip, Y. Nakatsukasa and L. N. Trefethen,\n% \"Rational minimax approximation via adaptive barycentric\n% representations\", arXiv:1705.10132.\n%\n% [2] R. Pachon and L. N. Trefethen, \"Barycentric-Remez algorithms for\n% best polynomial approximation in the chebfun system\", BIT Numerical\n% Mathematics, 49:721-742, 2009.\n%\n% See also AAA, CF, CHEBPADE, PADEAPPROX, RATINTERP, POLYFIT, POLYFITL1.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( ~isa(f,'chebfun') ) % check if input is chebfun; if not, look for\n % splitting points\n dom = [];\n domIndex = 0;\n \n for k = 1:length(varargin) % look for domain\n if isfloat(varargin{k})\n if length(varargin{k}) == 2\n dom = varargin{k};\n domIndex = k;\n end\n end\n end\n \n if isempty(dom) % domain not provided, default to [-1,1]\n dom = [-1 1];\n else\n varargin(domIndex) = [];\n end\n if ( ischar(f) )\n fHandle = str2op(vectorize(f));\n else\n fHandle = f;\n end\n f = chebfun(f, dom, 'splitting', 'on');\nelse % f is a chebfun input\n fHandle = @(x) feval(f, x);\nend\n\nif ( ~isreal(f) )\n error('CHEBFUN:CHEBFUN:minimax:real', ...\n 'MINIMAX only supports real valued functions.');\nend\n\nif ( numColumns(f) > 1 )\n error('CHEBFUN:CHEBFUN:minimax:quasi', ...\n 'MINIMAX does not currently support quasimatrices.');\nend\n\n% Parse the inputs.\n[m, n, N, rationalMode, polyOutput, symFlag, xk, opts] = ...\n parseInputs(f, varargin{:});\n\n% If m = -1, this means f = odd and input (m,n) = (0,n); return constant 0. \nif ( m == -1 )\n q = chebfun(1, f.domain([1, end]));\n p = chebfun(0, f.domain([1, end]));\n varargout = {p, q, @(x) feval(p, x)./feval(q, x), norm(f,'inf'), []}; \n return\nend\n\nif ( isempty(xk) ) % no initial reference is given by the user\n % Several initialization attempts are made\n if ( n == 0 ) % polynomial case\n % Try Chebyshev points\n xk = chebpts(N + 2, f.domain([1, end]));\n [p,err,status] = minimaxKernel(f, fHandle,m, n, N, rationalMode,...\n xk, opts, 1);\n q = chebfun('1', f.domain([1, end]));\n if ( polyOutput )\n varargout = {p, err, status};\n else\n varargout = {p, q, p, err, status};\n end\n else % rational case\n % A first attempt is using CF as an initial guess \n try\n xk = cfInit(f, fHandle, m, n);\n [p,q,rh,err,status] = minimaxKernel(f, fHandle,m, n, N, ...\n rationalMode, xk, opts, 1);\n varargout = {p, q, rh, err, status};\n catch\n if ~opts.silentFlag\n disp(['CF-based initialization failed,' ...\n ' turning to AAA-Lawson...']);\n end\n status.success = 0; % CF didn't work\n end \n \n % If CF doesn't give a satisfactory answer, we try AAA-Lawson\n if ~status.success\n if ~opts.silentFlag\n disp('Trying AAA-Lawson-based initialization...');\n end\n xk = AAALawsonInit(f, fHandle, m, n);\n [p,q,rh,err,status] = minimaxKernel(f, fHandle, m, n, N, ...\n rationalMode, xk, opts, 1);\n varargout = {p, q, rh, err, status};\n end\n \n\n % A final attempt using cumulative distribution functions\n if ~status.success\n xk = cdfInit(f, fHandle, m, n, symFlag, opts, 1);\n [p,q,rh,err,status] = minimaxKernel(f, fHandle, m, n, N, ...\n rationalMode, xk, opts, 1);\n varargout = {p, q, rh, err, status}; \n end\n \n\n \n if ~status.success\n xk = cdfInit(f, fHandle, m, n, symFlag, opts, 2);\n [p,q,rh,err,status] = minimaxKernel(f, fHandle, m, n, N, ...\n rationalMode, xk, opts, 1);\n varargout = {p, q, rh, err, status};\n end\n \n if ~status.success % all attempts failed\n \terror('CHEBFUN:CHEBFUN:minimax:failure', ...\n ['MINIMAX failed to produce the best approximant. ' ...\n 'If the accuracy is close to machine precision, ' ...\n 'it may be that what you''ve asked for is unachievable ' ...\n 'in floating-point arithmetic. In such a case, try ' ...\n 'reducing the degree to get a clean best approximant.'])\n end\n end\nelse % the user has also given a starting reference\n if ( n == 0 )\n [p,err,status] = minimaxKernel(f, fHandle, m, n, N, ...\n rationalMode, xk, opts, 1);\n q = chebfun('1', f.domain([1,end]));\n if ( polyOutput )\n varargout = {p, err, status};\n else\n varargout = {p, q, p, err, status};\n end\n else\n [p,q,rh,err,status] = minimaxKernel(f, fHandle, m, n, N, ...\n rationalMode, xk, opts, 1);\n varargout = {p, q, rh, err, status};\n end\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Functions implementing the different initialization strategies\n\n% CF-based initialization\nfunction xk = cfInit(f, fHandle, m, n)\n warning off\n if ( numel(f.funs) == 1 )\n [p, q] = cf(f, m, n);\n pqh = @(x) feval(p, x)./feval(q, x);\n [xk, ~, ~, flag] = exchange([], 0, 2, f, fHandle, p, pqh, m+n+2, n);\n else\n try\n [p, q] = cf(f, m, n, 50*(m+n) );\n pqh = @(x) feval(p, x)./feval(q, x);\n [xk, ~, ~, flag] = exchange([], 0, 2, f, fHandle, p, pqh, ...\n m+n+2, n);\n catch ME % an error occured when calling cf (ignore it)\n flag = 0;\n end\n end\n warning on\n\n % If the above procedure failed to produce a reference\n % with enough oscillation points, use polynomial Remez.\n if ( flag == 0 )\n [~,~,status] = minimax(f, m+n); xk = status.xk;\n end\nend\n\n% Now turn to initialization via AAA-Lawson, this is more expensive than CF\n% but less so than CDF (which follows if this fails). \n% \nfunction xk = AAALawsonInit(f,fHandle, m,n) % AAA-Lawson initialization for\n % functions with breakpoints\n NN = max(10*max(m,n),round(1e5/max(m,n))); \n dom = domain(f);\n Z = linspace(dom(1), dom(end), NN); \n F = fHandle(Z);\n [r,~,~,~,xk] = aaamn_lawson(F, Z, m, n); % 1st AAA-Lawson \n xk = findReference(f, fHandle, r, m, n, xk);\n \n % Iterate twice during which sample points are refined. \n % This is done to find the nonsmooth parts of the function\n % and sample more densely there. \n for it = 1:2 % (maybe helps to run more)\n num = round(NN/length(xk)); \n Z = [];\n for ii = 1:length(xk)-1\n Z = [Z linspace(xk(ii), xk(ii+1),num)]; % equispaced sampling\n % between each pair of\n % reference pts\n end\n Z = unique(Z); Z = Z(:); F = feval(f, Z);\n [r,~,~,~,xk] = aaamn_lawson(F, Z, m, n); % Do AAA-Lawson with updated\n % sample pts\n xk = findReference(f, fHandle, r, m, n, xk); \n end \nend \n\n% Cumulative distribution function-based initialization of the rational\n% version of the exchange algorithm.\nfunction xk = cdfInit(f, fHandle, m, n, symFlag, opts, step)\n newlineCounter = 0;\n stepSize = step; % Increase in degree of numerator and/or denominator\n % at each step.\n if ( symFlag > 0 ) % Dealing with symmetry (even or odd).\n stepSize = 2*step;\n end\n if ~opts.silentFlag\n text = ['Trying CDF-based initialization with step size ', ...\n num2str(stepSize),'...'];\n disp(text);\n end\n \n % The approximation is close to being diagonal; start from an\n % approximation where both the numerator and denominator degrees\n % are decreased by the same value.\n if ( abs(m-n) <= 2 )\n minValue = min(m, n);\n minValue = minValue - rem(minValue, stepSize);\n k = minValue / stepSize;\n k = k - (3 - step);\n % Starting small degree problem.\n startM = m - stepSize * k;\n startN = n - stepSize * k;\n \n % We need an initialization strategy that has a high chance\n % of working without problem for the small degree case;\n % CF is used for now.\n xk = cfInit(f, fHandle, startM, startN);\n [~,~,~,~,status] = minimaxKernel(f, fHandle, startM, startN, ...\n startM+startN, true, xk, opts, 0);\n % If Remez worked on the small degree problem, start increasing\n % the degrees in both the numerator and denominator.\n if status.success \n while(startM < m - stepSize && (status.success == 1))\n startM = startM + stepSize;\n startN = startN + stepSize;\n newlineCounter = newlineCounter + 1;\n if(newlineCounter == 10)\n newlineCounter = 0;\n if ~opts.silentFlag\n fprintf('\\n');\n end\n end\n if ~opts.silentFlag\n fprintf('(%d,%d) ',startM, startN);\n end\n % Use the distribution information from the previous\n % reference to construct a starting reference for the new,\n % larger degree problem.\n xk = refGen(f, status.xk, startM + startN + 2, symFlag);\n [~,~,~,~,status] = minimaxKernel(f, fHandle, startM, ...\n startN, startM+startN, true, xk, ...\n opts, 0);\n end\n end\n \n\n if status.success\n xk = refGen(f, status.xk, m + n + 2, symFlag);\n if ~opts.silentFlag\n fprintf('(%d,%d)\\n',m, n);\n end\n else\n % There was a failure somewhere, use reference from polynomial\n % Remez (might work sometimes).\n if ~opts.silentFlag\n fprintf('\\n');\n text = ['Initialization failed using CDF with step', ...\n ' size ', num2str(stepSize) '...'];\n disp(text);\n end\n [~,~,status] = minimax(f, m+n); xk = status.xk;\n end\n else\n % Similar strategy to the diagonal case.\n if ( m < n )\n % Construct the 'corner' instance.\n % (m - stepSize*k, n - stepSize*k), where m - stepSize * k will\n % usually be 0 or 1.\n minValue = m - rem(m, stepSize);\n k = minValue / stepSize;\n hM = m - stepSize * k;\n hN = n - stepSize * k;\n \n % Now decrease the degree only in the denominator.\n hminValue = hN - rem(hN, stepSize);\n hk = hminValue / stepSize;\n startN = hN - stepSize * hk;\n xk = cfInit(f, fHandle, hM, startN);\n [~,~,~,~,status] = minimaxKernel(f, fHandle, hM, startN, ...\n hM+startN, true, xk, opts, 0);\n % Construct approximations by successively increasing the\n % denominator degree.\n if status.success \n while ( startN < hN - stepSize && status.success )\n startN = startN + stepSize; \n xk = refGen(f, status.xk, hM + startN + 2, 0);\n newlineCounter = newlineCounter + 1;\n if ( newlineCounter == 10 )\n newlineCounter = 0;\n if ~opts.silentFlag\n fprintf('\\n');\n end\n end\n if ~opts.silentFlag\n fprintf('(%d,%d) ',hM, startN);\n end\n [~,~,~,~,status] = minimaxKernel(f, fHandle, hM, ...\n startN, hM+startN, true, xk, ...\n opts, 0);\n end\n end\n \n if ~status.success\n [~,~,status] = minimax(f, hM + hN);\n end\n \n % Go to the initial degree by now simultaneously increasing\n % both numerator and denominator degree.\n status.success = 1; \n while ( hM < m - stepSize && status.success )\n hM = hM + stepSize;\n hN = hN + stepSize;\n xk = refGen(f, status.xk, hM + hN + 2, symFlag);\n newlineCounter = newlineCounter + 1;\n if(newlineCounter == 10)\n newlineCounter = 0;\n if ~opts.silentFlag\n fprintf('\\n');\n end\n end\n if ~opts.silentFlag\n fprintf('(%d,%d) ', hM, hN);\n end\n [~,~,~,~,status] = minimaxKernel(f, fHandle, hM, ...\n hN, hM+hN, true, ...\n xk, opts, 0);\n end\n \n if status.success\n xk = refGen(f, status.xk, m + n + 2, 0);\n if ~opts.silentFlag\n fprintf('(%d,%d)\\n', m, n);\n end\n else\n if ~opts.silentFlag\n fprintf('\\n');\n text = ['Initialization failed using CDF with ', ...\n 'step size ', num2str(stepSize)];\n disp(text);\n end\n [~,~,status] = minimax(f, m+n); xk = status.xk;\n end \n \n else % m > n\n % Construction of the 'corner' instance by decreasing the\n % degree in both numerator and denominator.\n minValue = n - rem(n, stepSize);\n k = minValue / stepSize;\n startM = m - stepSize * k;\n startN = n - stepSize * k;\n xk = cfInit(f, fHandle, startM, startN);\n [~,~,~,~,status] = minimaxKernel(f, fHandle, startM, ...\n startN, startM + startN, true, ...\n xk, opts, 0);\n \n if status.success \n while ( startM < m - stepSize && status.success )\n startM = startM + stepSize;\n startN = startN + stepSize;\n newlineCounter = newlineCounter + 1;\n if ( newlineCounter == 10 )\n newlineCounter = 0;\n if ~opts.silentFlag\n fprintf('\\n');\n end\n end\n if ~opts.silentFlag\n fprintf('(%d,%d) ', startM, startN);\n end\n xk = refGen(f, status.xk, startM + startN + 2, ...\n symFlag);\n [~,~,~,~,status] = minimaxKernel(f, fHandle, ...\n startM, startN, startM+startN, ...\n true, xk, opts, 0);\n end\n end\n \n if status.success\n xk = refGen(f, status.xk, m + n + 2, symFlag);\n if ~opts.silentFlag\n fprintf('(%d,%d)\\n', m, n);\n end\n else\n if ~opts.silentFlag\n fprintf('\\n');\n text = ['Initialization failed using CDF with ', ...\n 'step size ', num2str(stepSize)];\n disp(text);\n end\n [~,~,status] = minimax(f, m+n); xk = status.xk;\n end\n end\n end\n if ~opts.silentFlag\n fprintf('\\n');\n end\nend\n\nfunction varargout = minimaxKernel(f, fHandle, m, n, N, rationalMode, ...\n xk, opts, dialogFlag)\n\n% This core function should only ever be called with a nonempty initial set\n% of xk reference values\nnormf = opts.normf;\ndom = opts.dom;\n\n% If m = -1, this means f = odd and input (m,n) = (0,n); return constant 0. \nif ( m == -1 && dialogFlag)\n q = chebfun(1, dom);\n p = chebfun(0, dom);\n varargout = {p, q, @(x) feval(p, x)./feval(q, x), norm(f,inf), []}; \n return\nelseif ( m == -1 )\n q = [];\n p = [];\n varargout = {p, q, [], [], []}; \n return\nend\n\n% With zero denominator degree, the denominator polynomial is trivial.\nif ( n == 0 )\n q = chebfun(1, dom);\nend\n\n% Initial values for some parameters.\niter = 0; % Iteration count.\ndelta = max(normf, eps); % Value for stopping criterion.\ndeltamin = inf; % Minimum error encountered.\ndiffx = 1; % Maximum correction to trial reference\n\nxo = xk;\n\n% Print header for text output display if requested.\nif ( opts.displayIter && dialogFlag)\n disp('It. Max(|Error|) |ErrorRef| Delta ErrorRef Delta Ref m n')\nend\n\nerr = normf;\n% Initialise the levelled error such that one iteration always executes\nh = 2*err + 1;\ninterpSuccess = 1;\n% Run the main algorithm.\nwhile ( (abs(abs(h)-abs(err))/abs(err) > opts.tol) && ...\n (iter < opts.maxIter) && (diffx > 0) && interpSuccess )\n hpre = h;\n % Approximation error is at the level of machine precision, stop.\n if ( abs(abs(h)-abs(err))/normf < 1e-14 )\n break\n end\n % Compute trial function and levelled reference error.\n if ( n == 0 )\n fk = fHandle(xk); % Evaluate on the exchange set.\n w = baryWeights(xk); % Barycentric weights for exchange set.\n [p, h] = computeTrialFunctionPolynomial(fk, xk, w, m, N, dom);\n \n % Perturb exactly-zero values of the levelled error.\n if ( h == 0 )\n h = 1e-19;\n end\n \n rh = @(x) 0;\n % Update the exchange set using the Remez algorithm\n % with full exchange rule.\n [xk, err, err_handle, ~] = exchange(xk, h, 2, f, fHandle, p, ...\n rh, N + 2, n);\n \n % If overshoot, recompute with one-point exchange rule.\n if ( err/normf > 1e5 )\n [xk, err, err_handle, ~] = exchange(xo, h, 1, f, fHandle, ...\n p, rh, N + 2, n);\n end\n \n % Update max. correction to trial reference and stopping criterion.\n diffx = max(abs(xo - xk));\n delta = err - abs(h);\n \n % Store approximation with minimum norm.\n if ( delta < deltamin )\n pmin = p;\n errmin = err;\n xkmin = xk;\n deltamin = delta;\n end\n \n else\n err = inf;\n [p, q, rh, h, interpSuccess, tk, alpha, beta] = ...\n computeTrialFunctionRational(f, fHandle, xk, m, n, hpre, ...\n dialogFlag, opts.silentFlag);\n \n % Perturb exactly-zero values of the levelled error.\n if ( h == 0 )\n h = 1e-19;\n end\n \n if(interpSuccess == 1)\n [xk, err, err_handle, ~] = exchange(xk, h, 2, f, fHandle, ...\n p, rh, N+2, n);\n diffx = max(abs(xo - xk));\n delta = err - abs(h);\n \n if opts.tol*norm(err_handle(xk),inf) < normf*1e-14\n % Relative tolerance below machine precision, make it\n % reasonable.\n opts.tol = normf*1e-13/norm(err_handle(xk),inf);\n opts.tol = min(opts.tol, 0.1);\n end\n end\n end\n \n % Display diagnostic information as requested.\n if ( opts.plotIter && interpSuccess && dialogFlag )\n doPlotIter(xo, xk, err_handle, h, dom);\n end\n \n if ( opts.displayIter && dialogFlag )\n doDisplayIter(iter, err, h, delta, normf, diffx, m, n);\n end\n \n xo = xk;\n iter = iter + 1;\nend\n \nif ( n == 0 )\n % Take best results of all the iterations we ran.\n p = pmin;\n err = errmin;\n xk = xkmin;\n delta = deltamin;\nend\n \n% Warn the user if we failed to converge.\nif ( abs(abs(h)-abs(err))/abs(err) > opts.tol && ...\n abs(abs(h)-abs(err))/normf >= 1e-14 && dialogFlag && interpSuccess )\n warning('CHEBFUN:CHEBFUN:minimax:convergence', ...\n ['minimax algorithm did not converge after ', num2str(iter), ...\n ' iterations to the tolerance ', num2str(opts.tol), '.']);\nend\n \n% Form the outputs.\nstatus.delta = delta/normf;\nstatus.iter = iter;\nstatus.diffx = diffx;\nstatus.xk = xk;\nstatus.success = interpSuccess;\n% Compute the poles and zeros in case of a rational approximation\nif status.success && dialogFlag && rationalMode\n [status.zer, status.pol] = pzeros(tk, alpha, beta, rh, m, n, dom);\nelse\n status.zer = []; status.pol = [];\nend\n \nif( ~isempty(p))\n p = simplify(p);\nend\nif ( rationalMode )\n varargout = {p, q, rh, err, status};\nelse\n varargout = {p, err, status};\nend\n\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input parsing.\n\nfunction [m, n, N, rationalMode, polyOutput, symFlag, xk, opts] = ...\n parseInputs(f, varargin)\n\nopts.silentFlag = 0;\nisSilent = 0;\nfor k = 1:length(varargin)\n if ( ischar(varargin{k}) && strcmpi('silent', varargin{k}) )\n opts.silentFlag = k;\n isSilent = 1;\n end\nend\n\nif opts.silentFlag\n varargin(opts.silentFlag) = [];\nend\n\n% Detect polynomial / rational approximation type and parse degrees.\npolyOutput = true;\nif ( ~mod(nargin - isSilent, 2) ) % Even number of inputs --> polynomial\n % case.\n m = varargin{1};\n n = 0;\n rationalMode = false;\n symFlag = 0;\n varargin = varargin(2:end);\nelse % Odd number of inputs --> rational case.\n polyOutput = false;\n [m, n, symFlag] = adjustDegreesForSymmetries(f, varargin{1}, ...\n varargin{2});\n if ( n == 0 )\n rationalMode = false;\n else\n rationalMode = true;\n end\n varargin = varargin(3:end);\nend\n\nN = m + n;\n\n% Parse name-value option pairs.\nif rationalMode\n opts.tol = 1e-4; % Relative tolerance for deciding\n % convergence.\n opts.maxIter = 10+round(max(m,n)/2); % Maximum number of allowable\n % iterations.\nelse\n opts.tol = 1e-14*(N^2 + 10); % Polynomial case is much more robust. \n opts.maxIter = 30; % Maximum number of allowable iterations.\nend\n\nopts.displayIter = false; % Print output after each iteration.\nopts.plotIter = false; % Plot approximation at each iteration.\nopts.dom = f.domain([1, end]);\nopts.normf = norm(f);\nxk = [];\n\nfor k = 1:2:length(varargin)\n if ( strcmpi('tol', varargin{k}) )\n opts.tol = varargin{k+1};\n elseif ( strcmpi('maxiter', varargin{k}) )\n opts.maxIter = varargin{k+1};\n elseif ( strcmpi('display', varargin{k}) )\n opts.displayIter = true;\n elseif ( strcmpi('plotfcns', varargin{k}) )\n opts.plotIter = true;\n elseif ( strcmpi('plot', varargin{k}) )\n opts.plotIter = true;\n elseif ( strcmpi('init', varargin{k}) )\n xk = varargin{k+1};\n else\n error('CHEBFUN:CHEBFUN:minimax:badInput', ...\n 'Unrecognized sequence of input parameters.')\n end\nend\n\nend\n\nfunction [m, n, symFlag] = adjustDegreesForSymmetries(f, m, n)\n%ADJUSTDEGREESFORSYMMETRIES Adjust rational approximation degrees to\n% account for function symmetries.\n%\n% [M, N] = ADJUSTDEGREESFORSYMMETRIES(F, M, N) returns new degrees M and\n% N to correct the defect of the rational approximation if the target\n% function is even or odd. In either case, the Walsh table is covered\n% with blocks of size 2x2, e.g. for even function the best rational\n% approximant is the same for types [m/n], [m+1/n], [m/n+1] and\n% [m+1/n+1], with m and n even. This strategy is similar to the one\n% proposed by van Deun and Trefethen for CF approximation in Chebfun\n% (see @chebfun/cf.m).\n\n% Sample piecewise-smooth CHEBFUNs.\nif ( (numel(f.funs) > 1) || (length(f) > 128) )\n f = chebfun(f, f.domain([1, end]), 128);\nend\n\n% Assume no symmetry at the outset.\nsymFlag = 0;\n% Compute the Chebyshev coefficients.\nc = chebcoeffs(f, length(f));\nc(1) = 2*c(1);\n\n% Check for symmetries and reduce degrees accordingly.\nif ( max(abs(c(2:2:end)))/vscale(f) < eps ) % f is even.\n symFlag = 1;\n if ( mod(m, 2) == 1 )\n m = max(m - 1, 0);\n end\n if ( mod(n, 2) == 1 )\n n = max(n - 1, 0);\n end\nelseif ( max(abs(c(1:2:end)))/vscale(f) < eps ) % f is odd.\n symFlag = 2;\n if ( ~mod(m, 2) )\n m = m - 1;\n end\n if ( mod(n, 2) )\n n = n - 1;\n end\nend\n\nend\n\nfunction [p, h] = computeTrialFunctionPolynomial(fk, xk, w, m, N, dom)\n\n% Vector of alternating signs.\nsigma = ones(N + 2, 1);\nsigma(2:2:end) = -1;\n\nh = (w'*fk) / (w'*sigma); % Levelled reference error.\npk = (fk - h*sigma); % Vals. of r*q in reference.\n\n% Trial polynomial.\np = chebfun(@(x) bary(x, pk, xk, w), dom, m + 1);\n\nend\n\nfunction [p, q, rh, h, interpSuccess,xsupport, wN, wD] = ...\n computeTrialFunctionRational(f, fHandle, xk, m, n, hpre, ...\n dialogFlag, silentFlag)\n% computeTrialFunctionRational finds a rational approximation to f at an \n% iteration of the Remez algorithm. It uses a barycentric representation\n% for improved numerical stability. \n% f: function \n% xk: approximate reference points\n% m,n: type\n% hpre: levelled error at the previous iteration\n\n% The function values at the current reference points\nfk = fHandle(xk);\n% Take barycentric support points to be alternating values of two\n% reference points\n xsupport = xk(2:2:end);\n xsuppind = 2:2:length(xk);\n xadd = xk(1:2:end);\n xother = xadd; \n xotherind = 1:2:length(xk);\n \nif m~=n % need to add more support points\n xadd = xother;\n % take Leja points from the remaining ref pts and add\n [xadd, ~] = leja(xadd, 1, length(xadd)); \n xsupport = [xsupport;xadd(1:max(m,n)+1-length(xsupport))]; \n xother = zeros(m+n+2-max(m,n)-1,1); \n xotherind = zeros(m+n+2-max(m,n)-1,1); \n xsuppind = zeros(max(m,n)+1,1);\n \n iother = 1; isupp = 1;\n for ii = 1:length(xk) % keep indices for later use\n if ~ismember(xk(ii),xsupport)\n xother(iother) = xk(ii);\n xotherind(iother) = ii;\n iother = iother+1;\n else\n xsuppind(isupp) = ii;\n isupp = isupp+1;\n end\n end \n \nend\n xsupport = sort(xsupport,'ascend');\n \nif m~=n\n % projection matrices that force coefficients to lie in null space \n % of Vandermonde matrix\n % projection subspace\n Qmn = orthspace(xsupport,abs(m-n),ones(length(xsupport),1)); \n [Qmnall,~] = qr(Qmn); \nend\n\n C = 1./bsxfun(@minus,xk,xsupport.'); % Cauchy matrix\n\n % form matrix Cstar = sqrt(|Delta|)*C \n % Cstar(ii,jj) = |wt(xi)/sqrt(wx'(xi))|/(xi-tj) \n Xkdiff = abs(bsxfun(@minus, xk, xk.'));\n Xkdiff(eye(size(Xkdiff))~=0) = 1; % inf to 0\n Xtdiff = abs(bsxfun(@minus, xother, xsupport.'));\n ST = sum(log(Xtdiff.')); SX = sum(log(Xkdiff));\n VV = exp(ST.'-0.5*SX(xotherind).');\n VV = VV*ones(1,length(xsupport));\n Div = bsxfun(@minus,xother,xsupport.');\n C1 = VV./Div; % odd columns of Cstar\n\n % diag elements Cstar(ii,jj) = |wt(xi)/sqrt(wx'(xi))|/(xi-tj) \n Xtdiff = abs(bsxfun(@minus, xsupport, xsupport.'));\n Xtdiff(eye(size(Xtdiff))~=0) = 1;\n ST = sum(log(Xtdiff.'));SX = sum(log(Xkdiff));\n C2 = diag(exp(ST.'-0.5*SX(xsuppind).'));\n Cstar = [C1;C2];\n Cstar(xsuppind,:) = C2;\n Cstar(xotherind,:) = C1; \n \n% prepare QR factorizations; these lead to a symmetric eigenproblem\n% we need to be careful how to do QR as rows have\n% large dynamical range (though orthogonal columns when m=n) \n% do Householder QR with row sorting, better than [Q,R] = qr(Cstar,0);\nif ( m == n )\n nrm = zeros(1, size(Cstar, 1));\n for ii = 1:length(nrm)\n nrm(ii) = norm(Cstar(ii,:));\n end\n [~,ix] = sort(nrm, 'descend');\n %[~,ix] = sort(norms(Cstar'), 'descend');\n [Q,R] = qr(Cstar(ix,:),0);\n ixx(ix) = 1:length(ix); Q = Q(ixx,:); \n \n %{\n nrm = zeros(1,m+1); % Cholesky QR with col-scaling, this works too\n for ii = 1:m+1, nrm(ii) = norm(Cstar(:,ii)); end\n Cstar = Cstar/diag(nrm); % this normalized Cstar is orthogonal\n CTC = Cstar'*Cstar; \n R = chol(CTC); Q = Cstar/R; R = R*diag(nrm);\n %}\nelseif ( m > n )\n nrm = zeros(1, size(Cstar, 1));\n for ii = 1:length(nrm)\n nrm(ii) = norm(Cstar(ii,:));\n end\n [~,ix] = sort(nrm, 'descend');\n %[~,ix] = sort(norms(Cstar'),'descend');\n [Q,R] = qr(Cstar(ix,:)*Qmn,0); \n [Qall,Rall] = qr(Cstar(ix,:)*Qmnall,0); \n ixx(ix) = 1:length(ix); \n Q = Q(ixx,:); Qall = Qall(ixx,:); \n \nelse % m n )\n alpha = Qmnall*((Rall)\\((Qall'*diag(-fk)*Q*VR)));\nelse % m1e-7);\n\nif isempty(pos) % Unfortunately, no solution with same signs.\n % Try old remez.\n\n% Take barycentric support points to be alternating values of two\n% reference points\nxsupport = (xk(1:2:end-1)+xk(2:2:end))/2; \nxadd = (xk(2:2:end-1)+xk(3:2:end))/2; % when m~=n, we need more support\n % points\n\nif ismember(f.domain(1),xk) == 0 % if endpoints aren't included,\n % add them\n xadd = [(f.domain(1)+xk(1))/2;xadd]; \nend\nif ismember(f.domain(end),xk) == 0\n xadd = [(f.domain(end)+xk(end))/2;xadd];\nend\nnum = abs((max(m,n)+1-length(xsupport)));\n[xadd, ~] = leja(xadd, 1, num); % take Leja points from the\n % remaining ref pts\n\nif m~=n\n % add any lacking supp pts\n xsupport = [xsupport;xadd(1:max(m,n)+1-length(xsupport))];\nend\nxsupport = sort(xsupport, 'ascend');\n\nC = 1./bsxfun(@minus,xk,xsupport.');\n\n% find Delta diag matrix \nDelta = zeros( 1,length(xk) );\nfor ii = 1:length(xk) \n% wt(ii) = prod(xk(ii)-xsupport);\n% wxdiff(ii) = prod(xk(ii)-xk([1:ii-1 ii+1:end])); \n% Delta = diag(-(wt.^2)./wxdiff); do in a way that avoids\n% underflow, overflow\n Delta(ii) = -exp(2*sum(log(abs(prod(xk(ii)-xsupport)))) ...\n - sum(log(abs(xk(ii)-xk([1:ii-1 ii+1:end])))));\nend\nDelta = diag(Delta); \n\n%DD = diag(1./norms(sqrt(abs(Delta))*C)); % scaling, might help stability\nDD = eye(size(C,2));\n\n% prepare QR factorizations; these lead to symmetric eigenproblem\nif ( m == n )\n [Q,R] = qr(sqrt(abs(Delta))*C,0);\nelseif ( m > n )\n [Q,R] = qr(sqrt(abs(Delta))*C*Qmn,0); \n [Qall,Rall] = qr(sqrt(abs(Delta))*C*Qmnall,0);\nelse % m n )\n alpha = Qmnall*((Rall)\\((Qall'*diag(-fk)*Q*VR)));\nelse % m1e-4); \n \nif isempty(pos) % still no solution, give up\n if ( dialogFlag && ~silentFlag )\n disp('Trial interpolant too far from optimal...')\n end\n interpSuccess = 0; \n p = []; q = []; rh = []; h = 1e-19; wD = []; wN = [];\n return\nelseif ( length(pos) > 1 ) % more than one solution with no sign changes...\n [~,ix] = min(abs(hpre)-diag(abs(d(pos,pos))));\n pos = pos(ix);\nend\n\nend \n\nh = -d(pos, pos); % levelled reference error.\n\n% coefficients for barycentric representations\nif ( m <= n )\n wD = vt(m+2:end,pos);\nelse\n wD = Qmn*vt(m+2:end,pos); \nend\nif ( m >= n )\n wN = vt(1:m+1,pos);\nelse\n wN = Qmn*vt(1:m+1,pos); \nend\n\nD = @(x) 0; N = @(x) 0; % form function handle rh = N/D \nfor ii = 1:length(xsupport)\n D = @(x) D(x) + wD(ii)./(x-xsupport(ii));\n N = @(x) N(x) + wN(ii)./(x-xsupport(ii)); \nend\nD = @(x)-D(x); % flip back sign\n\nrh = @(zz) reval(zz, xsupport, N, D, wN, wD);\n\ninterpSuccess = 1; % declare success\n\n% Form chebfuns of p and q (note: could be numerically unstable, but\n% provided for convenience).\n% Find values of node polynomial at Chebyshev points\nif dialogFlag\n x = chebpts(m+n+1,f.domain([1,end]));\n nodex = zeros(length(x),1);\n for ii = 1:length(x) \n nodex(ii) = node(x(ii)); \n end \n qvals = nodex.*feval(D,x); % Values of p and q at Chebyshev points\n pvals = nodex.*feval(N,x);\n % If certain Chebyshev points map to support points, inf values will\n % get propagated, so we need to handle them separately\n for ii = 1:length(xsupport)\n for jj = 1:length(x)\n if x(jj) == xsupport(ii)\n nodei = 1.0;\n for kk = 1:length(xsupport)\n if ~(kk == ii)\n nodei = nodei * (x(jj) - xsupport(kk)); \n end\n end\n qvals(jj) = -nodei*wD(ii);\n pvals(jj) = nodei*wN(ii);\n end\n end\n end\n \n p = chebfun(pvals,f.domain([1,end]));\n q = chebfun(qvals,f.domain([1,end]));\n p = simplify(p); q = simplify(q);\nelse\n p = [];\n q = [];\nend\n\nend\n\nfunction r = reval(zz, xsupport, N, D, wN, wD)\nzv = zz(:);\nr = N(zv)./D(zv);\nii = find(isnan(r));\nfor jj = 1:length(ii)\n if ( isnan(zv(ii(jj))) || ~any(zv(ii(jj)) == xsupport) )\n % r(NaN) = NaN is fine.\n % The second case may happen if r(zv(ii)) = 0/0 at some point.\n else\n % Clean up values NaN = inf/inf at support points.\n % Find the corresponding node and set entry to correct value:\n pos = zv(ii(jj)) == xsupport; \n r(ii(jj)) = -wN(pos)./wD(pos);\n end \nend\nr = reshape(r, size(zz));\nend\n\nfunction [xx, pos] = leja(x, startIndex, nPts) \n% put NPTS from X in a Leja sequence\n% starting from x(startIndex)\nn = length(x);\np = zeros(n,1);\npos = zeros(nPts, 1);\nxx = zeros(nPts, 1);\nxx(1) = x(startIndex); \npos(1) = startIndex;\n\nfor j = 2:nPts\n % we want to pick the jth point now:\n for i = 1:n\n %p(i) = prod(abs(x(i) - xx(1:j-1)));\n p(i) = sum(log(abs(x(i) - xx(1:j-1)))); % no overflow\n end \n [~,pos(j)] = max(p);\n xx(j) = x(pos(j));\nend\n\nend\n\n\nfunction [xk, norme, err_handle, flag] = exchange(xk, h, method, f, ...\n fHandle, p, rh, Npts, n)\n%EXCHANGE Modify an equioscillation reference using the Remez algorithm.\n% EXCHANGE(XK, H, METHOD, F, P, RH, NPTS, N) performs one step of the\n% Remez algorithm for the best rational approximation of the CHEBFUN F\n% of the target function according to the first method (METHOD = 1),\n% i.e., exchanges only one point, or the second method (METHOD = 2),\n% i.e., exchanges all the reference points. XK is a column vector with\n% the reference, H is the levelled error, P is the numerator, and RH is a\n% function handle, NPTS is the required number of alternation points,\n% and N is the denominator degree.\n%\n% [XK, NORME, E_HANDLE, FLAG] = EXCHANGE(...) returns the modified\n% reference XK, the supremum norm of the error NORME (included as an\n% output argument, since it is readily computed in EXCHANGE and is used\n% later in MINIMAX), a function handle E_HANDLE for the error, and a FLAG\n% indicating whether there were at least N+2 alternating extrema of the\n% error to form the next reference (FLAG = 1) or not (FLAG = 0).\n\n% Compute extrema of the error.\nif(n == 0) % polynomial case\n % Function handle output for evaluating the error.\n rh = @(x) feval(p,x);\n rr = findExtrema(f, fHandle, rh, xk);\n err_handle = @(x) fHandle(x) - feval(p, x);\nelse % Rational case.\n rr = findExtrema(f, fHandle, rh, xk);\n err_handle = @(x) fHandle(x) - rh(x);\nend\n\n% Select exchange method.\nif ( method == 1 ) % One-point exchange.\n [~, pos] = max(abs(feval(err_handle, rr)));\n pos = pos(1);\nelse % Full exchange.\n pos = find(abs(err_handle(rr)) >= abs(h)); % Values above levelled\n % error.\nend\n\n% Add extrema nearest to those which are candidates for exchange to the\n% existing exchange set.\n[r, m] = sort([rr(pos) ; xk]);\nv = ones(Npts, 1);\nv(2:2:end) = -1;\ner = [feval(err_handle, rr(pos)) ; v*h];\ner = er(m);\n\n% Delete repeated points.\nrepeated = diff(r) == 0;\nr(repeated) = [];\ner(repeated) = [];\n\n% Determine points and values to be kept for the reference set.\ns = r(1); % Points to be kept.\nes = er(1); % Values to be kept.\nfor i = 2:length(r)\n if ( (sign(er(i)) == sign(es(end))) && (abs(er(i)) > abs(es(end))) )\n % Given adjacent points with the same sign, keep one with largest\n % value.\n s(end) = r(i);\n es(end) = er(i);\n elseif ( sign(er(i)) ~= sign(es(end)) )\n % Keep points which alternate in sign.\n s = [s ; r(i)]; %#ok\n es = [es ; er(i)]; %#ok\n end\nend\n\n\n\n% Of the points we kept, choose n + 2 consecutive ones that include the\n% maximum of the error.\n[norme, index] = max(abs(es));\nd = max(index - Npts + 1, 1);\nif ( Npts <= length(s) )\n xk = s(d:d+Npts-1);\n flag = 1;\nelse\n xk = s;\n flag = 0;\nend\n\nend\n\nfunction rts = findExtrema(f, fHandle, rh,xk)\n% Finds all the local maxima and minima of f-rh.\n% xk is the present reference\n% rh is a handle to p/q\n\nerr_handle = @(x) fHandle(x) - rh(x);\n\ndoms = unique([f.domain'; xk]).';\ndoms = sort(doms,'ascend');\n\n% Initial trial\nif ( isempty(xk) )\nsample_points = linspace(f.domain(1),f.domain(end),5000);\nscale_of_error = norm(err_handle(sample_points),inf);\nrelTol = 1e-15 * (vscale(f)/scale_of_error); \n warning off\n ek = chebfun(@(x) err_handle(x), f.domain, 'eps', relTol, ...\n 'splitting', 'on');\n warning on\n rts = roots(diff(ek), 'nobreaks');\nelse\n nn = 2^3; % sampling pts in each subinterval (try low number first)\n mid = (doms(1:end-1)+doms(2:end))/2; % midpoints\n rad = (doms(2:end)-doms(1:end-1))/2; % radius\n xx = ones(nn+1,1)*mid+cos(pi*((nn:-1:0).')/nn)*rad; % sample matrix\n valerr = feval(f,xx)-rh(xx);\n rts = zeros(5*length(xk),1);\n pos = 1;\n for k = 1:length(doms)-1 \n rnow = rootsdiff(valerr(:,k),[doms(k) doms(k+1)],err_handle);\n rts(pos:pos+length(rnow)-1) = rnow; % update reference points\n pos = pos+length(rnow);\n end \n rts(pos:end) = [];\nend\n\n% Append end points of the domain.\nrts = unique([f.domain' ; rts]);\nrts = sort(rts,'ascend');\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Find extrema of error function in AAA-Lawson\nfunction xk = findReference(f,fHandle,r,m,n,z) \n % f: function \n % r: rational approximant \n % m,n: (m,n) is the type of our rational approximant\n % z: barycentric support points \n % OUTPUT: reference points xk\n \n % Find extrema points as usual.\n xk = findExtrema(f,fHandle, r, sort(z,'ascend'));\n \n % Deal with length(xk) not equal to the desired m+n+2.\n if length(xk) > m+n+2 % Reduce reference pts becuse too many found. \n \n xkdiff = diff(xk); \n [~,ix] = sort(xkdiff,'descend'); % Take those with largest gaps.\n xk = [xk(1);xk(1+ix(1:m+n+1))];\n xk = sort(xk,'ascend'); \n elseif length(xk) < m+n+2 % Increase # of reference pts\n % if too few found. \n\n xkdiff = diff(xk); \n add = m+n+2-length(xk); % We need to add this many reference\n % points. \n % Take those with largest gaps and fill midpoints.\n [~,ix] = sort(xkdiff,'descend');\n xk = [xk;(xk(ix(1:add))+xk(ix(1:add)+1))/2];\n xk = sort(xk,'ascend');\n end \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Functions for displaying diagnostic information.\n\n% Function called when opts.plotIter is set.\nfunction doPlotIter(xo, xk, err_handle, h, dom)\n\nxxk = linspace(dom(1), dom(end), 10000);\nplot(xo, err_handle(xo), 'or', 'MarkerSize', 4) % Old reference.\nholdState = ishold;\nhold on\nplot(xk, err_handle(xk), '*k', 'MarkerSize', 4) % New reference.\nplot(xxk, err_handle(xxk)) % Error function.\nplot(xxk, ones(size(xxk))*h,'r');\nplot(xxk, -ones(size(xxk))*h,'r');\nif ( ~holdState ) % Return to previous hold state.\n hold off\nend\nxlim(dom)\nerr = norm(err_handle(xk),'inf');\nylim(2*[-err,err])\nlegend('Current Ref.', 'Next Ref.', 'Error')\ndrawnow\nend\n\n% Function called when opts.displayIter is set.\nfunction doDisplayIter(iter, err, h, delta, normf, diffx, m, n)\n\ndisp([num2str(iter,'%3g'), ' ', num2str(err, '%5.4e'), ' ', ...\n num2str(abs(h), '%5.4e'), ' ', ...\n num2str(delta/normf, '%5.4e'), ' ', num2str(diffx, '%5.4e'),...\n ' ', num2str(m, '%4g'),' ', num2str(n, '%4g')])\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Functions used by the CDF-based initialization routine\n\n% Constructs a piecewise linear function which interpolates the data\n% (xd(i), yd(i)) when i goes from 1 to length(xd). It then computes\n% the value of this piecewise linear approximation at the xi nodes\n% (ni is the number of xi nodes)\nfunction yi = pwiselin(xd, yd, ni, xi)\n\n nd = length(xd);\n xd = xd(:);\n yd = yd(:);\n xi = xi(:);\n\n if ( nd == 1 )\n yi(1:ni,1) = yd;\n return\n end\n\n [~, ~,k] = histcounts(xi, xd);\n\n k ( k == 0 ) = 1;\n k ( k == nd ) = nd - 1;\n\n t = ( xi - xd(k,1) ) ./ ( xd(k+1,1) - xd(k,1) );\n yi = ( 1 - t ) .* yd(k) + t .* yd(k+1);\n \n return\nend\n\n% Generate a set of n reference points which follow a distribution\n% of the xk nodes. The symType flag tells us if we are dealing with\n% an even or odd function, in which case the new reference nodes are\n% taken to be symmetric with respect to the middle of the approximation\n% domain\nfunction nxk = refGen(f, xk, n, symType)\n\nxx = linspace(-1,1,length(xk));\n\nif(symType == 0)\n\n nxk = pwiselin(xx, xk, n, linspace(-1,1,n));\n\n% handling of even symmetries\n\nelseif(symType == 1)\n\n halfSize = length(xx)/2;\n halfn = n/2;\n\n\n if (xk(1) == f.domain(1))\n nxk = pwiselin(xx(halfSize+1:end), xk(halfSize+1:end),halfn, ...\n linspace(xx(halfSize+1),xx(end),halfn));\n nxk = [nxk; -nxk(2:end); f.domain(1)];\n nxk = sort(nxk,'ascend');\n elseif (xk(end) == f.domain(end))\n nxk = pwiselin(xx(1:halfSize), xk(1:halfSize),halfn, ...\n linspace(xx(1),xx(halfSize),halfn));\n nxk = [nxk; -nxk(1:end-1); f.domain(end)];\n nxk = sort(nxk,'ascend');\n else\n nxk = pwiselin(xx, xk, n, linspace(-1,1,n));\n end\n\n% handling of odd symmetries\nelse\n\nhalfSize = (length(xx)-1) / 2;\nhalfn = (n-1)/2;\n\n if (xk(1) == f.domain(1))\n nxk = pwiselin(xx(halfSize+2:end), xk(halfSize+2:end),halfn, ...\n linspace(xx(halfSize+2),xx(end),halfn));\n nxk = [nxk; -nxk(1:end); f.domain(1)];\n nxk = sort(nxk,'ascend');\n elseif (xk(end) == f.domain(end))\n nxk = pwiselin(xx(1:halfSize+1), xk(1:halfSize+1),halfn, ...\n linspace(xx(1),xx(halfSize+1),halfn));\n nxk = [nxk; -nxk(1:end); f.domain(end)];\n nxk = sort(nxk,'ascend');\n else\n nxk = pwiselin(xx, xk, n, linspace(-1,1,n));\n end\n\nend\n\nend\n\n\n\nfunction [r, pol, res, zer, z, Z, f, w, wf, errvec, p, q] = ...\n aaamn_lawson(F, varargin)\n%AAAMN_Lawson near-best rational approximation of F. \n% \n% R = aaamn_lawson(F) computes a rational aproximant of (default) type\n% (10,10) on the default interval [-1,1]\n%\n% [R, POL, RES, ZER] = aaamn_lawson(...) outputs the poles, residues and\n% zeros of R. The poles, zeros will approximate those of F (not well if\n% R-F is not small)\n% \n% [R, POL, RES, ZER, z, Z, F, W,WF, ERRVEC, P, Q] = aaamn_lawson(...) \n% outputs additionally the sample points Z, support points z, values\n% F=f(Z), weights w and wf (see below) and AAA errvec, and p,q = chebfuns \n% s.t. r= p/q (note this can be numerically unstable)\n%\n% [...] = aaamn_lawson(F,m,n) specifies the type to (m,n).\n%\n% [...] = aaamn_lawson(F,Z,m,n) also specifies the sample points Z\n% (recommended). \n%\n% [...] = aaamn_lawson(F,Z,m,n,'plot','on') will plot the error functions\n% as the Lawson iterations proceed. \n%\n% [...] = aaamn_lawson(F,m,n,'dom',[-1,2]) specifies the domain (this has\n% no effect if Z is specified)\n%\n% [...] = aaamn_lawson(F,m,n,'tol',1e-5) specifies the Lawson iterate\n% relative stopping criterion (here to 1e-5)\n%\n% [...] = aaamn_lawson(F,m,n,'iter',10) limits the Lawson maximum\n% iterations to 10. \n% \n% \n% The algorithm first finds a AAA rational approximant to F \\approx r(Z),\n% then attempts to refine the approximant by a Lawson process, i.e. an\n% iterative reweighting. \n% \n% This code is designed for computing good reference points for the\n% rational minimax code to follow, but can be used independently for\n% constructing a rational approximation r that can be much closer than AAA\n% to the best rational approximant. \n%\n% Input: Z = vector of sample points\n% F = vector of data values, or a function handle\n% m, n: max type is (m,n), set to 10 if omitted\n% tol = relative tolerance tol, default: 1e-13 \n% Lawsoniter: max. iteration number of Lawson updates (default 10)\n% doplot: 1 to plot error curve history (default 0)\n% R = AAAMN_Lawson(F, Z, m, n, NAME, VALUE) sets the following\n% parameters:\n% - 'tol', TOL: relative tolerance for Lawson\n% iteration (default 1e-5)\n% - 'iter', IT: maximal number of Lawson iterations\n% (default MMAX = max([5 min([20, m, n])])).\n% \n% Output: r = AAA-Lawson approximant to F (function handle)\n% pol,res,zer = vectors of poles, residues, zeros\n% errvec = vector of errors at each step\n% z,f,w,wf = vectors of support pts, function values, weights\n% s.t. r = N/D, N(x) = sum_i wf(i)/(x-z(i)) and \n% D(x) = sum_i w(i)/(x-z(i)).\n% p,q = chebfuns s.t. r= p/q (note this can be numerically unstable)\n%\n% Examples:\n% r = aaamn_lawson(@abs,10,10)\n% r = aaamn_lawson(@abs,10,10,'plot','on')\n% [r, pol, res, zer, z, f, w, wf, errvec, p, q] = aaamn_lawson(@abs,...\n% 10,10,'plot','on','dom',[-1 2])\n% r = aaamn_lawson(@exp,4,2,'plot','on','dom',[-1 2])\n% r = aaamn_lawson(@(x)log(1.1-x),5,5,'plot','on')\n%\n% f = chebfun(@(x)-1./(log(abs(x)).^2),[-.1,.1],'splitting','on'); \n% [r,pol,res] = aaamn_lawson(f,linspace(-.1,.1,1e4),18,18,'plot','on')\n%\n%\n\n% parse inputs\n[F, Z, m, n, Lawsoniter, tolLawson, doplot, tol ] = ...\n parseInputslawson(F, varargin{:});\n\nM = length(Z); % number of sample points\nmmax = m+1; nmax = n+1; % for coding convenience\nif ( (nargin < 6) || isempty(Lawsoniter) ) % number of Lawson updates\n Lawsoniter = max([5 min([20,mmax,nmax])]); \nend \nif ~isfloat(F), F = feval(F,Z); end % convert function handle to\n % vector\n Z = Z(:); F = F(:); % work with column vectors\n SF = spdiags(F,0,M,M); % left scaling matrix\n J = 1:M; % indices that are not support\n % pts\n z = []; f = []; C = []; % initializations\n errvec = []; R = mean(F); \nfor mn = 1:max(mmax,nmax)\n [~,j] = max(abs(F-R)); % select next support point\n z = [z; Z(j)]; % update set of support points\n f = [f; F(j)]; % update set of data values\n J(J==j) = []; % update index vector\n C = [C 1./(Z-Z(j))]; % next column of Cauchy matrix\n Sf = diag(f); % right scaling matrix\n A = SF*C - C*Sf; % Loewner matrix\n \n if ( mn > min(nmax,mmax) ) % nondiagonal case, find projection\n % subspace \n if mmax < nmax\n q = f(:);\n else\n q = ones(length(z),1);\n end\n Q = orthspace(z,mn-min(mmax,nmax),q); % projection subspace \n [~,~,V] = svd(A(J,:)*Q,0); % SVD on projected\n % subspace\n w = Q*V(:,end);\n else \n [~,~,V] = svd(A(J,:),0); % SVD, no projection\n % needed\n w = V(:,mn); % weight vector \n end \n wf = w.*f;\n N = C*(w.*f); D = C*w; % numerator and denominator\n R = F; R(J) = N(J)./D(J); % rational approximation\n err = norm(F-R,inf);\n errvec = [errvec; err]; % max error at sample points\n if ( err < tol*norm(F,inf) ), break, end % stop if converged\nend\n r = @(zz) feval(@rrint,zz,z,w,f); % AAA approximant as\n % function handle\n Rori = R;\n \n% now start Lawson, in this mode we leave interpolation and work with\n% 'alpha-beta' mode. \n wei = ones(length(J),1);\n nrmbest = inf;\n if ( mn > min(nmax,mmax) ) % Deal with projection for m neq n \n if mn>nmax\n A =[SF*C*Q -C]; \n else % need to redefine Q as not the same as AAA above \n q = ones(length(z),1);\n Q = orthspace(z,mn-min(mmax,nmax),q); % projection\n % subspace \n A =[SF*C -C*Q]; \n end\n else\n A =[SF*C -C]; % diagonal case\n end\n \n rate = 1; % default Lawson rate, will shrink if not\n % converging\n nrmincreased = 0; % initialization \n\t for it = 1:Lawsoniter\n weiold = wei; \n wei = wei .* power(abs(F(J)-R(J)),rate); % update Lawson\n % weights\n wei = wei/sum(wei); % normalize \n if norm(weiold-wei)/norm(wei)< tolLawson % declare Lawson\n % converged\n break\n end\n % diagonal weight matrix\n D = spdiags(sqrt(wei),0,length(wei),length(wei));\n\n [~,~,V] = svd(D*A(J,:),0); % weighted least-squares via SVD\n \n if ( mn > min(nmax,mmax) ) % deal with nondiagonal case\n if ( mn > nmax )\n w = Q*V(1:nmax,end); wf = V(nmax+1:end,end); \n else\n w = V(1:nmax,end); wf = Q*V(nmax+1:end,end); \n end\n else\n w = V(1:mn,end); wf = V(mn+1:2*mn,end); \n end \n f = wf./w; % for compatibility with\n % interpolatory-aaa \n N = C*wf; D = C*w; % numerator and denominator \n R = F; R(J) = N(J)./D(J); % rational approximation\n err = norm(F-R,inf); \n errvec = [errvec; err]; % max error at sample points \n if ( err < nrmbest ) % adopt best so far\n nrmbest = norm(F-R,'inf'); \n weibest = wei; % store best weight\n r = @(zz) feval(@rrab,zz,z,w,wf,f); % AAA approximant as\n % function handle\n else\n nrmincreased = nrmincreased + 1;\n end\n if ( nrmincreased >= 3 ) % perhaps not converging,\n rate = max( rate/2,0.01 ); % make Lawson update conservative\n if doplot\n warning(['Lawson rate made conservative to ',num2str(rate)])\n end\n nrmincreased = 0; \n end\n\n if doplot % plot error functions\n % (hopefully near-equioscillating)\n subplot(2,1,1)\n plot(Z,F-Rori,'r.','markersize',8)\n title('AAA error')\n grid on, hold on\n if exist('hh','var')\n set(hh,'color',(0.8)*[1 1 1]); \n end\n subplot(2,1,2)\n title('AAA-Lawson error')\n hh = plot(Z,F-R,'k.','markersize',8); \n grid on, hold on\n h2 = plot(z,0*z,'m.','markersize',12);\n ylim(err*[-1 1]); drawnow, shg \n if ( it == Lawsoniter ) % plot best function \n plot(Z,F-r(Z),'b.','markersize',10);\n end\n end \n\t end \n\n % compute poles and roots\n B = eye(mn+1); B(1,1) = 0; \n E = [0 wf.'; ones(mn,1) diag(z)]; \n zer = eig(E,B); zer = zer(~isinf(zer)); % zeros \n E = [0 w.'; ones(mn,1) diag(z)]; \n pol = eig(E,B); pol = pol(~isinf(pol)); % poles\n dz = 1e-5*exp(2i*pi*(1:4)/4);\n res = r(bsxfun(@plus,pol,dz))*dz.'/4; % residues\n \n if ( nargout > 8 ) % form p and q via N/D, NOTE: not always stable\n D = @(x) 0; N = @(x) 0; % form r=N/D in barycentric form\n for ii = 1:length(z)\n D = @(x) D(x) + w(ii)./(x-z(ii));\n N = @(x) N(x) + wf(ii)./(x-z(ii)); \n end\n dom = [min(real(Z)) max(real(Z))]; % set domain\n x = chebpts(mmax+nmax+1,dom);\n node = @(x) prod(x-z); % needed to check sign\n nodex = zeros(length(x),1); % setup node values \n for ii = 1:length(x), nodex(ii) = node(x(ii)); end\n qvals = nodex.*feval(D,x); % values of p,q\n pvals = nodex.*feval(N,x);\n p = chebfun(pvals,dom); q = chebfun(qvals,dom); % form chebfuns \n end\nend \n\n\n% parse Inputs for Lawson:\n\nfunction [F, Z, m, n, Lawsoniter, tolLawson, doplot, tol ] = ...\n parseInputslawson(F, varargin)\n% Input parsing for AAAmn_lawson.\n\n% Check if F is empty:\nif ( isempty(F) )\n error('CHEBFUN:aaamn_lawson:emptyF', 'No function given.')\nelseif ( isa(F, 'chebfun') )\n if ( size(F, 2) ~= 1 )\n error('CHEBFUN:aaamn_lawson:nColF', ...\n 'Input chebfun must have one column.')\n end\nend\n\n% Domain:\nif ( isa(F, 'chebfun') )\n dom = F.domain([1, end]);\nelse\n dom = [-1, 1];\nend\n\n% Sample points:\nif ( ~isempty(varargin) && isfloat(varargin{1}) )\n if length(varargin{1})>2 % sample points Z given. \n Z = varargin{1};\n varargin(1) = []; \n else % sample points not given.\n \n end\nend\n\n% m,n\nif ( ~isempty(varargin) && isfloat(varargin{1}) )\n if length(varargin{1})>1 % input (f,Z,[m n])\n mn = varargin{1};\n m = mn(1); n = mn(2);\n varargin(1) = []; \n elseif isfloat(varargin{2}) % input (f,Z,m,n)\n m = varargin{1}; \n n = varargin{2}; \n varargin([1, 2]) = [];\n else\n m = varargin{1}; \n n = m; % input (f,Z,m), default to diagonal type (m,m)\n varargin(1) = [];\n end\nend\n\nif ( ~exist('m', 'var') ) \n warning(['CHEBFUN:aaamn_lawson: type (m,n) not specified,', ...\n ' default to (10,10)'])\n m = 10; n = 10; \nend\n\n% Set defaults for other parameters:\ntolLawson = 1e-5; % Relative tolerance for\n % Lawson update.\ntol = 1e-15; % AAA tolerance\nLawsoniter = max([5 min([20, m, n])]); % Maximum number of terms.\ndoplot = 0; % Don't plot intermediate functions\n % unless specified\n\n% Check if parameters have been provided:\nwhile ( ~isempty(varargin) )\n if ( strncmpi(varargin{1}, 'tol', 3) || ...\n strncmpi(varargin{1}, 'tolLawson', 3) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n tolLawson = varargin{2}; % Lawson tolerance\n end\n varargin([1, 2]) = [];\n\n elseif ( strncmpi(varargin{1}, 'iter', 4) || ...\n strncmpi(varargin{1}, 'maxit', 5))\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 1]) )\n Lawsoniter = varargin{2}; % maximum Lawson iterations\n else\n warning(['CHEBFUN:aaamn_lawson:iter unspecified,', ...\n ' use default itermax ', num2str(Lawsoniter)])\n end\n varargin([1, 2]) = [];\n \n elseif ( strncmpi(varargin{1}, 'dom', 3) )\n if ( isfloat(varargin{2}) && isequal(size(varargin{2}), [1, 2]) )\n dom = varargin{2};\n end\n varargin([1, 2]) = [];\n if ( isa(F, 'chebfun') )\n if ( ~isequal(dom, F.domain([1, end])) )\n warning('CHEBFUN:aaamn_lawson:dom', ...\n ['Given domain does not match the domain ', ...\n 'of the chebfun.\\n', 'Results may be inaccurate.'])\n end\n end\n \n elseif strncmpi(varargin{1}, 'plot', 4) % plot error functions\n if isfloat(varargin{2})\n doplot = varargin{2};\n elseif ( strncmpi(varargin{2}, 'true', 4) || ...\n strncmpi(varargin{2}, 'on', 2) )\n doplot = 1;\n end\n varargin([1, 2]) = []; \n else\n error('CHEBFUN:aaamn_lawson:UnknownArg', 'Argument unknown.')\n end\nend\n\n% Deal with Z and F:\nif ( ~exist('Z', 'var') && isfloat(F) )\n % F is given as data values, pick same number of sample points:\n Z = linspace(dom(1), dom(2), length(F)).';\nend\n\nif ( exist('Z', 'var') )\n % Work with column vector:\n Z = Z(:);\n M = length(Z);\n \n % Function values:\n if ( isa(F, 'function_handle') || isa(F, 'chebfun') )\n % Sample F on Z:\n F = F(Z);\n elseif ( isnumeric(F) )\n % Work with column vector and check that it has correct length.\n F = F(:);\n if ( length(F) ~= M )\n error('CHEBFUN:aaamn_lawson:lengthFZ', ...\n 'Inputs F and Z must have the same length.')\n end\n else\n error('CHEBFUN:aaamn_lawson:UnknownF', ...\n 'Input for F not recognized.')\n end\n \nelse\n % Z was not given. Set flag that Z needs to be determined.\n % Also set Z and M since they are needed as output.\n % in AAA this is done adaptively. This can be done with Lawson, but\n % probably safe to take as many points as reasonably possible here. \n Z = linspace(dom(1), dom(end), 4000).'; \nend\n\nend % End of PARSEINPUT().\n\n\n% generate function handle, interpolatory mode\nfunction r = rrint(zz,z,w,f) % evaluate r at zz\nzv = zz(:); % vectorize zz if necessary\nCC = 1./bsxfun(@minus,zv,z.'); % Cauchy matrix \nr = (CC*(w.*f))./(CC*w); % AAA approx as vector\nii = find(isnan(r)); % Find values NaN = 0/0 if any\nfor j = 1:length(ii)\n r(ii(j)) = f(find(zv(ii(j))==z)); % Force interpolation there\nend\nr = reshape(r,size(zz)); % AAA approx\nend\n\n% generate function handle, non-interpolatory mode\nfunction r = rrab(zz,z,w,wf,f) % evaluate r at zz\nzv = zz(:); % vectorize zz if necessary\nCC = 1./bsxfun(@minus,zv,z.'); % Cauchy matrix \nr = (CC*(wf))./(CC*w); % AAA approx as vector\n\nii = find(isnan(r)); % Find values NaN = 0/0 if any\nfor j = 1:length(ii)\n r(ii(j)) = f(find(zv(ii(j))==z)); % Force interpolation there\nend\n\nr = reshape(r,size(zz)); % AAA approx\nend\n\n% find null space for nondiagonal case m~=n\nfunction Q = orthspace(z,dim,q) % orthonormal projection space for (m,n)\nif ( dim == 0 ), Q = eye(length(z)); end \nif ( nargin < 3 ), q = ones(length(z),1); end\n Q = q/norm(q);\n for ii = 2:dim % orthogonal complement via\n % Lanczos-type process\n Qtmp = diag(z)*Q(:,end);\n Qtmp = Qtmp - Q*(Q'*Qtmp); % orthogonalize\n Qtmp = Qtmp - Q*(Q'*Qtmp); % orthogonalize again (CGS2) \n Qtmp = Qtmp/norm(Qtmp); % normalize\n Q = [Q Qtmp]; \n end\n [Q,~] = qr(Q); Q = conj(Q(:,dim+1:end)); % desired null space\nend\n\nfunction r = rootsdiff(vals,dom,err_handle) % vals is either a function or\n % values at chebpts\n% returns the roots of diff(vals) via ChebyshevU-colleague\nif length(vals)<=1\nif nargin<3, n = 2^5; end \nxx = chebpts(n+1,dom); \nvals = vals(xx);\nelse \nn = size(vals,1)-1;\nend\n\ntol = 1e-3; % no need for high tolerance\nc = 1; % initialize\nwhile ( (abs(c(end)/c(1))>tol) && (n<=2^6) )% sample until happy\ncc = fft([vals(end:-1:1);vals(2:end-1)])/n;\ncc(1) = cc(1)/2;\nc = real(cc(1:n+1)); % coeffs of f=err_handle in T\ncU = c(2:end).*(1:length(c)-1).'; % coeffs of df in U\n% simplify; no need to get full accuracy.\n% Then reorder to highest coeffs first. \nlen = max( find((abs(cU)/norm(cU)>1e-14)) ); cU = flipud(cU(1:len)); \n%if ( length(cU)<=1 || norm(cU./max(abs(cU)))<1e-14 ), r = []; return; end\n% constant function\nif ( length(cU)<=1 ), r = []; return; end\nif abs(c(end)/c(1))>tol % resample at finer grid\n n = 2*n;\n vals = feval(err_handle,(dom(1)+dom(end))/2 + ...\n cos(pi*((n:-1:0).')/n)*(dom(end)-dom(1))/2);\nend\nend\n\nif length(cU)<=1, r = []; return; end % constant function\n\nif (length(cU)==2)\n % degree 1 polynomial: just take the root\n ei = -cU(2)/(2*cU(1));\n % remove root if outside domain\n ei = ei(abs(ei)<=1+1e-7);\nelse\n % now construct colleague matrix for ChebyshevU\n oh = ones(len-2,1)/2;\n C = diag(oh,1) + diag(oh,-1);\n cU = -cU(2:end)/cU(1)/2;cU(2) = cU(2)+.5;\n C(1,:) = cU.';\n ei = eig(C);\n % remove irrelevant roots\n ei = real(ei(abs(imag(ei))<1e-5 & abs(ei)<=1+1e-7)); \nend\nr = (dom(1)+dom(2))/2 + ei*(dom(2)-dom(1))/2; % map back to the subinterval\nend\n\n% Compute the poles zeros of the barycentric approximant with\n% weights alpha and beta.\nfunction [zer, pol] = pzeros(zj, alpha, beta, rh, m, n, dom)\n\nif ( n == 0 || isempty(beta) )\n pol = [];\nelse\n l = length(beta);\n\n % Compute poles via generalized eigenvalue problem:\n B = eye(l+1);\n B(1,1) = 0;\n E = [0 beta.'; ones(l, 1) diag(zj)];\n pol = eig(E, B);\n % Remove zeros of denominator at infinity:\n pol = pol(~isinf(pol));\n\n rad = 1e-5; % radius for approximating residual\n\n if ( l - 1 > n )% superdiagonal case, remove irrelevant poles \n dz = rad*exp(2i*pi*(1:4)/4);\n res = rh(bsxfun(@plus, pol, dz))*dz.'/4; % residues\n ix = find( abs(res) > 1e-10 ); % pole with suff. residues\n pol = pol(ix); \n zerBern = abs(pol-dom(1)) + abs(pol-dom(2)); % Bernstein ellipse radius\n [~,ix] = sort( zerBern, 'ascend'); % sort wrt radius\n pol = pol( ix(1:min(n,end)) ); % choose <=n zeros with largest residues \n end\nend\n\nif ( m == 0 && isempty(alpha) )\n zer = [];\nelse\n l = length(alpha);\n \n % Compute zeros via generalized eigenvalue problem:\n B = eye(l+1);\n B(1,1) = 0;\n E = [0 alpha.'; ones(l, 1) diag(zj)];\n \n zer = eig(E,B);\n % Remove zeros of numerator at infinity:\n zer = zer(~isinf(zer));\n \n % subdiagonal case, remove irrelevant zeros:\n if ( l - 1 > m )\n rad = 1e-5; % radius for approximating derivative\n dz = rad*exp(2i*pi*(1:4)/4);\n deriv = sum(abs(bsxfun(@minus,rh(zer),rh(dz))./bsxfun(@minus,zer,dz)),2);\n deriv = deriv/4;\n ix = find( abs(deriv) > 1e-10 );\n \n zer = zer(ix);\n zerBern = abs(zer-dom(1)) + abs(zer-dom(2));\n [~,ix] = sort(zerBern,'ascend');\n zer = zer( ix(1:min(m,end)) );\n end\n \nend\n\nend % End of PZEROS().\n\nfunction op = str2op(op)\n % Convert string inputs to either numeric format or function_handles.\n sop = str2num(op);\n if ( ~isempty(sop) )\n op = sop;\n else\n depVar = symvar(op);\n if ( numel(depVar) ~= 1 )\n error('CHEBFUN:CHEBFUN:str2op:indepvars', ...\n 'Incorrect number of independent variables in string input.');\n end\n op = eval(['@(' depVar{:} ')', op]);\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/minimax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.7521238561811986}} {"text": "function f = p40_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P40_F evaluates the objective function for problem 40.\n%\n% Discussion:\n%\n% There is a typo in the reference. I'm just guessing at the correction.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the argument of the objective function.\n%\n% Output, real F, the value of the objective function.\n%\n f = x(1)^2 + 2.0 * x(2)^2 ...\n - 0.3 * cos ( 3.0 * pi * x(1) ) ...\n + cos ( 4.0 * pi * x(2) ) + 0.3;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p40_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7521063077158785}} {"text": "function jac = p19_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P19_JAC evaluates the jacobian for problem p19.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n jac = zeros ( neqn, neqn );\n\n d = ( sqrt ( ( y(1).^2 + y(2).^2 ) ) ).^5;\n\n jac(1,3) = 1.0;\n jac(2,4) = 1.0;\n jac(3,1) = ( 2.0 * y(1).^2 - y(2).^2 ) / d;\n jac(3,2) = 3.0 * y(1) * y(2) / d;\n jac(4,1) = 3.0 * y(1) * y(2) / d;\n jac(4,2) = ( - y(1).^2 + 2.0 * y(2).^2 ) / d;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_ode/p19_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7520903360862684}} {"text": "function p = betaScores(r)\n%BETASCORES Compute Beta scores for rank vector\n% p = BETASCORES(r) \n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n% INPUTS:\n% r vector of normalized rank values on interval [0,1]\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n% OUTPUTS:\n% p a vector of p-values that corresponds to the sorted input \n% vector. The NaN-s are moved to the end.\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n% See also CORRECTBETAPVALUES, THRESHOLDBETASCORE, AGGREGATERANKS.\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n% Copyright (2013) Nejc Ilc \n% Based on R package RobustRankAggreg written by Raivo Kolde. \n% Reference:\n% Kolde, R., Laur, S., Adler, P., & Vilo, J. (2012).\n% Robust rank aggregation for gene list integration and meta-analysis.\n% Bioinformatics, 28(4), 573-580\n% \n% Revision: 1.0 Date: 2013/05/16\n%--------------------------------------------------------------------------\n n = sum(~isnan(r));\n p = nan(1,length(r));\n % Sort the values.\n r = sort(r);\n % Get the order statistics and calculates p-values for each of the\n % order statistics. These are based on their expected distribution\n % under the null hypothesis of uniform distribution.\n p(1:n) = betacdf(r(1:n),1:n,n:-1:1);\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/src/betaScores.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7520892003172678}} {"text": "% Copyright (C) 2010 Quan Wang \n% Signal Analysis and Machine Perception Laboratory\n% Department of Electrical, Computer, and Systems Engineering\n% Rensselaer Polytechnic Institute, Troy, NY 12180, USA\n\n%% A demo showing how to use this package for binary classification\n% f: (n0+n1)*2 feature matrix, each row being a data point\n% l0: (n0+n1)*1 ground truth of binary label vector, each element being 0 or 1\n% l: (n0+n1)*1 resulting binary label vector, each element being 0 or 1\nclear;clc;close all;\n\nn0=100;\nn1=100;\n\nl0=[zeros(n0,1);ones(n1,1)];\nf=[l0+randn(n0+n1,1),l0+randn(n0+n1,1)];\n\n[w,t,fp]=fisher_training(f,l0);\n[l,precision,recall,accuracy,F1]=fisher_testing(f,w,t,l0);\n\n%% visualization\nfigure;\nplot(f(1:n0,1),f(1:n0,2),'bo','MarkerSize',10);\nhold on;\nplot(f(n0+1:end,1),f(n0+1:end,2),'rs','MarkerSize',10);\ngrid on;\n\nxx=-2:0.1:3;\nyy=-w(1)/w(2)*xx+t/w(2);\nplot(xx,yy,'-.k','LineWidth',2);\ntitle('data points and classification border');\nlegend('label 0','label 1','class border');\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42785-binary-fisher-lda/BinaryFisherLDA/Matlab/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7520891910858819}} {"text": "function c_jac = cheb2jac( c_cheb, alpha, beta ) \n%CHEB2JAC Convert Chebyshev coefficients to Jacobi coefficients. \n% C_JAC = CHEB2LEG(C_CHEB, A, B) converts the vector C_CHEB of Chebyshev\n% coefficients to a vector C_JAC of Jacobi coefficients such that \n% C_CHEB(1)*T_0(x) + ... + C_CHEB(N)*T{N-1}(x) = ...\n% C_LEG(1)*P_0^{(A,B)}(x) + ... + C_LEG(N)*P{N-1}^{(A,B)}(x),\n% where P_k^{(A,B)} is the degree k Jacobi polynomial corresponding to the\n% weight function w(x) = (1-X)^A * (1+X)^B.\n%\n% See also JAC2CHEB, JAC2JAC.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%% For developers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% For more information on the algorithm for N>512, see Section 5.3 of \n% \n% A. Townsend, M. Webb, and S. Olver, \"Fast polynomial transforms based on \n% Toeplitz and Hankel matrices\", submitted, 2016. \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nN = size(c_cheb, 1); % Length of coefficients. \n\nif ( alpha == 0 && beta == 0 ) \n % Use cheb2leg for alpha = beta = 0:\n \n c_jac = cheb2leg( c_cheb ); \n \nelseif ( alpha == -.5 && beta == -.5 ) \n % Undo scaling: \n \n % Convert T_n -> P_n^(-1/2,1/2): \n scl = [1 cumprod((1/2:1/2+N-2)./(1:N-1))]'; % P_n^(-1/2,-1/2)(1)\n c_jac = spdiags( scl, 0, N, N) \\ c_cheb; \n \nelseif ( N <= 512 ) \n \n c_jac = cheb2jac_direct(c_cheb, alpha, beta);\n \nelse\n % Convert Chebyshev to Jacobi (-1/2,-1/2) and then call jac2jac: \n \n % Convert T_n -> P_n^(-1/2,1/2): \n scl = [1 cumprod((1/2:1/2+N-2)./(1:N-1))]'; % P_n^(-1/2,-1/2)(1)\n c_jac = spdiags( scl, 0, N, N) \\ c_cheb; \n % Now convert P_n^(-1/2,-1/2) -> P_n^(alpha,beta): \n c_jac = jac2jac( c_jac, -1/2, -1/2, alpha, beta );\n\nend\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% DIRECT METHOD %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction c_jac = cheb2jac_direct(c_cheb, a, b)\n%CHEB2JAC_DIRECT Convert Cheb to Jacobi (A,B) coeffs using direct method.\n\n[N, m] = size(c_cheb); % Number of columns.\nN = N - 1; % Degree of polynomial.\n% Don't let N be too big:\n\nif ( N <= 0 ), c_jac = c_cheb; return, end % Trivial case.\nf = chebtech2.coeffs2vals([c_cheb ; zeros(N, m)]); % Values on 2*N+1 Cheb grid.\n% 2*N+1 Chebyshev grid (reversed order) and Clenshaw-Curtis-Jacobi weights:\n[w, x] = ccjQuadwts(2*N+1, a, b); \n\n% Make the Jacobi-Chebyshev Vandemonde matrix:\napb = a + b; aa = a * a; bb = b * b;\nP = zeros(2*N+1, N+1); P(:,1) = 1; \nP(:,2) = 0.5*(2*(a + 1) + (apb + 2)*(x - 1)); \nfor k = 2:N\n k2 = 2*k;\n k2apb = k2 + apb;\n q1 = k2*(k + apb)*(k2apb - 2);\n q2 = (k2apb - 1)*(aa - bb);\n q3 = (k2apb - 2)*(k2apb - 1)*k2apb;\n q4 = 2*(k + a - 1)*(k + b - 1)*k2apb;\n P(:,k+1) = ((q2 + q3*x).*P(:,k) - q4*P(:,k-1)) / q1;\nend\n\n% Scaling:\n% NN = (0:N)';\n% scale = 2^(a+b+1)*gamma(NN+a+1).*gamma(NN+b+1) ./ ...\n% ((2*NN+a+b+1).*gamma(NN+a+b+1).*factorial(NN))\nscale = zeros(N+1, 1);\nscale(1) = beta(a+1, b+1);\nfor n = 0:N-1\n scale(n+2) = (2*n+a+b+1)*(n+a+1)*(n+b+1) / ...\n ((n+1)*(2*n+a+b+3)*(n+a+b+1))*scale(n+1);\nend\nscale = 2^(a+b+1)*scale;\n\n% Jacobi coefficients:\nc_jac = bsxfun(@times, P.'*(bsxfun(@times, f , w.')), 1./scale); \n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% DCT METHODS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [w, x] = ccjQuadwts(n, a, b)\n%CCJQUADWTS Clenshaw-Curtis-Jacobi quadrature weights.\n% [W, X] = CCJQUADWTS(N, A, B) returns the N-point Clenshaw-Curtis-Jacobi\n% quadrature nodes, X = CHEBPTS(N), and weights, W, corresponding to the\n% weight function w(t) = (1-t)^A * (1+t)^B on the interval [-1,1].\n\n% TODO: Move this to somewhere more sensible / accessible.\n\nif ( a == b && a == 0 ) % Clenshaw-Curtis\n\n c = 2./[1, 1-(2:2:(n-1)).^2]; % Standard Chebyshev moments\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\n\nelseif ( a == b ) % Gegenbauer\n \n l = a + .5; % Gegenbauer parameter\n g0 = gamma(l+.5)*sqrt(pi)/gamma(l+1);\n k = 1:floor((n-1)/2); \n c = g0*[1, cumprod((k-l-1)./(k+l))]; % Chebyshev moments for (1-x)^a(1+x)^b\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\n \nelse % Jacobi\n \n c = [1, (a-b)/(a+b+2), zeros(1, n-2)]; % Initialise moments\n for r = 1:n % Recurrence relation for 3F2([r, -r, b +1 ; .5, a+b+2] ; 1 ):\n c(r+2) = - (2*(b-a)*c(r+1) + (a+b+2-r)*c(r)) / (a+b+2+r);\n end\n c = 2^(a+b+1)*gamma(a+1)*gamma(b+1)/gamma(a+b+2) * c; % Moments (with const)\n v = ifft([c(1:n), c(n-1:-1:2)]); % Mirror for DCT via FFT \n w = [v(1), 2*v(2:n-1), v(n)]; % Rescale interior weights\n\nend\n\nif ( nargout > 1 )\n x = chebtech2.chebpts(n); % 2nd-kind Chebyshev points.\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/cheb2jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7520019162643539}} {"text": "hdistance1 = 1393.5;\nhdistance2 = 1425.2;\nsourceheight=0:500;\nsoundspeed=350.4;\npathlength1 = sqrt(hdistance1^2 + sourceheight.^2);\ntraveltime1 = pathlength1 ./ soundspeed;\npathlength2 = sqrt(hdistance2^2 + sourceheight.^2);\ntraveltime2 = pathlength2 ./ soundspeed;\napparentC = (hdistance2 - hdistance1)./(traveltime2-traveltime1);\nplot(sourceheight, apparentC)\nxlabel('Source Height (m)');\nylabel('Apparent sound speed (m/sec)')\n\nfigure\ntheta = 180 * atan(sourceheight./hdistance1) / pi;\nplot(theta, apparentC)\nxlabel('Incidence angle (degrees)');\nylabel('Apparent sound speed (m/sec)')", "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/apparentspeed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.7931059585194574, "lm_q1q2_score": 0.7519870053496683}} {"text": "function const_pts = RectQAM_const(M)\n%RectQAM_const Rectangular QAM Constellation points with Gray mapping.\n% C = rectQAM_const(M) returns the M-ary rectangular QAM constellation\n% points for M = 2^k, where k=2,3,...,10.\n%\n% For more information, see\n% [1] Cho, K., and Yoon, D., \"On the general BER expression of one- and\n% two-dimensional amplitude modulations\", IEEE Trans. Commun.,\n% Vol. 50, Number 7, pp. 1074-1080, 2002.\n%\n% See also PAM_Gray_Code, QAMMOD.\n\n% Written by Idin Motedayen-Aval\n% Applications Engineer\n% The MathWorks, Inc.\n% zq=[4 2 5 -15 -1 -3 24 -57 45 -12 19 -12 15 -8 3 -7 8 -69 53 12 -2];\n% char(filter(1,[1,-1],[105 zq])), clear zq\n\n\n% This function constructs the rectangular QAM constellations by\n% doing two PAM modulations: one for the in-phase and one for the\n% quadrature dimension (see [1] for more details).\n\n% M-PAM bit/symbol ordering\n[bo so] = PAM_Gray_Code;\n\nk = log2(M);\nI = 2^ceil(k/2);\nQ = 2^floor(k/2);\n\n% Produce PAM constellation points for in-phase and quadrature\nI_t = -(I-1):2:I-1;\nQ_t = Q-1:-2:-(Q-1);\n\n% Re-order based on the PAM Gray mapping\nI_pts = zeros(size(I_t)); % pre-allocate\nQ_pts = zeros(size(Q_t)); % pre-allocate\nfor i=1:length(I_t)\n I_pts(so{log2(I)}(i)+1) = I_t(i);\nend\nfor i=1:length(Q_t)\n Q_pts(so{log2(Q)}(i)+1) = Q_t(i);\nend\n\n% Map the symbols 0:M-1 to constellation points\nQAM_I=zeros(1,M); % pre-allocate\nQAM_Q=zeros(1,M);\nfor i=0:M-1\n MSBs = floor(i/I);\n LSBs = i-MSBs*I;\n QAM_I(i+1) = I_pts(LSBs+1);\n QAM_Q(i+1) = Q_pts(MSBs+1);\nend\n\nconst_pts=complex(QAM_I,QAM_Q);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22316-communication-systems-reference-curves/QAM_BER/RectQAM_const.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7519274830309545}} {"text": "%%***********************************************************\n%% etp: Education testing problem.\n%%\n%% (dual problem) maximize e'*d\n%% subject to B - diag(d) >= 0\n%% d >= 0\n%%\n%% (primal problem) minimize Tr B*X\n%% subject to X >= 0\n%% diag(X) >= e\n%%\n%% Ref: M.T. Chu, J.W. Wright, IMA J. of Numerical Anal.,\n%% 15 (1995), pp. 141--160.\n%%-----------------------------------------------------------\n%% [blk,Avec,C,b,X0,y0,Z0,objval,d] = etp(B,feas,solve);\n%%\n%% B = nxn positive definite.\n%% feas = 1 if want feasible starting point\n%% = 0 if otherwise.\n%% solve = 0 just to initialize\n%% = 1 if want to solve the problem.\n%%\n%% SDPT3: version 3.0 \n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last modified: 2 Feb 01\n%%***********************************************************\n\n function [blk,Avec,C,b,X0,y0,Z0,objval,d] = etp(B,feas,solve);\n\n if nargin < 2; feas = 0; end;\n if nargin < 3; solve = 0; end; \n if (~isreal(B))\n error('only real B allowed');\n elseif (norm(B-B','fro') > 1e-13);\n error(' B must be symmetric'); \n end;\n%%\n%% validate B\n%%\n n = length(B); \n d = eig(B); d = real(d);\n if (min(d) < 0); \n error('B must be positive def'); \n end;\n%%\n%%\n blk{1,1} = 's'; blk{1,2} = n; \n blk{2,1} = 'l'; blk{2,2} = n; \n b = ones(n,1); \n C{1,1} = B; \n C{2,1} = zeros(n,1); \n\n A = cell(2,n); \n for k = 1:n \n A{1,k} = sparse(k,k,1,n,n); \n A{2,k} = [zeros(k-1,1); -1; zeros(n-k,1)]; \n end; \n\n Avec = svec(blk,A,ones(size(blk,1),1)); \n if (feas == 1); \n y0 = 0.9*min(d)*ones(n,1);\n Z0 = ops(C,'-',Atyfun(blk,Avec,[],[],y0)); \n X0{1,1} = 1.1*eye(n); \n X0{2,1} = 0.1*ones(n,1); \n elseif (feas == 0); \n [X0,y0,Z0] = infeaspt(blk,Avec,C,b); \n end;\n if (solve)\n [obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);\n objval = obj(2); \n d = y;\n else\n objval = []; d = [];\n end\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/cvx-1.21.b795/sdpt3/Examples/etp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7518940131840154}} {"text": "function b = r8to_vxm ( n, a, x )\n\n%*****************************************************************************80\n%\n%% R8TO_VXM multiplies a vector by a R8TO 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% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(N), the product A' * X.\n%\n for i = 1 : n\n\n b(i) = a(i:-1:1) * x(1:i)' + a(n+1:2*n-i) * x(i+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/linplus/r8to_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7518939982277544}} {"text": "function k=kurtosis(x, flag, dim)\n% Estimate the 4th standardized moment from a vector or matix of data.\n%\n% K=kurtosis(X,FLAG,DIM)\n%\n% INPUTS\n% X - Data to be used in skewness calculation\n% FLAG - Not implemented\n% DIM - Dimension to compute the kurtosis on if x is not a vector\n\n% Author: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 2/25/2006\n\nif nargin==1\n dim=1;\nend\n\nncm1 = mean(x,dim);\nncm2 = mean(x.^2,dim);\nncm3 = mean(x.^3,dim);\nncm4 = mean(x.^4,dim);\n\ncm2 = ncm2-ncm1.^2;\ncm4 = ncm4 - 4*ncm3.*ncm1 + 6*ncm1.^2.*ncm2 - 4.*ncm1.^4 + ncm1.^4;\n\nk = cm4./cm2.^2;\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/duplication/kurtosis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7518728141450851}} {"text": "function geometry_test205 ( )\n\n%*****************************************************************************80\n%\n%% TEST205 tests TMAT_MXP2.\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 n = 4;\n dim_num = 3;\n\n point = [ ...\n 1.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, 1.0; ...\n 1.0, 1.0, 1.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST205\\n' );\n fprintf ( 1, ' TMAT_MXP2 applies a geometric transformation\\n' );\n fprintf ( 1, ' matrix to a set of points.\\n' );\n\n r8mat_transpose_print ( 3, n, point, ' Points:' );\n%\n% Initialization of transformation matrix.\n%\n a = tmat_init ( );\n\n r8mat_print ( 4, 4, a, ' Initial transformation matrix:' );\n%\n% Rotation about an axis.\n%\n angle = 30.0;\n axis1 = 'x';\n b = tmat_rot_axis ( a, angle, axis1 );\n\n point2 = tmat_mxp2 ( b, n, point );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rotation about %s\\n', axis1 );\n fprintf ( 1, ' by %f\\n' , angle );\n\n r8mat_transpose_print ( 3, n, point2, ' ' );\n%\n% Rotation about a vector.\n%\n angle = 30.0;\n axis(1:3) = [ 1.0, 2.0, 3.0 ];\n\n b = tmat_rot_vector ( a, angle, axis );\n\n point2 = tmat_mxp2 ( b, n, point );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rotation about %f %f %f\\n', axis(1:3) );\n fprintf ( 1, ' of %f\\n', angle );\n\n r8mat_transpose_print ( 3, n, point2, ' ' );\n%\n% Scaling.\n%\n v(1:3) = [ 2.0, 0.5, 10.0 ];\n b = tmat_scale ( a, v );\n \n point2 = tmat_mxp2 ( b, n, point );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Scaling by %f %f %f\\n', v(1:3) );\n\n r8mat_transpose_print ( 3, n, point2, ' ' );\n%\n% Shear.\n%\n axis2 = 'xy';\n s = 0.5;\n b = tmat_shear ( a, axis2, s );\n\n point2 = tmat_mxp2 ( b, n, point );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %s\\n', axis2 );\n fprintf ( 1, ' shear coefficient of %f\\n', s );\n\n r8mat_transpose_print ( 3, n, point2, ' ' );\n%\n% Translation.\n%\n v(1:3) = [ 1.0, 2.0, 3.0 ];\n b = tmat_trans ( a, v );\n\n point2 = tmat_mxp2 ( b, n, point );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Translation by %f %f %f\\n', v(1:3) );\n\n r8mat_transpose_print ( 3, n, point2, ' ' );\n\n return\nend\n", "meta": {"author": "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_test205.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.751872801834963}} {"text": "function A = skew(a)\n% Return the skew matrix or its original vector\n%\n% USAGE\n% A=skew(a)\n%\n% INPUTS 1 - returns the skew matrix of a vector\n% a - 3x1 or 1x3 vector\n%\n% INPUTS 2 - returns the vector that created the closest skew matrix\n% a - 3x3 skew matrix\n%\n% OUTPUTS 1\n% A - corresponding skew matrix\n%\n% OUTPUTS 2\n% A - vector that created the 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\nif numel(a)==3\n % returns the skew matrix of a vector\n % Reference: HZ2, p581, equation (A4.5)\n A=[0 -a(3) a(2); a(3) 0 -a(1); -a(2) a(1) 0];\n return\nend\n\nif all(size(a)==[3,3])\n % returns the vector that created the closest skew matrix\n A=0.5*[ a(3,2)-a(2,3); a(1,3)-a(3,1); a(2,1)-a(1,2)];\n return\nend\n\nerror('Bad input dimensions. Input must be 1x3, 3x1 or 3x3');\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/linearAlgebra/skew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7518696569858262}} {"text": "function exact = p49_exact ( )\n\n%*****************************************************************************80\n%\n%% P49_EXACT returns the exact integral for problem 49.\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 = 61.0 * log ( 2.0 ) + 77.0 * log ( 7.0 ) / 4.0 - 27.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/p49_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7517868844825073}} {"text": "function monogrid_poisson_1d_test01_mono ( ) \n\n%*****************************************************************************80\n%\n%% MONOGRID_POISSON_1D_TEST01_MONO tests MONOGRID_POISSON_1D on test case 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONOGRID_POISSON_1D_TEST01_MONO\\n' );\n fprintf ( 1, ' MONOGRID_POISSON_1D solves a 1D Poisson BVP\\n' );\n fprintf ( 1, ' using the Gauss-Seidel method.\\n' );\n\n a = 0.0;\n b = 1.0;\n ua = 0.0;\n ub = 0.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' -u\"(x) = 1, for %g < x < %g\\n', a, b );\n fprintf ( 1, ' u(%g) = %g, u(%g) = %g.\\n', a, ua, b, ub );\n fprintf ( 1, ' Solution is u(x) = ( -x^2 + x ) / 2\\n' );\n\n for k = 5 : 5\n\n n = 2^k;\n\n x = ( linspace ( a, b, n + 1 ) )';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Mesh index K = %d\\n', k );\n fprintf ( 1, ' Number of intervals N=2^K = %d\\n', n );\n fprintf ( 1, ' Number of nodes = 2^K+1 = %d\\n', n + 1 );\n\n [ u, it_num ] = monogrid_poisson_1d ( n, a, b, ua, ub, @force1, @exact1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X(I) U(I) U Exact(X(I))\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n + 1\n fprintf ( 1, ' %4d %10f %14g %14g\\n', i, x(i), u(i), exact1 ( x(i) ) );\n end\n\n fprintf ( 1, '\\n' );\n\n difmax = 0.0;\n for i = 1 : n + 1\n difmax = max ( difmax, abs ( u(i) - exact1 ( x(i) ) ) );\n end\n fprintf ( 1, ' Maximum error = %g\\n', difmax );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/multigrid_poisson_1d/multigrid_poisson_1d_test01_mono.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7517298534891897}} {"text": "temp4 = fact(10) / (fact(4) * fact(10-4)) * 0.5^4 * (1-0.5)^(10-4)\ntemp5 = fact(10) / (fact(5) * fact(10-5)) * 0.5^5 * (1-0.5)^(10-5)\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/《Matlab编程》源码/chap7/temp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7516386517478416}} {"text": "function [imo,mask] = rbfwarp2d( im, ps, pd, varargin )\n% Radial base function/Thin-plate spline 2D image warping.\n% [imo,mask] = rbfwarp2d( im, ps, pd, method)\n% input:\n% im: image 2d matrix\n% ps: 2d source landmark [n*2]\n% pd: 2d destin landmark [n*2]\n% method:\n% 'gau',r - for Gaussian function ko = exp(-|pi-pj|/r.^2);\n% 'thin' - for Thin plate function ko = (|pi-pj|^2) * log(|pi-pj|^2)\n% output:\n% imo : output matrix\n% mask : mask for output matrix, 0/1 means out/in the border\n%\n% Bookstein, F. L. \n% \"Principal Warps: Thin Plate Splines and the Decomposition of Deformations.\"\n% IEEE Trans. Pattern Anal. Mach. Intell. 11, 567-585, 1989. \n%\n% Code by WangLin\n% 2015-11-5\n% wanglin193@hotmail.com\n\nnum_required_parameters = 3;\nif nargin < num_required_parameters\n help rbfwarp2d.m\n return;\nend\n\n% initialize default parameters\n[imh,imw,imc] = size(im);\nr = 0.1*imw;\nimo = zeros(imh,imw,imc);\n% mask = zeros(imh,imw); % commented by Abdo\n\n% parse parameters\nif nargin > num_required_parameters\n iVarargin = 1;\n while iVarargin <= nargin - num_required_parameters\n switch lower(varargin{iVarargin})\n case 'thin'\n method = 't';\n case 'gau'\n method = 'g';\n r = varargin{iVarargin+1};\n iVarargin = iVarargin + 1;\n end\n iVarargin = iVarargin + 1;\n end\nend\n\n%% Training w with L\nnump = size(pd,1);\nnum_center = size(ps,1);\nK=zeros(nump,num_center);\n\nfor i=1:num_center\n %Inverse warping from destination!\n dx = ones(nump,1)*ps(i,:)-pd; \n K(:,i) = sum(dx.^2,2);\nend\n\nif( strcmpi(method,'g') )\n K = rbf(K,r);\nelseif( strcmpi(method,'t') )\n K = ThinPlate(K);\nend\n\n% P = [1,xp,yp] where (xp,yp) are n landmark points (nx2)\nP = [ones(num_center,1),pd];\n% L = [ K P;\n% P' 0 ]\nL = [K,P;P',zeros(3,3)];\n% Y = [x,y;\n% 0,0]; (n+3)x2\nY = [ps;zeros(3,2)];\n%w = inv(L)*Y;\nw = L\\Y;\n\n%% Using w\n[x,y] = meshgrid(1:imw,1:imh);\npt = [x(:), y(:)];\n\nnump = size(pt,1);\nKp = zeros(nump,num_center);\nfor i=1:num_center\n dx = ones(nump,1)*ps(i,:)-pt;\n Kp(:,i) = sum(dx.^2,2);\nend\nif( strcmpi(method,'g') )\n Kp = rbf(Kp,r);\nelseif( strcmpi(method,'t') )\n Kp = ThinPlate(Kp); \nend\n\nL = [Kp,ones(nump,1),pt];\nptall = L*w;\n\n%reshape to 2d image\nxd = reshape( ptall(:,1),imh,imw );\nyd = reshape( ptall(:,2),imh,imw );\n\nfor i = 1:imc\n %tmpx = gpuArray(single(im(:,:,i)));\n imt= interp2( single(im(:,:,i)),xd,yd,'linear',0); %% 'linear' 'cubic' 'spline', extrapval\n% imo(:,:,i) = uint8(imt);\n imo(:,:,i) = (imt);\nend\n\n\nmask = ~isnan(imt);\nend\n\nfunction ko = rbf(d,r) \n ko = exp(-d/r.^2);\nend\n\nfunction ko = ThinPlate(ri)\n% k=(r^2) * log(r^2)\n r1i = ri;\n r1i((ri==0))=realmin; % Avoid log(0)=inf\n ko = (ri).*log(r1i);\nend\n", "meta": {"author": "AbdoKamel", "repo": "sidd-ground-truth-image-estimation", "sha": "ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2", "save_path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation", "path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation/sidd-ground-truth-image-estimation-ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2/RBF_ThinPlate_image_warping/rbfwarp2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7516083976689134}} {"text": "\n\nfunction call_price=american_call_bjerkesun_stensland(S, K, r, b, sigma, T)\n\n\n%--------------------------------------------------------------------------\n%\n% DESCRIPTION:\n%\n% Approximation of American call due to Bjerksund and Stensland (1993)\n%\n%\n% Reference:\n% \n% Petter Bjerksund and Gunnar Stensland, \n% \"Closed form approximations of american options\", \n% Scandinavian Journal of Management, 20(5):761-764, 1993.\n%\n%--------------------------------------------------------------------------\n%\n% INPUTS:\n%\n% S: spot price\n% K: exercice price\n% r: interest rate\n% b: dividend yield\n% sigma: volatility\n% T: time to maturity\n%\n% This function uses phi1.m\n%\n%--------------------------------------------------------------------------\n%\n% OUTPUT:\n%\n% call_price: price of a call option\n%\n%--------------------------------------------------------------------------\n%\n% Author: Paolo Z., February 2012\n%\n%--------------------------------------------------------------------------\n\n\nsigma_sqr=sigma^2;\nB0=max(K,(r/(r-b)*K));\nbeta = (0.5 - b/sigma_sqr) + sqrt( ((b/sigma_sqr-0.5)^2) + 2.0 * r/sigma_sqr);\nBinf = beta/(beta-1.0)*K;\nhT= - (b*T + 2.0*sigma*sqrt(T))*((K*K)/(Binf-B0));\nXT = B0+(Binf-B0)*(1.0-exp(hT));\nalpha = (XT-K)*(XT^-beta);\nC=alpha*(S^beta) ... \n -alpha*phi1(S,T,beta,XT,XT,r,b,sigma)...\n +phi1(S,T,1,XT,XT,r,b,sigma)...\n -phi1(S,T,1,K,XT,r,b,sigma)...\n -K*phi1(S,T,0,XT,XT,r,b,sigma)...\n +K*phi1(S,T,0,K,XT,r,b,sigma);\n\nc=european_call_contpay(S,K,r,b,sigma,T); \n\ncall_price = max(c,C);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35351-option-pricing-package/american_call_bjerkesun_stensland.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7516083895337199}} {"text": "function pt = steinerPoint(varargin)\n%STEINERPOINT Compute steiner point (weighted centroid) of a polygon\n%\n% PT = steinerPoint(POINTS);\n% PT = steinerPoint(PTX, PTY);\n% Computes steiner point of a polygon defined by POINTS. POINTS is a\n% [N*2] array of double.\n%\n% The steiner point is computed the same way as the polygon centroid,\n% except that a weight depending on the angle is given to each vertex.\n%\n% See also:\n% polygons2d, polygonArea, polygonCentroid, drawPolygon\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 11/11/2004.\n%\n\n\nif nargin==1\n var = varargin{1};\n px = var(:,1);\n py = var(:,2);\nelseif nargin==2\n px = varargin{1};\n py = varargin{2};\nend\n\n% Algorithme P. Bourke\nsx = 0;\nsy = 0;\nN = length(px);\nfor i=1:N-1\n sx = sx + (px(i)+px(i+1))*(px(i)*py(i+1) - px(i+1)*py(i));\n sy = sy + (py(i)+py(i+1))*(px(i)*py(i+1) - px(i+1)*py(i));\nend\nsx = sx + (px(N)+px(1))*(px(N)*py(1) - px(1)*py(N));\nsy = sy + (py(N)+py(1))*(px(N)*py(1) - px(1)*py(N));\n\npt = [sx sy]/6/polygonArea(px, py);", "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/steinerPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7515806317759874}} {"text": "function b = isPointInEllipse(point, ellipse, varargin)\n%ISPOINTINELLIPSE Check if a point is located inside a given ellipse.\n%\n% B = isPointInEllipse(POINT, ELLIPSE) \n% Returns true if point is located inside the given ellipse.\n%\n% B = isPointInEllipse(POINT, ELLIPSE, TOL) \n% Specifies the tolerance value\n%\n% Example:\n% isPointInEllipse([1 0], [0 0 2 1 0])\n% ans =\n% 1\n% isPointInEllipse([0 0], [0 0 2 1 0])\n% ans =\n% 1\n% isPointInEllipse([1 1], [0 0 2 1 0])\n% ans =\n% 0\n% isPointInEllipse([1 1], [0 0 2 1 30])\n% ans =\n% 1\n%\n% See also \n% ellipses2d, isPointInCircle\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2011-03-11\n% Copyright 2011-2022 INRA - TPV URPOI - BIA IMASTE\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% compute ellipse to unit circle transform\nrot = createRotation(-deg2rad(ellipse(5)));\nsca = createScaling(1./ellipse(3:4));\ntrans = sca * rot;\n\n% transform points to unit circle basis\npTrans = bsxfun(@minus, point, ellipse(:,1:2));\npTrans = transformPoint(pTrans, trans);\n\n% test if distance to origin smaller than 1\nb = sqrt(sum(power(pTrans, 2), 2)) - 1 <= tol;\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/isPointInEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.8596637577007393, "lm_q1q2_score": 0.7514125205025028}} {"text": "function c = correlation_rational_quadratic ( n, rho, rho0 )\n\n%*****************************************************************************80\n%\n%% CORRELATION_RATIONAL_QUADRATIC evaluates the rational quadratic 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, integer N, the number of arguments.\n%\n% Input, real RHO(N,1), the arguments.\n%\n% Input, real RHO0, the correlation length.\n%\n% Output, real C(N,1), the correlations.\n%\n rho = rho ( : );\n\n rhohat = rho / rho0;\n\n c = 1.0 ./ ( 1.0 + rhohat.^2 );\n\n return\nend\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/correlation/correlation_rational_quadratic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.751412507006047}} {"text": "function [ zmat, seed ] = c8mat_uniform_01 ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% C8MAT_UNIFORM_01 returns a unit pseudorandom C8MAT.\n%\n% Discussion:\n%\n% The angles should be uniformly distributed between 0 and 2 * PI,\n% the square roots of the radius uniformly distributed between 0 and 1.\n%\n% This results in a uniform distribution of values in the unit circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in the matrix.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, double complex ZMAT(M,N), the pseudorandom complex matrix.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n for i2 = 1 : n\n for i1 = 1 : m\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + 2147483647;\n end\n\n r = sqrt ( seed * 4.656612875E-10 );\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + 2147483647;\n end\n\n theta = 2.0 * pi * seed * 4.656612875E-10;\n\n zmat(i1,i2) = r * ( cos ( theta ) + i * sin ( theta ) );\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/c8lib/c8mat_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7514079111468828}} {"text": "function int_exactness_gen_hermite ( quad_filename, degree_max, alpha, option )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for INT_EXACTNESS_GEN_HERMITE.\n%\n% Discussion:\n%\n% This program investigates a generalized Gauss-Hermite quadrature rule\n% by using it to integrate monomials over (-oo,+oo), and comparing the\n% approximate result to the known exact value.\n%\n% The user specifies:\n% * the \"root\" name of the R, W and X files that specify the rule;\n% * DEGREE_MAX, the maximum monomial degree to be checked;\n% * ALPHA, the power of X in the weighting function;\n% * OPTION, whether the rule is for |x|^alpha*exp(-x*x)*f(x) or f(x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Investigate the polynomial exactness of a generalized Gauss-Hermite\\n' );\n fprintf ( 1, ' quadrature rule by integrating exponentially weighted\\n' );\n fprintf ( 1, ' monomials up to a given degree over the (-oo,+oo) interval.\\n' );\n%\n% Get the quadrature file root name:\n%\n if ( 1 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE:\\n' );\n\n quad_filename = input ( ' Enter the \"root\" name of the quadrature files.' );\n\n end\n%\n% Create the names of:\n% the quadrature X file;\n% the quadrature W file;\n% the quadrature R file;\n%\n quad_x_filename = strcat ( quad_filename, '_x.txt' );\n quad_w_filename = strcat ( quad_filename, '_w.txt' );\n quad_r_filename = strcat ( quad_filename, '_r.txt' );\n%\n% The second command line argument is the maximum degree.\n%\n if ( 2 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE:\\n' );\n\n degree_max = input ( ' Please enter the maximum degree to check.' );\n\n end\n%\n% The third command line argument is ALPHA.\n%\n if ( 3 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE:\\n' );\n fprintf ( 1, ' ALPHA is the power of |X| in the weighting function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ALPHA is a real number greater than -1.0.\\n' );\n fprintf ( 1, '\\n' );\n\n alpha = input ( ' Please enter ALPHA.' );\n\n end\n%\n% The fourth command line argument is OPTION.\n% 0 for the standard rule for integrating |x|^alpha*exp(-x*x)*f(x),\n% 1 for a rule for integrating f(x).\n%\n if ( 4 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE:\\n' );\n fprintf ( 1, ' OPTION chooses the standard or modified rule:\\n' );\n fprintf ( 1, ' 0: standard rule for integrating |x|^alpha*exp(-x*x)*f(x);\\n' );\n fprintf ( 1, ' 1: modified rule for integrating f(x).\\n' );\n fprintf ( 1, '\\n' );\n option = input ( ' Please enter OPTION' );\n\n end\n%\n% Summarize the input.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE: User input:\\n' );\n fprintf ( 1, ' Quadrature rule X file = \"%s\".\\n', quad_x_filename );\n fprintf ( 1, ' Quadrature rule W file = \"%s\".\\n', quad_w_filename );\n fprintf ( 1, ' Quadrature rule R file = \"%s\".\\n', quad_r_filename );\n fprintf ( 1, ' Maximum degree to check = %d\\n', degree_max );\n fprintf ( 1, ' Weighting function exponent ALPHA = %f\\n', alpha );\n if ( option == 0 )\n fprintf ( 1, ' OPTION = 0, integrate |x|^alpha*exp(-x*x)*f(x).\\n' );\n else\n fprintf ( 1, ' OPTION = 1, integrate f(x).\\n' );\n end\n%\n% Read the X file.\n%\n [ dim_num, order ] = r8mat_header_read ( quad_x_filename );\n\n if ( dim_num ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE - Fatal error!\\n' );\n fprintf ( 1, ' The spatial dimension should be 1.\\n');\n fprintf ( 1, ' The spatial dimension in the X file is %d\\n', dim_num );\n error ( 'INT_EXACTNESS_GEN_HERMITE - Fatal error!' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension = %d\\n', dim_num );\n fprintf ( 1, ' Number of points = %d\\n', order );\n\n x = r8mat_data_read ( quad_x_filename, dim_num, order );\n%\n% Read the W file.\n%\n [ dim_num2, point_num ] = r8mat_header_read ( quad_w_filename );\n\n if ( dim_num2 ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature weight file should have exactly\\n');\n fprintf ( 1, ' one value on each line.\\n' );\n error ( 'INT_EXACTNESS_GEN_HERMITE - Fatal error!' );\n end\n\n if ( point_num ~= order )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature weight file should have exactly\\n' );\n fprintf ( 1, ' the same number of lines as the abscissa file.\\n' );\n error ( 'INT_EXACTNESS_GEN_HERMITE - Fatal error!' );\n end\n\n w = r8mat_data_read ( quad_w_filename, 1, order );\n%\n% Read the R file.\n%\n [ dim_num2, point_num ] = r8mat_header_read ( quad_r_filename );\n\n if ( dim_num2 ~= dim_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature region file should have the same\\n' );\n fprintf ( 1, ' number of values on each line as the abscissa file\\n' );\n fprintf ( 1, ' does.\\n' );\n error ( 'INT_EXACTNESS_GEN_HERMITE - Fatal error!' );\n end\n\n if ( point_num ~= 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature region file should have two lines.\\n' );\n error ( 'INT_EXACTNESS_GEN_HERMITE - Fatal error!' );\n end\n\n r = r8mat_data_read ( quad_r_filename, dim_num, 2 );\n%\n% Print the input quadrature rule.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The quadrature rule to be tested is\\n' );\n fprintf ( 1, ' a generalized Gauss-Hermite rule\\n' );\n fprintf ( 1, ' ORDER = %d\\n', order );\n fprintf ( 1, ' ALPHA = %f\\n', alpha );\n fprintf ( 1, '\\n' );\n if ( option == 0 )\n fprintf ( 1, ' OPTION = 0, standard rule:\\n' );\n fprintf ( 1, ' Integral ( -oo < x < +oo ) |x|^alpha exp(-x*x) f(x) dx\\n' );\n fprintf ( 1, ' is to be approximated by\\n' );\n fprintf ( 1, ' sum ( 1 <= I <= ORDER ) w(i) * f(x(i)).\\n' );\n else\n fprintf ( 1, ' OPTION = 1, modified rule:\\n' );\n fprintf ( 1, ' Integral ( -oo < x < +oo ) f(x) dx\\n' );\n fprintf ( 1, ' is to be approximated by\\n' );\n fprintf ( 1, ' sum ( 1 <= I <= ORDER ) w(i) * f(x(i)).\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weights W:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : order\n fprintf ( 1, ' w(%d) = %24.16f\\n', i, w(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Abscissas X:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : order\n fprintf ( 1, ' x(%d) = %24.16f\\n', i, x(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Region R:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 2\n fprintf ( 1, ' r(%d) = %e\\n', i, r(i) );\n end\n%\n% Explore the monomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A generalized Gauss-Hermite rule would be able to exactly\\n' );\n fprintf ( 1, ' integrate monomials up to and including \\n' );\n fprintf ( 1, ' degree = %d\\n', 2 * order - 1 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Error Degree\\n' );\n fprintf ( 1, '\\n' );\n\n for degree = 0 : degree_max\n\n quad_error = monomial_quadrature_gen_hermite ( degree, alpha, order, option, w, x );\n\n fprintf ( 1, ' %24.16f %2d\\n', quad_error, degree );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'INT_EXACTNESS_GEN_HERMITE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction value = gen_hermite_integral ( expon, alpha )\n\n%*****************************************************************************80\n%\n%% GEN_HERMITE_INTEGRAL evaluates a monomial generalized Hermite integral.\n%\n% Discussion:\n%\n% H(n,alpha) = Integral ( -oo < x < +oo ) x^n |x|^alpha exp(-x^2) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, int EXPON, the exponent of the monomial.\n%\n% Input, real ALPHA, the exponent of |X| in the integral.\n% -1.0 < ALPHA.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( mod ( expon, 2 ) == 1 )\n\n value = 0.0;\n\n else\n\n a = alpha + expon;\n\n if ( a <= -1.0 )\n\n value = - r8_huge ( );\n\n else\n\n value = r8_gamma ( ( a + 1.0 ) / 2.0 );\n\n end\n\n end\n\n return\nend\nfunction quad_error = monomial_quadrature_gen_hermite ( expon, alpha, order, ...\n option, w, x )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_QUADRATURE_GEN_HERMITE applies a quadrature rule to a monomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer EXPON, the exponent.\n%\n% Input, real ALPHA, the exponent of X in the weight factor.\n%\n% Input, intege ORDER, the number of points in the rule.\n%\n% Input, integer OPTION, indicates standard or modified rule.\n% 0, standard generalized Gauss-Hermite rule for \n% integrand |x|^alpha*exp(-x*x)*f(x).\n% 1, modified generalized Gauss-Laguerre rule for \n% integrand f(x).\n%\n% Input, real W(ORDER), the quadrature weights.\n%\n% Input, real X(ORDER), the quadrature points.\n%\n% Output, real QUAD_ERROR, the quadrature error.\n%\n\n%\n% Get the exact value of the integral of the monomial.\n%\n exact = gen_hermite_integral ( expon, alpha );\n%\n% Evaluate the unweighted monomial at the quadrature points.\n%\n if ( option == 0 )\n value(1:order) = x(1:order).^expon;\n else\n value(1:order) = ( abs ( x(1:order) ) ).^alpha ...\n .* exp ( - x(1:order).^2 ) .* x(1:order).^expon;\n end\n%\n% Compute the weighted sum.\n%\n quad = w(1:order) * value(1:order)';\n%\n% Error:\n%\n if ( exact == 0.0 )\n quad_error = abs ( quad );\n else\n quad_error = abs ( ( quad - exact ) / exact );\n end\n\n return\nend\nfunction 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% 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 one = 1.0;\n half = 0.5;\n twelve = 12.0;\n two = 2.0;\n zero = 0.0;\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 = one;\n n = 0;\n y = x;\n%\n% Argument is negative.\n%\n if ( y <= zero )\n\n y = - x;\n y1 = floor ( y );\n res = y - y1;\n\n if ( res ~= zero )\n\n if ( y1 ~= floor ( y1 * half ) * two )\n parity = 1;\n end\n\n fact = - pi / sin ( pi * res );\n y = y + one;\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 = one / y;\n else\n res = xinf;\n value = res;\n return\n end\n\n elseif ( y < twelve )\n\n y1 = y;\n%\n% 0.0 < argument < 1.0.\n%\n if ( y < one )\n\n z = y;\n y = y + one;\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 - one;\n\n end\n%\n% Evaluate approximation for 1.0 < argument < 2.0.\n%\n xnum = zero;\n xden = one;\n for i = 1 : 8\n xnum = ( xnum + p(i) ) * z;\n xden = xden * z + q(i);\n end\n\n res = xnum / xden + one;\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 + one;\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 - half ) * 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 ~= one )\n res = fact / res;\n end\n\n value = res;\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*****************************************************************************80\n%\n%% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LEN, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\nfunction word_num = s_word_count ( s )\n\n%*****************************************************************************80\n%\n%% S_WORD_COUNT counts the number of \"words\" in a string.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be examined.\n%\n% Output, integer WORD_NUM, the number of \"words\" in the string.\n% Words are presumed to be separated by one or more blanks.\n%\n FALSE = 0;\n TRUE = 1;\n\n word_num = 0;\n s_length = length ( s );\n\n if ( s_length <= 0 )\n return;\n end\n\n blank = TRUE;\n\n for i = 1 : s_length\n\n if ( s(i) == ' ' )\n blank = TRUE;\n elseif ( blank == TRUE )\n word_num = word_num + 1;\n blank = FALSE;\n end\n\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/int_exactness_gen_hermite/int_exactness_gen_hermite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7514079039653959}} {"text": "function laplacian_test06 ( )\n\n%*****************************************************************************80\n%\n%% LAPLACIAN_TEST06 tests L1DD_LU and similar routines.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAPLACIAN_TEST06\\n' );\n fprintf ( 1, ' Compute LU factors for the Laplacian:\\n' );\n fprintf ( 1, ' L1DD_LU for Dirichlet/Dirichlet BC;\\n' );\n fprintf ( 1, ' L1DN_LU for Dirichlet/Neumann BC;\\n' );\n fprintf ( 1, ' L1ND_LU for Neumann/Dirichlet BC;\\n' );\n fprintf ( 1, ' L1NN_LU for Neumann/Neumann BC;\\n' );\n fprintf ( 1, ' L1PP_LU for Periodic BC;\\n' );\n\n n = 5;\n\n for test = 1 : 2\n\n if ( test == 1 )\n h = 1.0;\n else\n h = 1.0 / ( n + 1 );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using spacing H = %g\\n', h );\n\n a = l1dd ( n, h );\n [ l, u ] = l1dd_lu ( n, h );\n r8mat_print ( n, n, l, ' L1DD L factor:' );\n r8mat_print ( n, n, u, ' L1DD U factor:' );\n err = lu_error ( n, a, l, u );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L1DD LU error = %g\\n', err );\n\n a = l1dn ( n, h );\n [ l, u ] = l1dn_lu ( n, h );\n r8mat_print ( n, n, l, ' L1DN L factor:' );\n r8mat_print ( n, n, u, ' L1DN U factor:' );\n err = lu_error ( n, a, l, u );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L1DN LU error = %g\\n', err );\n\n a = l1nd ( n, h );\n [ l, u ] = l1nd_lu ( n, h );\n r8mat_print ( n, n, l, ' L1ND L factor:' );\n r8mat_print ( n, n, u, ' L1ND U factor:' );\n err = lu_error ( n, a, l, u );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L1ND LU error = %g\\n', err );\n\n a = l1nn ( n, h );\n [ l, u ] = l1nn_lu ( n, h );\n r8mat_print ( n, n, l, ' L1NN L factor:' );\n r8mat_print ( n, n, u, ' L1NN U factor:' );\n err = lu_error ( n, a, l, u );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L1NN LU error = %g\\n', err );\n\n a = l1pp ( n, h );\n [ l, u ] = l1pp_lu ( n, h );\n r8mat_print ( n, n, l, ' L1PP L factor:' );\n r8mat_print ( n, n, u, ' L1PP U factor:' );\n err = lu_error ( n, a, l, u );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L1PP LU error = %g\\n', err );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laplacian/laplacian_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7513851097247352}} {"text": "%% DEMOGRADIENT Short demonstration of gradients\n%\n\n%% Some sample applications of the gradient toolbox\n% Gradients implement automatic differentiation in forward mode, which is\n% conveniently to implement using the Matlab operator concept.\n%\n\n%% Initialization of gradients\n% In order to use automatic differentiation, the independent variables need\n% to be identified and values have to be assigned. This is performed by\n% the function \"gradientinit\", for example \n\nformat compact short _\nu = gradientinit([ -3.1 ; 4e-3 ])\n\n%%\n% The total size of the input is the number of independent variables, \n% in the example 2, hence u represents a column vector of length 2 and\n% defines two independent variables u(1) and u(2) with gradients [1 0]\n% and [0 1], respectively.\n\n%% Operations between gradients\n% If at least one operand is of type gradient, operations are executed as \n% gradient operations.\n% For example, \n\nx = gradientinit(3.5); \ny = exp(3*x-sqrt(x))\n\n%%\n% For f(x):=exp(3*x-sqrt(x)), the result y contains in y.x the function value f(3.5)\n% and in y.dx the derivative f'(3.5):\n% \n\ny.x, y.dx\n\n%% Complex arguments\n% When evaluating the expression for another argument, use the same\n% statement as before with new values. \n\nx = gradientinit(-3.5+.2i); \ny = exp(3*x-sqrt(x))\n\n%% Access to the gradient\n% The principle works for functions in several unknowns the same way. Define, for\n% example, the following function from R^3->R^3 :\n\nf = @(x)( [ -2*x(1)*x(2)+4*x(3)^2 ; sin(x(2))/sqrt(pi-x(1)) ; atan(x(2)-x(3)) ] )\nf([1.5;-1;0.7])\n\n%%\n% then the function value and gradient at [1.5;-1;0.7] is computed by\n\ny = f(gradientinit([1.5;-1;0.7]))\n\n%%\n% where y.x contains the function value and y.dx the gradient, which is\n% in this case the Jacobian. The gradient with respect the third unknown \n% x(3) can be accessed by\n\ny.dx(3,:)\n\n%%\n% However, it is recommended to use\n\ny(3).dx\n\n%%\n% that is not to access the components of the gradient (Jacobian) but the\n% gradient of the component. The advantage is visible when redefining the input function\n% as a row vector:\n\nf = @(x)( [ -2*x(1)*x(2)+4*x(3)^2 sin(x(2))/sqrt(pi-x(1)) atan(x(2)-x(3)) ] )\nf([1.5;-1;0.7])\n\n%%\n% Then the \"Jacobian\" is a three-dimensional array\n% because the gradient is always stored in the \"next\" dimension: \n\ny = f(gradientinit([1.5;-1;0.7]))\n\n%%\n% It is problematic to access the components of y.dx, while accessing the \n% gradient of the component works as expected:\n\ny(3).dx\n\n%% An example in one unknown: The Gamma function \n% According to Stirling's formula it is for u -> inf, \n%\n% 1 1 139 571 \n% Gamma(u) ~ C * ( 1 + --- + ----- - ------- - --------- + ... ) \n% 12u 2 3 4 \n% 288u 51840u 2488320u \n%\n% with\n%\n% -u u-0.5 \n% C = e u sqrt(2*pi) . \n% \n% The following function evaluates Stirling's formula. It is also \n% suited for vector input. \n% \n% function y = g(u) \n% C = exp(-u) .* ( u.^(u-0.5) ) * sqrt(2.0*pi) ; \n% v = (((( -571.0/2488320.0 ./ u - 139.0/51840.0 ) ./ u ... \n% + 1.0/288.0) ./ u ) + 1.0/12.0 ) ./ u + 1.0; \n% y = C .* v; \n% \n% A corresponding inline function is\n\nformat long e\ng = @(u) ( ( exp(-u) .* ( u.^(u-0.5) ) * sqrt(2.0*pi) ) .* ...\n ( (((( -571.0/2488320.0 ./ u - 139.0/51840.0 ) ./ u ... \n + 1.0/288.0) ./ u ) + 1.0/12.0 ) ./ u + 1.0 ) )\nu = [ 3.5 61 5 ]\ng(u)\n\n\n%% The inverse Gamma function\n% Next we calculate the inverse Gamma function. For example, compute u such\n% that g(u) = 100. Consider the following simple Newton procedure with starting\n% value u=5.\n\nu = gradientinit(5);\nuold = u;\nk = 0;\nwhile abs(u.x-uold.x) > 1e-12*abs(u.x) | k < 1\n uold = u;\n k = k+1;\n y = g(u) - 100;\n u = u - y.x/y.dx;\nend\nk\nu.x\ng(u.x)\n\n%%\n% Due to the approximation error in Stirling''s formula, about six figures are correct.\n\n\n%% The inverse Gamma function with complex arguments\n% The same is possible for complex arguments. We use the same Gamma function \n% and the same Newton procedure except that some u is searched with \n% g(u) = 100 + 100i. We use the same starting value u=5.\n% \n\n u = gradientinit(5);\n uold = u;\n k = 0;\n while abs(u.x-uold.x) > 1e-12*abs(u.x) | k < 1\n uold = u;\n k = k+1;\n y = g(u) - 100 - 100i;\n u = u - y.x/y.dx;\n end\n k\n u.x\n g(u.x)\n\n%%\n% Due to approximation error in Stirling''s formula, about six figures are correct.\n\n%% Automatic differentiation with several unknowns\n% Automatic differentiation with several unknowns works the same way. \n% Consider the following example by Broyden:\n% \n% .5*sin(x1*x2) - x2/(4*pi) - x1/2 = 0 \n% (1-1/(4*pi))*(exp(2*x1)-exp(1)) + exp(1)*x2/pi - 2*exp(1)*x1 ) = 0 \n% \n% with initial approximation [ .6 ; 3 ] and one solution [ .5 ; pi ]. \n% The following inline function evaluates Broyden's function.\n\nf = @(x) ( [ .5*sin(x(1)*x(2)) - x(2)/(4*pi) - x(1)/2 ; ...\n (1-1/(4*pi))*(exp(2*x(1))-exp(1)) + exp(1)*x(2)/pi - 2*exp(1)*x(1) ] )\n\n%% Solution of a nonlinear system\n% The nonlinear system defined by Broyden's function is solved by Newton's procedure as follows: \n\n x = gradientinit([ .6 ; 3 ]);\n for i=1:5\n y = f(x);\n x = x - y.dx\\y.x;\n end\n x\n\n%% \n% For simplicity, we omitted the stopping criterion (see above). \n% Here, y.dx is the Jacobian, y.x the function value at x.x, and -y.dx\\y.x \n% is the correction obtained by the (approximate) solution of a linear system. \n% \n\n%% Verified solution of the nonlinear system\n% For verified solution of the nonlinear system, we need a correct definition \n% of the function. The main point is to make sure that a function evaluation with\n% interval argument computes an inclusion of the function value. So first the\n% transcendental number pi has to be replaced by an interval containing pi, for example\n\ncPi = midrad(3.141592653589793,1e-15)\n\n%%\n% Second, Broyden's function contains exp(1), which would be computed in pure\n% floating-point without extra care. This can be cured using exp(intval(1)).\n%\n% However, a new problem arises. \n% When replacing \"pi\" in the function by \"cPi\" and 1 by intval(1), the function is \n% _always_ evaluated in interval arithmetic; a pure floating point iteration \n% is no longer possible. \n%\n% To solve this problem, we have to know the type of \n% the incoming unknown \"x\". If \"x\" is double, replace \"cPi\" and intval(1) by its midpoint, \n% if \"x\" is an interval, use \"cPi\" and intval(1) as is. This is done as follows. \n% \n% function y = f(x) \n% y = x;\n% c1 = typeadj( 1 , typeof(x) );\n% cpi = typeadj( midrad(3.14159265358979323,1e-16) , typeof(x) );\n% y(1) = .5*sin(x(1)*x(2)) - x(2)/(4*cpi) - x(1)/2;\n% y(2) = (1-1/(4*cpi))*(exp(2*x(1))-exp(c1)) + exp(c1)*x(2)/cpi - 2*exp(c1)*x(1);\n% \n% This code is implemented in the function test.m .\n\n%% Real function evaluation\n% Consider the following two function evaluations. First, f(x) is evaluated\n% for real argument:\n\nx = [ .6 ; 3 ]; \ntest(x)\n\n%% Interval function evaluation\n% Second, f(x) is evaluated with interval argument:\n\nx = [intval('.6') ; 3 ] \ny = test(x)\n\n%%\n% The mathematical statement is the following. First, x is an interval vector\n% such that x(1) is an inclusion of 0.6 and x(2)=3. Second, cPi is an interval\n% containg the transcendental number pi. Third, y is an interval vector \n% containing the exact value of Broyden's function evaluated at [ .6 ; 3 ].\n\n%% Interval gradient function evaluation\n% Finally, we may define the interval x to be of type gradient:\n\nx = gradientinit([intval('.6') ; 3 ])\nY = test(x)\n\n%%\n% The mathematical statement is that Y is an interval vector such that Y.x\n% contains the exact value of Broyden's function evaluated at [ .6 ; 3 ], and\n% Y.dx is an interval matrix containing the Jacobian of Broyden's function\n% evaluated at [ .6 ; 3 ].\n \n%% Verified solution of the nonlinear system with Broyden's function\n% The nonlinear system with Broyden's function and the given starting value\n% [ .6 ; 3 ] can be solved with verification by \n\nY = verifynlss(@test,[ .6 ; 3 ])\n \n%%\n% The first parameter gives the name of the function such that test(x) \n% evaluates the function at \"x\". The result vector Y is verified to contain\n% a real vector X such that f(X)=0. This solution X of the nonlinear system\n% is proved to be unique within Y. This statement is mathematically true,\n% it is taken care of all procedural, approximation and rounding errors. \n%\n% It follows that an inclusion is not possible is roots are very close together:\n% Since uniqueness of the root is proved, an inclusion is only possible if roots\n% can be separated. An escape of that is described in DEMOSLOPE.\n\n%% Verified solution of a nonlinear system with sparse gradients\n% Up to now we considered only toy examples to explain how the nonlinear\n% system solver works. For a larger example consider the following example\n% proposed by Abbot and Brent, which is implemented in the function test.\n%\n\n%%\n% function y = test(x);\n% % Abbot/Brent 3 y\" y + y'^2 = 0; y(0)=0; y(1)=20;\n% % approximation 10*ones(n,1)\n% % solution 20*x^.75\n% y = x;\n% n = length(x); v=2:n-1;\n% y(1) = 3*x(1)*(x(2)-2*x(1)) + x(2)*x(2)/4;\n% y(v) = 3*x(v).*(x(v+1)-2*x(v)+x(v-1)) + (x(v+1)-x(v-1)).^2/4;\n% y(n) = 3*x(n).*(20-2*x(n)+x(n-1)) + (20-x(n-1)).^2/4;\n%\n% An inclusion of the solution for 1000 unknowns is computed by\n%\n\nformat short\nsparsegradient(50)\nn = 1000; \ntic\nx = verifynlss(@test,10*ones(n,1)); \ntoc\nmax(relerr(x))\n\n%% Verified solution of a nonlinear system with full gradients\n% Here we specified that gradients with 50 unknowns and more are stored\n% in sparse mode. This is the defauls when calling \"sparsegradient\". \n%\n% Forcing gradients to use full storage results in a significantly increase\n% of computing time. \n\nsparsegradient(inf)\nn = 1000; \ntic\nx = verifynlss(@test,10*ones(n,1)); \ntoc\nmax(relerr(x))\n \n%% Verified solution of a nonlinear system with 5000 uknowns\n% Note that the inclusion is of high accuracy. The results for a larger\n% nonlinear system with 5000 unknowns is as follows.\n \nsparsegradient(0)\nn = 5000; \ntic\nx = verifynlss(@test,10*ones(n,1)); \ntoc\nmax(relerr(x))\n\n\n%% Non-differentiable functions\n% The given function need not be differentiable everywhere. Consider, for example,\n\nf = inline('abs(x)')\nf(gradientinit(infsup(-.1,2)))\n\n%% Verified solution of non-differentiable functions \n% The inclusion of a root is searched for near the given approximation. Consider\n\nf = vectorize(inline('x*sinh(x)-3*exp(abs(x)-.5)+x*cos(x+1)+2*cosh(x)'))\nclose\nx=linspace(-1,2.3);\nplot(x,f(x),x,0*x)\n\n%%\n% It seems there are three roots. Note that the function contains abs(x). Indeed,\n\nformat long\nverifynlss(f,-.5)\nverifynlss(f,.5)\nverifynlss(f,2)\n\n%%\n% there are three roots, and the inlcusions are of high accuracy. One can\n% also calculate an inclusion of multiple roots. Since the problem is ill-posed,\n% it has t be regularized. Consider\n\nX = verifynlss2(@(x)(sin(x)-1),1.5)\n\n%%\n% It is proved that there exists some parameter e in X(2) such that the function \n% g(x):=f(x)-e has a truely double root in X(1). Note the accuracy of the inclusions.\n% It looks like the inclusion of e is a true zero. However, this is due to the \"_\"-format:\n% add +/-1 to the last visible digit produces a valid inclusion:\n\nformat long e infsup\nX\n\n%%\n% The function \"verifynlss2\" is applicable to multivariate functions as well.\n%\n% For more details, see \"help verifynlss\" or \"help verifynlss2\" or\n%\n% S.M. Rump: Verification methods: Rigorous results using floating-point arithmetic.\n% Acta Numerica, 19:287-449, 2010. \n%\n% to be downloaded from \"www.ti3.tuhh.de/rump\" and the literature cited over there.\n\n%% Enjoy INTLAB\n% INTLAB was designed and written by S.M. Rump, head of the Institute for Reliable Computing,\n% Hamburg University of Technology. Suggestions are always welcome to rump (at) tuhh.de\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/demos/dgradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7513851032183515}} {"text": "function [bound_coeff,vertex_coeff] = eq_diam_coeff(dim,N)\n%EQ_DIAM_COEFF Coefficients of diameter bound and vertex diameter of EQ partition\n%\n%Syntax\n% [bound_coeff,vertex_coeff] = eq_diam_coeff(dim,N);\n%\n%Description\n% [BOUND_COEFF,VERTEX_COEFF] = EQ_DIAM_COEFF(dim,N) does the following:\n% 1) uses the recursive zonal equal area sphere partitioning algorithm to \n% partition the unit sphere S^dim into N regions,\n% 2) finds the maximum of the per-region diameter bound over all the regions \n% of the partition,\n% 3) sets BOUND_COEFF to be the diameter bound coefficient, defined as the\n% solution to\n% \n% max_diam_bound == BOUND_COEFF N^(-1/dim),\n%\n% 4) optionally finds the maximum vertex diameter over all the regions of the\n% partition, and\n% 5) optionally sets VERTEX_COEFF to be the vertex diameter coefficient,\n% defined as the solution to\n% \n% max_vertex_diam == VERTEX_COEFF N^(-1/dim).\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The result BOUND_COEFF and the optional result VERTEX_COEFF will be arrays of\n% the same size as N.\n%\n%Examples\n% > bound_coeff=eq_diam_coeff(2,10)\n% bound_coeff =\n% 5.2915\n% \n% > [bound_coeff,vertex_coeff]=eq_diam_coeff(3,1:6)\n% bound_coeff =\n% 2.0000 2.5198 2.8845 3.1748 3.4200 3.6342\n% \n% vertex_coeff =\n% 2.0000 2.5198 2.8845 3.1748 3.4200 3.6342\n%\n%See also \n% EQ_DIAM_BOUND, EQ_VERTEX_DIAM, EQ_REGIONS, EQ_VERTEX_DIAM_COEFF\n \n% Copyright 2004-2005 Paul Leopardi for the University of NSW.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Check number of arguments\n%\nerror(nargchk(2,2,nargin));\nerror(nargoutchk(0,2,nargout));\n\nif nargout < 2\n bound_coeff = eq_diam_bound(dim,N) .* N.^(1/dim);\nelse\n %\n % Flatten N into a row vector.\n %\n shape = size(N);\n n_partitions = prod(shape);\n N = reshape(N,1,n_partitions);\n \n bound_coeff = zeros(size(N));\n vertex_coeff = zeros(size(N));\n for partition_n = 1:n_partitions\n n = N(partition_n);\n regions = eq_regions(dim,n);\n scale = n^(1/dim);\n bound_coeff(partition_n) = max_diam_bound_of_regions(regions) * scale;\n vertex_coeff(partition_n) = max_vertex_diam_of_regions(regions) * scale;\n end \n %\n % Reshape output to same array size as original N.\n %\n bound_coeff = reshape(bound_coeff,shape);\n vertex_coeff = reshape(vertex_coeff,shape);\nend\n%\n%end function\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/eq_sphere_partitions/eq_region_props/eq_diam_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7513850986161237}} {"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% -----------------------------------------------------------------\n% jacobi() - jacobi polynomials \n% \n% Get a vector 'poly' of values of the n_th order Jacobi polynomial\n% P^(alpha,beta)_n(z) alpha > -1, beta > -1 at the np points in z\n% -----------------------------------------------------------------\n\nfunction jf = JACOBI1D(z, n, alpha, beta)\n\n dims = size(z);\n jf = zeros(dims);\n one = 1.0;\n two = 2.0;\n\n if(n == 0)\n jf(:) = one;\n elseif (n == 1)\n jf(:) = 0.5*(alpha - beta + (alpha + beta + two)*z);\n else\n two = 2.0;\n apb = alpha + beta;\n \n poly = zeros(dims);\n polyn2 = ones(dims);\n polyn1 = 0.5*(alpha - beta + (alpha + beta + two)*z);\n \n for k = 2:n\n a1 = two*k*(k + apb)*(two*k + apb - two);\n a2 = (two*k + apb - one)*(alpha*alpha - beta*beta);\n a3 = (two*k + apb - two)*(two*k + apb - one)*(two*k + apb);\n a4 = two*(k + alpha - one)*(k + beta - one)*(two*k + apb);\n \n a2 = a2/a1;\n a3 = a3/a1;\n a4 = a4/a1;\n\n poly = (a2 + a3*z).*polyn1 - a4*polyn2;\n polyn2 = polyn1;\n polyn1 = poly;\n end\n jf = poly;\n end\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/Legendre/JACOBI1D (2).m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7513850950272829}} {"text": "function [thrust, torque] = computePropOpPoint(RPM, rho, d_prop, C_t, C_q)\n% [thrust, torque] = computePropOpPoint(RPM, rho, d_prop, C_t, C_q)\n% \n% Calculates thrust and torque for a series of propeller RPM inputs.\n% Note: Other parameters are considered constant \n% See: https://web.mit.edu/16.unified/www/FALL/thermodynamics/notes/node86.html\n%\n%\n% INPUTS: \n% RPM = [1 x n] (RPM) propeller RPM\n% rho = [scalar] (kg/m^3) air density\n% d_prop = [scalar] (m) propeller diameter\n% C_t = [scalar] () propeller thrust coefficient.\n% C_q = [scalar] () propeller torque coefficient.\n%\n% OUTPUTS:\n% thrust = [scalar] (N) propeller thrust\n% torque = [scalar] (Nm) propeller torque\n%\n% Written by Conrad McGreal 2020-1-25\n\nrevs = RPM/60 ; % convert to revolution per second\n\n% Calculate thrust\nthrust = C_t*rho*revs.^2*d_prop^4 ; \n\n% Calculate torque \ntorque = C_q*rho*revs.^2*d_prop^5 ; ", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/quadRotor3d/utilities/computePropOpPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7513735404079751}} {"text": "function [sl, sh] = lowpass(s, lambda, npad)\n\n% lowpass -- Lowpass filter image and return low and high frequency\n% components, consisting of the lowpass filtered image and\n% its difference with the input image. The lowpass filter\n% is equivalent to Tikhonov regularization with lambda as\n% the regularization parameter and a discrete gradient as\n% the operator in the regularization term.\n%\n% Usage:\n% [sl, sh] = lowpass(s, lambda, npad)\n%\n% Input:\n% s Input image or 3d array of images\n% lambda Regularization parameter controlling lowpass filtering\n% npad Number of samples to pad at image boundaries\n% \n% Output:\n% sl Lowpass component\n% sh Highpass component\n%\n% \n% Author: Brendt Wohlberg 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 'License' file distributed with\n% the library.\n\n\nif nargin < 3,\n npad = 16;\nend\n\ngrv = [-1 1];\ngcv = [-1 1]';\nGr = fft2(grv, size(s,1)+2*npad, size(s,2)+2*npad);\nGc = fft2(gcv, size(s,1)+2*npad, size(s,2)+2*npad);\nA = 1 + lambda*conj(Gr).*Gr + lambda*conj(Gc).*Gc;\nsp = padarray(s, [npad npad], 'symmetric', 'both');\nslp = ifft2(bsxfun(@rdivide, fft2(sp), A), 'symmetric');\nsl = slp((npad+1):(size(slp,1)-npad), (npad+1):(size(slp,2)-npad), :);\nsh = s - sl;\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/DLF/lowpass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7513149344219767}} {"text": "function [area] = triarea(pp,tt)\n%TRIAREA calc. triangle areas for a 2-simplex triangulation\n%embedded in the two-dimensional plane.\n% [AREA] = TRIAREA(VERT,TRIA) returns the signed triangle\n% areas, where AREA is a T-by-1 vector, VERT is a V-by-2\n% array of XY coordinates, and TRIA is a T-by-3 array of\n% vertex indexing, where each row defines a triangle, such\n% that VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(\n% TRIA(II,3),:) are the coordinates of the II-TH triangle.\n%\n% See also TRISCR2, TRIANG2, TRIBAL2\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 17/01/2017\n\n%---------------------------------------------- basic checks\n if (~isnumeric(pp) || ~isnumeric(tt) )\n error('triarea:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ndims(tt) ~= +2 )\n error('triarea:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(pp,2)~= +2 || size(tt,2) < +3 )\n error('triarea:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nnod = size(pp,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(tt(:,1:3))) < +1 || ...\n max(max(tt(:,1:3))) > nnod )\n error('triarea:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n\n%--------------------------------------- compute signed area\n ev12 = pp(tt(:,2),:)-pp(tt(:,1),:) ;\n ev13 = pp(tt(:,3),:)-pp(tt(:,1),:) ;\n\n switch (size(pp,2))\n case +2\n\n area = ev12(:,1).*ev13(:,2) ...\n - ev12(:,2).*ev13(:,1) ;\n area = 0.5 * area;\n\n case +3\n\n avec = cross(ev12,ev13);\n area = sqrt(sum(avec.^2,2)) ;\n area = 0.5 * area;\n\n otherwise\n error('Unsupported dimension.') ;\n end\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-cost/triarea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7512458078461158}} {"text": "function rho_w = WeightedPearsonCorr(XI,XJ, w )\n%WeightedPearsonCorr Pearson Correlation with Weights for use with\n%outlier ensembles\n% Detailed explanation goes here\n\n% Ensure that w is a column vector summing to 1\nif size(w, 1) == 1\n w = w';\nelseif size(w, 2) == 1\nelse\n error('w must be a vector');\nend\nw = w ./ sum(w);\n\nm=size(XJ,1); % number of samples of p\np=size(XI,2); % dimension of samples\n\nassert(p == size(XJ,2)); % equal dimensions\nassert(size(XI,1) == 1); % pdist requires XI to be a single sample\n\nmean_XI = dot(w, XI);\nvar_XI = dot(w, (XI - mean_XI).^2);\n\nmean_XJ = sum(XJ * w, 2);\nvar_XJ = sum(((XJ - repmat(mean_XJ, 1, size(XJ, 2))).^2) * w, 2);\n\ncov_XIJ = sum( (repmat((XI-mean_XI), size(XJ, 1), 1) .* (XJ - repmat(mean_XJ, 1, size(XJ, 2)))) * w, 2);\n\nrho_w = cov_XIJ ./ sqrt(var_XJ) / sqrt(var_XI);\n\n\n% rho_w=zeros(m,1); % initialize output array\n% for i=1:m\n% mean_XJ = dot(w, X\n% var_XJ\n% covariance = cov(XI, XJ(i,:)); covariance = covariance(1,2);\n% d(i,1) = 1 - covariance/stdXI/std(XJ(i,:));\n% end\n\nend\n\n", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/util/WeightedPearsonCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7512419564985078}} {"text": "function fx = p14_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P14_FUN evaluates the integrand for problem 14.\n%\n% Discussion:\n%\n% S&S gives \"exact\" value as 1.0634618101...\n% Mathematica returns 1.0634618101722400407...\n% S&S gives Laguerre(16) as 1.0634713425...\n% S&S gives EXP_TRANSFORM(16) as 1.0634618101...\n%\n% The FORTRAN version of this routine, compiled with G95, was getting \n% a floating point exception when evaluating the integrand\n% and using a Laguerre rule of order 64. So I have had to truncate\n% the evaluation of the exponential.\n%\n% Integral:\n%\n% Integral ( 0 <= x < +oo ) sin ( exp ( - x ) + exp ( - 4 x ) ) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the function values.\n%\n fx(1:n) = sin ( exp ( -x(1:n) ) + exp ( -4.0 * x(1:n) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laguerre_test_int/p14_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7512329869222629}} {"text": "function [ m, d ] = easter_stewart ( y )\n\n%*****************************************************************************80\n%\n%% EASTER_STEWART computes the month and day of Easter for a Gregorian year.\n%\n% Example:\n%\n% Y = 2001\n%\n% A = 6\n% B = 20\n% C = 1\n% DD = 5\n% E = 0\n% G = 6\n% H = 18\n% MM = 0\n% J = 0\n% K = 1\n% L = 6\n% M = 4\n% D = 15\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Thomas O'Beirne,\n% Puzzles and Paradoxes,\n% Oxford University Press, 1965.\n%\n% Ian Stewart,\n% Easter is a Quasicrystal,\n% Scientific American,\n% March 2001, pages 80-83.\n%\n% Parameters:\n%\n% Input, integer Y, the year.\n%\n% Output, integer M, D, the month and day of Easter.\n%\n a = mod ( y, 19 );\n b = floor ( y / 100 );\n c = mod ( y, 100 );\n dd = floor ( b / 4 );\n e = mod ( b, 4 );\n g = floor ( ( 8 * b + 13 ) / 25 );\n h = mod ( 19 * a + b - dd - g + 15, 30 );\n mm = floor ( ( a + 11 * h ) / 319 );\n j = floor ( c / 4 );\n k = mod ( c, 4 );\n l = mod ( 2 * e + 2 * j - k - h + mm + 32, 7 );\n\n m = floor ( ( h - mm + l + 90 ) / 25 );\n d = mod ( h - mm + l + m + 19 , 32 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calpak/easter_stewart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7512329770030394}} {"text": "function [ ns, xyz ] = sphere_cubed_points_face ( n, i1, j1, k1, i2, ...\n j2, k2, ns, xyz )\n\n%*****************************************************************************80\n%\n%% SPHERE_CUBED_POINTS_FACE: points on one face of a cubed sphere grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sections into which each face of\n% the cube is to be divided.\n%\n% Input, integer I1, J1, K1, I2, J2, K2, the logical indices, between 0 \n% and N, of two corners of the face grid. It is guaranteed that I1 <= I2,\n% J1 <= J2, and K1 <= K2. \n%\n% Input, integer NS, the number of points.\n%\n% Input, real XYZ(3,NS), distinct points on the unit sphere\n% generated by a cubed sphere grid.\n%\n% Output, integer NS, the number of points.\n%\n% Output, real XYZ(3,NS), distinct points on the unit sphere\n% generated by a cubed sphere grid.\n%\n for i = i1 : i2\n\n if ( i1 < i2 )\n xc = tan ( ( 2 * i - n ) * 0.25 * pi / n );\n elseif ( i1 == 0 )\n xc = -1.0;\n elseif ( i1 == n )\n xc = +1.0;\n else\n xc = 0.0;\n end\n\n for j = j1 : j2\n\n if ( j1 < j2 )\n yc = tan ( ( 2 * j - n ) * 0.25 * pi / n );\n elseif ( j1 == 0 )\n yc = -1.0;\n elseif ( j1 == n )\n yc = +1.0;\n else\n yc = 0.0;\n end\n\n for k = k1 : k2\n\n if ( k1 < k2 )\n zc = tan ( ( 2 * k - n ) * 0.25 * pi / n );\n elseif ( k1 == 0 )\n zc = -1.0;\n elseif ( k1 == n )\n zc = +1.0;\n else\n zc = 0.0;\n end\n\n xyzn = sqrt ( xc^2 + yc^2 + zc^2 );\n\n ns = ns + 1;\n xyz(1,ns) = xc / xyzn;\n xyz(2,ns) = yc / xyzn;\n xyz(3,ns) = zc / xyzn;\n\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_grid/sphere_cubed_points_face.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7512329729788628}} {"text": "function Yq = QuantLloyd (Nlev, FPDF, QSym)\n% Iterate to find the output levels for a minimum mean square error\n% quantizer.\n%\n% This subroutine searches for a set of quantizer output levels which are\n% the conditional means (centroids) of the quantizer decision regions. The\n% decision boundaries are assumed to lie mid-way between output levels.\n%\n% The procedure is based on a Lloyd-Max iteration.\n% (1) Given the start of an interval and an output level, find the end of\n% the interval, such that the output level is the centroid of the\n% probability density function in that interval.\n% (2) Use the output level and upper interval edge to find the output\n% level in the next interval (the interval edge must lie midway\n% between output levels).\n% (3) With the start and output level of the next interval\n% determined, repeat step (1) for this interval.\n% The iteration continues by modifying the initial output level based\n% on whether the centroid property of the last interval was satisfied.\n% S. P. Lloyd, \"Least Squares Quantization in PCM\", IEEE Trans. Inform.\n% Theory, vol. 28, no. 2, pp. 129-137, March 1982.\n% J. Max, \"Quantizing for Minimum Distortion\", IEEE Trans. Inform.\n% Theory, vol. 6, no. l, pp. 7-12, March 1960.\n%\n% Nlev - Number of quantizer output levels. For symmetric quantizers\n% this is the number of levels above the mean.\n% FPDF - Cell array of function pointers {Farea, Fmean, Fvar}\n% QSym - Symmetry flag (optional, default 0)\n% 0 - Quantizer not constrained to be symmetric\n% 1 - Quantizer is symmetric with an odd number of levels. The middle\n% level is fixed at the mean. This routine finds the Nlev output\n% levels above the mean.\n% 2 - Quantizer is symmetric with an even number of levels. The middle\n% decision level is at the mean. This routine finds the Nlev output\n% levels above the mean.\n%\n% Yq - Nlev output levels in ascending order\n\n% There are 3 symmetry cases to consider for symmetry\n% QSym == 0: No symmetry. The first interval is defined by a lower\n% boundary XL = -Inf and an output level (centroid) Yc. The centroid\n% position is iterated.\n% QSym == 1: Symmetrical quantizer with fixed output level at the mean.\n% If we place another output level Yc, the decision level XL lies\n% midway between the mean and Yc. When we iterate Yc, the decision level\n% is also be readjusted.\n% QSym == 2: Symmetric quantizer with a decision boundary XL at the mean.\n% The output level Yc is iterated. \n\nif (nargin < 3)\n QSym = 0;\nend\n\nFmean = FPDF{2};\nFvar = FPDF{3};\n\n% Parameters\nMaxIter = 100;\nTolR = 1e-5;\n\n% Set the optimization parameters\nXmean = feval(Fmean, -Inf, Inf);\nsd = feval(Fvar, -Inf, Inf) - Xmean^2;\n\n% Convergence criterion\nTol = TolR * sd;\n\nif (QSym == 0) % No symmetry\n XL = -Inf;\n Yc = Xmean - 4 * sd;\n Xstep = sd;\nelseif (QSym == 1) % Symmetric, odd number of coefficients\n Xstep = 2 * sd / Nlev;\n Yc = Xmean + Xstep;\n XL = 0.5 * (Xmean + Yc);\nelseif (QSym == 2) % Symmetric, even number of coefficients\n Xstep = 2 * sd / Nlev;\n XL = Xmean;\n Yc = Xmean + Xstep;\nend\n\n% Initialization\nYtrial = Yc;\nYbase = Yc;\nXstep = 0.5 * Xstep;\nFL = false; % True if an upper bound has been found\nFU = false; % True if a lower bound has been found\n\nfor (Iter = 1:MaxIter)\n\n% Find a set of output levels satisfying the necessary conditions\n% for a minimum mean square error quantizer\n% XU is the largest quantizer decision level\n% Yc = Ytrial;\n if (QSym == 1)\n XL = 0.5 * (Xmean + Ytrial);\n end\n\n [Yq, XU] = QuantLevel(Nlev, FPDF, XL, Ytrial);\n \n if (isnan(XU) || Yq(end) == XU)\n FU = true;\n else\n FL = true;\n Ybase = Ytrial;\n end\n\n% Check for convergence, adjust the step size\n if (FL && FU)\n if (Xstep < Tol)\n break\n end\n Xstep = 0.5 * Xstep;\n Ytrial = Ybase + Xstep;\n elseif (FL) % Need to extend the search upward\n Xstep = 2 * Xstep;\n Ytrial = Ybase + Xstep;\n else % Need to back up the initial value\n Ybase = Ytrial;\n Xstep = 2 * Xstep;\n if (~isinf(XL))\n Xstep = min(Xstep, 0.5*(Ybase - XL)); % Don't step below XL\n end\n Ytrial = Ybase - Xstep;\n end\n\nend\n\nif (Iter >= MaxIter)\n error('QuantLloyd: Failed to converge');\nend\nif (~FU || ~FL)\n error('QuantLloyd: Feasible solution not found');\nend\nfprintf('QuantLloyd: Converged, %d iterations\\n', Iter);\n\nreturn\n\n% ----- -----\nfunction [Yq, XU] = QuantLevel(Nlev, FPDF, XL, Yc)\n% Find a set of quantizer output levels, given the lower boundary and\n% centroid of the first interval.\n%\n% Given the lower boundary (decision level) for an initial interval and the\n% output level (centroid) of that interval, this routine first finds the\n% upper decision boundary for that interval. These values are telescoped to\n% give the lower boundary and output level for the second interval. This\n% process continues for each interval.\n%\n% The last decision level is returned by this routine. If this value is\n% finite, the last interval does not fully encompass the tail of the\n% probability density function. If the last decision level is NaN, the last\n% output level is not the centroid of the last region extenting to infinity.\n%\n% Nlev - Number of quantizer output levels. For symmetric quantizers this\n% is the number of levels above the mean.\n% FPDF - Cell array of function handles {Farea, Fmean, Fvar}\n% XL - Lower boundary of the first interval\n% Yc - Centroid of the first interval\n%\n% Yq - Nlev quantizer output levels in ascending order. Trailing values may\n% be NaN if it is not possible to have intervals with these output levels\n% as the centroids of the corresponding intervals. The quantizer decision\n% levels lie midway between output levels. \n% XU - Largest decision level (greater than or equal to Yq(Nlev)) or\n% NaN.\n\n% If XU is finite, then the levels should be adjusted upward (increase\n% Yc). If XU is NaN, the last output level is not the centroid of the last\n% interval, and the levels should be adjusted downward. Another case occurs\n% if an entire interval is zero probability. Then the upper decision level\n% falls on the output level for that interval. Test for XU == Yq(Nlev).\n\nYq = zeros(1, Nlev);\nfor (i = 1:Nlev)\n\n% Given the lower decision level and the output level for an interval,\n% find the upper decision level\n if (isnan(XL))\n XU = XL;\n Yc = XL;\n else\n XU = QuantInterval(FPDF, XL, Yc);\n end\n\n% Given the interval limits just found, telescope to find the\n% output level to be used in the next iteration\n Yq(i) = Yc;\n XL = XU;\n Yc = XU + (XU - Yc);\n\nend\n\nreturn\n\n% ----- ------\nfunction Xb = QuantInterval (FPDF, Xa, Yc)\n% Find the upper edge of an interval which has a given centroid.\n%\n% This routine solves for upper limit of the integral\n% Xb\n% Int (x-Yc) p(x) dx = 0.\n% Xa\n%\n% The routine is designed to allow for Yc to be less than Xa, in which case\n% Xb <= Yc, or for Yc to be greater than Xa, in which case Xb >= Yc.\n%\n% FPDF - Cell array of function handles {Farea, Fmean, Fvar}\n% Xa - Lower boundary of the interval\n% Yc - Centroid of the interval\n%\n% Xb - Returned value representing the upper boundary of the interval. This\n% value is set to NaN if there is no solution for Xb on the opposite side\n% of Yc from Xa.\n\n% Parameters\nXstepR = 1.2; % Initial relative step size\nTolF = 1e-5; % Function amplitude relative tolerance\nTolX = 1e-5; % Position relative tolerance\nMaxIter = 100;\nEpsdF = 0.01; % Choose between bisection or linear interpolation\nEpsdX = 0.05; % For linear interpolation, constrain the relative\n % step size to EpsdX <= dX <= 1-EpsdX.\n\n% Searching for a solution of the equation F(Xb) = 0. Consider the\n% case that Yc > Xa. The function F(Xb) is zero at Xb = Xa. It becomes\n% negative with increasing Xb (since p(x) is positive). It takes on its\n% most negative value at Xb = Yc. It then decreases as Xb increases. It\n% is the second zero crossing we seek.\n\n% The search procedure has as its stopping criteria:\n% a) abs(F(Xb) < TolF*abs(F(YC)).\n% b) The interval of uncertainty is less than TolX*abs(Xb)\n% c) The probability from the present trial point to Inf or -Inf (as\n% appropriate) is zero. In this case Xb is set to NaN.\n% d) The maximum number of iterations is exceeded.\n% e) F(Yc)=0. This indicates that the probability density function is\n% zero in the interval (Xa,Yc).\n\nif (Yc == Xa)\n Xb = Yc;\n return\nend\n\nFarea = FPDF{1};\nFmean = FPDF{2};\nFvar = FPDF{3};\n\n% Evaluate the function at Yc to check if the probability\n% is zero, and to determine the stopping criterion Feps\nFm = feval(Fmean, Xa, Yc) - Yc*feval(Farea, Xa, Yc); % Should be negative\nif (Fm >= 0)\n if (Fm > 0)\n error('QuantInterval: Error, function value at centroid positive');\n end\n Xb = Yc; % Fm == 0;\n return\nend\n\n% Set up the boundaries of the search and the step size\nFL = Fm; % Value at lower boundary (initially negative)\nXL = Yc; % Lower boundary of search\nif (~isinf(Xa))\n\n Xb = Yc + XstepR * (Yc - Xa); % Initial trial upper boundary\n\nelse\n\n% Find the standard deviation of the distribution\n Xmean = feval(Fmean, -Inf, Inf);\n sd = sqrt(feval(Fvar, -Inf, Inf) - Xmean^2);\n Xb = Yc + sign(Yc-Xa) * sd; % Initial test upper boundary\nend\n\nFR = -1; % Same sign as FL to indicate no zero found\nXR = Xb;\nFeps = TolF * abs(Fm); % Tolerance on integral value\nXstep = 0.5 * (Xb - Yc);\n\n% Search loop\nfor (Iter = 1:MaxIter)\n\n Fp = Fm; % Previous Fm\n Fm = feval(Fmean, Xa, Xb) - Yc*feval(Farea, Xa, Xb);\n\n% Update the end-points of the search\nif (Fm >= 0)\n FR = Fm;\n XR = Xb;\nelse\n FL = Fm;\n XL = Xb;\nend\n\n% ----- ------\n if (FR >= 0)\n% Straddling a root\n\n% Check for convergence in the function value\n% Check for convergence of the position\n if (abs(Fm) <= Feps) || ...\n (~isinf(XL) && ~isinf(XR) && ...\n abs(XR-XL) <= TolX*max(abs(XR), abs(XL)))\n return\n end\n\n% The root location is sought by cautious linear interpolation; however\n% if successive function values are nearly equal, bisection is used.\n if (abs(Fp-Fm) > EpsdF * abs(FL-FR))\n dX = FL / (FL-FR); % Estimated zero crossing position\n dX = max(min(dX, 1-EpsdX), EpsdX); % Avoid region close to XL or XR\n else\n dX = 0.5; % Bisection\n end\n Xb = XL + dX*(XR-XL);\n\n% ------ ------\n else\n% Not straddling a root\n\n% Right boundary undefined\n% Check for successive identical returned values\n if (Yc > Xa)\n if (Fm == Fp && feval(Farea, Xb, Inf) <= 0)\n Xb = NaN;\n return\n end\n else\n if (Fm == Fp && feval(Farea, -Inf, Xb) <= 0)\n Xb = NaN;\n return\n end\n end\n\n% Increase the step size\n Xb = Xb + Xstep;\n Xstep = 2 * Xstep;\n\n end\n\nend\n\nerror('QuantInterval: Failed to converge');\n", "meta": {"author": "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/QuantLloyd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7512149123350839}} {"text": "%% Gammatone-like spectrograms\n% Gammatone filters are a popular linear approximation to the\n% filtering performed by the ear. This routine provides a simple\n% wrapper for generating time-frequency surfaces based on a\n% gammatone analysis, which can be used as a replacement for a\n% conventional spectrogram. It also provides a fast approximation\n% to this surface based on weighting the output of a conventional\n% FFT. \n\n%% Introduction\n% It is very natural to visualize sound as a time-varying\n% distribution of energy in frequency - not least because this is\n% one way of describing the information our brains get from our\n% ears via the auditory nerve. The spectrogram is the traditional\n% time-frequency visualization, but it actually has some important\n% differences from how sound is analyzed by the ear, most\n% significantly that the ear's frequency subbands get wider for\n% higher frequencies, whereas the spectrogram has a constant\n% bandwidth across all frequency channels.\n% \n% There have been many signal-processing approximations proposed\n% for the frequency analysis performed by the ear; one of the most\n% popular is the Gammatone filterbank originally proposed by \n% Roy Patterson and colleagues in 1992. Gammatone filters were \n% conceived as a simple fit to experimental observations of \n% the mammalian cochlea, and have a repeated pole structure leading\n% to an impulse response that is the product of a Gamma envelope \n% g(t) = t^n e^{-t} and a sinusoid (tone).\n%\n% One reason for the popularity of this approach is the\n% availability of an implementation by Malcolm Slaney, as \n% described in:\n%\n% Malcolm Slaney (1998) \"Auditory Toolbox Version 2\", \n% Technical Report #1998-010, Interval Research Corporation, 1998. \n% http://cobweb.ecn.purdue.edu/~malcolm/interval/1998-010/\n%\n% Malcolm's toolbox includes routines to design a Gammatone \n% filterbank and to process a signal by every filter in a bank, \n% but in order to convert this into a time-frequency visualization \n% it is necessary to sum up the energy within regular time bins.\n% While this is not complicated, the function here provides a \n% convenient wrapper to achieve this final step, for applications \n% that are content to work with time-frequency magnitude\n% distributions instead of going down to the waveform levels. In\n% this mode of operation, the routine uses Malcolm's MakeERBFilters \n% and ERBFilterBank routines.\n%\n% This is, however, quite a computationally expensive approach, so\n% we also provide an alternative algorithm that gives very similar\n% results. In this mode, the Gammatone-based spectrogram is\n% constructed by first calculating a conventional, fixed-bandwidth\n% spectrogram, then combining the fine frequency resolution of the\n% FFT-based spectra into the coarser, smoother Gammatone responses\n% via a weighting function. This calculates the time-frequency\n% distribution some 30-40x faster than the full approach.\n\n%% Routines\n% The code consists of a main routine, , \n% which takes a waveform and other parameters and returns a\n% spectrogram-like time-frequency matrix, and a helper function \n% , which constructs the\n% weighting matrix to convert FFT output spectra into gammatone\n% approximations. \n\n%% Example usage\n% First, we calculate a Gammatone-based spectrogram-like image of \n% a speech waveform using the fast approximation. Then we do the \n% same thing using the full filtering approach, for comparison.\n\n% Load a waveform, calculate its gammatone spectrogram, then display:\n[d,sr] = wavread('sa2.wav');\ntic; D = gammatonegram(d,sr); toc\n%Elapsed time is 0.140742 seconds.\nsubplot(211)\nimagesc(20*log10(D)); axis xy\ncaxis([-90 -30])\ncolorbar\ntitle('Gammatonegram - fast method')\n\n% Now repeat with flag to use actual subband filters.\n% Since it's the last argument, we have to include all the other\n% arguments. These are the default values for: summation window \n% (0.025 sec), hop between successive windows (0.010 sec), \n% number of gammatone channels (64), lowest frequency (50 Hz), \n% and highest frequency (sr/2). The last argument as zero \n% means not to use the FFT approach.\ntic; D2 = gammatonegram(d,sr,0.025,0.010,64,50,sr/2,0); toc\n%Elapsed time is 3.165083 seconds.\nsubplot(212)\nimagesc(20*log10(D2)); axis xy\ncaxis([-90 -30])\ncolorbar\ntitle('Gammatonegram - accurate method')\n% Actual gammatone filters appear somewhat narrower. The fast \n% version assumes coherence of addition of amplitude from \n% different channels, whereas the actual subband energies will\n% depend on how the energy in different frequencies combines.\n% Also notice the visible time smearing in the low frequency \n% channels that does not occur in the fast version.\n\n%% Validation\n% We can check the frequency responses of the filterbank \n% simulated with the fast method against the actual filters \n% from Malcolm's toolbox. They match very closely, but of \n% course this still doesn't mean the two approaches will give \n% identical results - because the fast method ignores the phase \n% of each frequency channel when summing up.\n\n% Check the frequency responses to see that they match:\n% Put an impulse through the Slaney ERB filters, then take the \n% frequency response of each impulse response.\nfcfs = flipud(MakeERBFilters(16000,64,50));\ngtir = ERBFilterBank([1, zeros(1,1000)],fcfs);\nH = zeros(64,512);\nfor i = 1:64; H(i,:) = abs(freqz(gtir(i,:),1,512)); end\n% The weighting matrix for the FFT is the frequency response \n% of each output filter\ngtm = fft2gammatonemx(1024,16000,64,1,50,8000,512);\n% Plot every 5th channel from both. Offset by 3 dB just so we can\n% see both\nfs = [0:511]/512*8000;\nfigure\nplot(fs,20*log10(H(5:5:64,:))','b',fs, -3 + 20*log10(gtm(5:5:64,:))','r')\naxis([0 8000 -150 0])\ngrid\n% Line up pretty well, apart from wiggles below -100 dB\n% (from truncating the impulse response at 1000 samples?)\n\n%% Download\n% You can download all the code and data for these examples here:\n% .\n\n%% Referencing\n% If you use this work in a publication, I would be grateful \n% if you referenced this page as follows:\n%\n% D. P. W. Ellis (2009). \"Gammatone-like spectrograms\", web resource, http://www.ee.columbia.edu/~dpwe/resources/matlab/gammatonegram/ .\n\n%% Acknowledgment\n% This project was supported in part by the NSF under \n% grant IIS-0535168. Any opinions, findings and conclusions \n% or recommendations expressed in this material are those of the \n% authors and do not necessarily reflect the views of the Sponsors.\n\n% Last updated: $Date: 2009/02/22 01:46:42 $\n% Dan Ellis \n", "meta": {"author": "detly", "repo": "gammatone", "sha": "0626328ef7c31d3b33214db2fdcd52e8601eb4c5", "save_path": "github-repos/MATLAB/detly-gammatone", "path": "github-repos/MATLAB/detly-gammatone/gammatone-0626328ef7c31d3b33214db2fdcd52e8601eb4c5/auditory_toolkit/gammatone_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7512149045468565}} {"text": "function [coef]=ref_dwiltii_1(f,g,a,M)\n%COMP_DWILT Compute Discrete Wilson transform.\n% \n% Do not call this function directly, use DWILT instead.\n\n% Author : Peter L. Søndergaard.\n\nL=size(g,1);\nN=L/a;\nW=size(f,2);\n\nc=ref_gdgt(f,g,a,2*M,.5,0,0);\n\ncoef2=reshape(c,2*M,N,W); % ----- Type II ------\n%coef2=dgt(f,g,a,2*M);\n\ncoef=zeros(2*M,N/2,W);\n\nif 0\n % --- Loop version ---\n for n=0:N/2-1\n\n % ---- m is zero ---------\n coef(1,n+1,:)=coef2(1,2*n+1,:);\n \n for m=1:2:M-1\n % --- m is odd ----------\n coef(m+1,n+1,:)= i/sqrt(2)*(coef2(m+1,2*n+1,:)+coef2(2*M-m+1,2*n+1,:));\n coef(M+m+1,n+1,:)= 1/sqrt(2)*(coef2(m+1,2*n+2,:)-coef2(2*M-m+1,2*n+2,:));\n end;\n for m=2:2:M-1\n % --- m is even ---------\n coef(m+1,n+1,:)= 1/sqrt(2)*(coef2(m+1,2*n+1,:)-coef2(2*M-m+1,2*n+1,:));\n coef(M+m+1,n+1,:)= i/sqrt(2)*(coef2(m+1,2*n+2,:)+coef2(2*M-m+1,2*n+2,:)); \n end;\n\n % --- m is nyquest ------\n if mod(M,2)==0\n coef(M+1,n+1,:) = i*coef2(M+1,2*n+2,:);\n else\n coef(M+1,n+1,:) = i*coef2(M+1,2*n+1,:);\n end;\n \n end;\n\n\nelse\n % --- Vector version---\n\n % ---- m is zero ---------\n coef(1,:,:)=coef2(1,1:2:N,:);\n \n % --- m is odd ----------\n coef(2:2:M,:,:) = i/sqrt(2)*(coef2(2:2:M,1:2:N,:)+coef2(2*M:-2:M+2,1:2:N,:));\n coef(M+2:2:2*M,:,:)= 1/sqrt(2)*(coef2(2:2:M,2:2:N,:)-coef2(2*M:-2:M+2,2:2:N,:));\n \n % --- m is even ---------\n coef(3:2:M,:,:)= 1/sqrt(2)*(coef2(3:2:M,1:2:N,:)-coef2(2*M-1:-2:M+2,1:2:N,:));\n coef(M+3:2:2*M,:,:)= i/sqrt(2)*(coef2(3:2:M,2:2:N,:)+coef2(2*M-1:-2:M+2,2:2:N,:));\n \n % --- m is nyquest ------\n if mod(M,2)==0\n coef(M+1,:,:) = i*coef2(M+1,2:2:N,:);\n else\n coef(M+1,:,:) = i*coef2(M+1,1:2:N,:);\n end;\n\nend;\n\n\ncoef=reshape(coef,M*N,W);\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/reference/ref_dwiltii_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7512149042578328}} {"text": "function b = det(a)\n% function b=det(a)\n%\n% DESCRIPTION\n% Determinant of a matrix polynomial\n%\n% INPUTS\n% A: polynomial\n%\n% OUTPUTS\n% B: polynomial, the determinant of A\n%\n% SYNTAX\n% B = det(A);\n\n\n% 6/14/2002: PJS Initial Coding\n\nsza=size(a);\nif sza(1)~=sza(2)\n error('Matrix must be square');\nend\n\nif isempty(a)\n b = polynomial(1);\nelseif sza(1)==1\n b = a;\nelse\n L.type = '()';\n b = polynomial(0);\n for i1 = 1:sza(1);\n % Recursive cofactor expansion for det\n % XXX Faster algos for computing det exist\n L.subs = {[2:sza(1)] [1:i1-1, i1+1:sza(1)]};\n M = subsref(a,L);\n cofactor = (-1)^(1+i1)*det(M);\n \n L.subs = {1, i1};\n a1_i1 = subsref(a,L);\n b = b + a1_i1*cofactor;\n end\nend\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/det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7512046879989672}} {"text": "function euler = rotMat2euler(R)\n % from paper: \"Adaptive Filter for a Miniature MEMS Based Attitude and\n % Heading Reference System\" by Wang et al, IEEE.\n \n phi = atan2(R(3,2,:), R(3,3,:) );\n theta = -atan(R(3,1,:) ./ sqrt(1-R(3,1,:).^2) ); \n psi = atan2(R(2,1,:), R(1,1,:) );\n\n euler = [phi(1,:)' theta(1,:)' psi(1,:)']; \nend\n\n", "meta": {"author": "xioTechnologies", "repo": "Gait-Tracking-With-x-IMU", "sha": "040966bd249bb842531e495eb78e1133820c4947", "save_path": "github-repos/MATLAB/xioTechnologies-Gait-Tracking-With-x-IMU", "path": "github-repos/MATLAB/xioTechnologies-Gait-Tracking-With-x-IMU/Gait-Tracking-With-x-IMU-040966bd249bb842531e495eb78e1133820c4947/Gait Tracking With x-IMU/Quaternions/rotMat2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7512046715250614}} {"text": "function rad = deg2rad(deg) \n% \n% Function Name: \n% \n% deg2rad - Convert degrees to radians. \n% \n% Calling Sequence: \n% \n% rad = deg2rad(deg); \n% \n% Parameters: \n% \n% deg\t\t: Angle in degrees. \n% \n% rad\t\t: Angle in radians. \n% \n% Description: \n% \n% Convenient utility function for converting degrees to radians, which are \n% often the required angular units for functions in the NURBS toolbox. \n% \n% Examples: \n% \n% // Convert 35 degrees to radians \n% rad = deg2rad(35); \n \n% D.M. Spink \n% Copyright (c) 2000. \n \nrad = pi*deg/180.0; \n ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/deg2rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7512011145083484}} {"text": "function [hd, ind1, ind2] = hausdorffDistance(pts1, pts2)\n%HAUSDORFFDISTANCE Hausdorff distance between two point sets\n%\n% HD = hausdorffDistance(PTS1, PTS2)\n% Computes the Hausdorff distance between the two point sets PTS1 and\n% PTS2. The Hausdorf distance can be used to compare two shapes. \n%\n% The distance between a point x and a set Y is given by:\n% d(x, Y) = inf { d(x,y) | y in Y }\n% The distance between two non empty sets X and Y is given by:\n% d(X, Y) = sup { d(x,Y) | x in X }\n% The Hausdorff distance between sets X and Y distance is defined as the\n% maximum of d(X,Y) and d(Y,X):\n% HD(X,Y) = max { d(X,Y), d(Y,X) }\n%\n%\n% Example\n% % Compute Hausdorff distance between an ellipse and a rectangle\n% % first define two shapes\n% rect = resamplePolygon(orientedBoxToPolygon([20 30 80 40 30]), 60);\n% poly = ellipseToPolygon([20 30 40 20 30], 500);\n% % display the shapes\n% figure; hold on\n% drawPolygon(poly, 'b');\n% drawPolygon(rect, 'g');\n% axis equal;\n% % compute hausdorff distance\n% [hd ind1 ind2] = hausdorffDistance(poly, rect);\n% p1h = poly(ind1, :);\n% p2h = rect(ind2, :);\n% drawPoint([p1h;p2h], 'mo');\n% drawEdge([p1h p2h], 'm')\n%\n% See also\n% minDistancePoints\n%\n% References\n% http://en.wikipedia.org/wiki/Hausdorff_distance\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-05-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% distance from pts1 to pts2\n[dists1, ind12] = minDistancePoints(pts1, pts2);\n[max1, ind11] = max(dists1);\n\n% distance from pts2 to pts1\n[dists2, ind22] = minDistancePoints(pts2, pts1);\n[max2, ind21] = max(dists2);\n\n% keep the max of the two distances\nhd = max(max1, max2);\n\n% keep the rigt indices\nif max1 > max2\n ind1 = ind11;\n ind2 = ind12(ind11);\nelse\n ind1 = ind22(ind21);\n ind2 = ind21;\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/hausdorffDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.751165141608471}} {"text": "clear all; close all; clc\n\n\n% A=randn(10,10,10);\n% model=parafac(A,3);\n% [A1,A2,A3]=fac2let(model)\n\n\nx=-5:0.1:5; y=-6:0.1:6; t=0:0.1:10*pi;\n[X,Y,T]=meshgrid(x,y,t);\nA=exp(-(X.^2+0.5*Y.^2)).*(cos(2*T))+ ...\n (sech(X).*tanh(X).*exp(-0.2*Y.^2)).*sin(T);\n\nfor j=1:length(t)\n pcolor(x,y,A(:,:,j)), shading interp, caxis([-1 1]), drawnow\nend\n\nfigure(1)\nfor j=1:8\n subplot(2,4,j)\n pcolor(x,y,A(:,:,8*j-3)), colormap(hot), shading interp, caxis([-1 1]), axis off\nend\n\n\nfigure(2)\nmodel=parafac(A,2);\n[A1,A2,A3]=fac2let(model);\nsubplot(3,1,1), plot(y,A1,'Linewidth',[2])\nsubplot(3,1,2), plot(x,A2,'Linewidth',[2])\nsubplot(3,1,3), plot(t,A3,'Linewidth',[2])\n\nsubplot(3,1,1), set(gca,'Xtick',[-6 0 6],'Fontsize',[15])\nsubplot(3,1,2), set(gca,'Xtick',[-5 0 5],'Fontsize',[15])\nsubplot(3,1,3), set(gca,'Xlim',[0 10*pi],'Xtick',[0 5*pi 10*pi],'Xticklabels',{'0','5\\pi','10\\pi'},'Fontsize',[15])\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH01/CH01_SEC09_Tensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7510503221370106}} {"text": "function determ = circulant2_determinant ( n )\n\n%*****************************************************************************80\n%\n%% CIRCULANT2_DETERMINANT returns the determinant of the CIRCULANT2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n w = c8vec_unity ( n );\n\n lambda = zeros ( n, 1 );\n lambda(1:n) = n;\n for i = n-1 : -1 : 1\n lambda(1:n) = lambda(1:n) .* w(1:n) + i;\n end\n%\n% First eigenvalue is \"special\".\n%\n determ = real ( lambda(1) );\n%\n% Eigenvalues 2, 3 through ( N + 1 ) / 2 are paired with complex conjugates.\n%\n for i = 2 : floor ( ( n + 1 ) / 2 )\n determ = determ * ( abs ( lambda(i) ) )^2;\n end\n%\n% If N is even, there is another unpaired eigenvalue.\n%\n if ( mod ( n, 2 ) == 0 )\n determ = determ * real ( lambda((n/2)+1) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/circulant2_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7510101243538819}} {"text": "function y = wprctile(x, p, w)\n% WPRCTILE Percentiles of a weighted sample.\n%\n% Description\n% Y = PRCTILE(X, P, W) returns percentiles of the values in X. P\n% is a scalar or a vector of percent values. W is a vector of\n% unnormalized weights for samples. Length of W has to be same\n% as length of X. X need to be a a vector. Y is the same size as\n% P, and Y(i) contains the P(i)-th percentile.\n%\n% Example\n% y = prctile(x,50,w); % the median of x given sample weights w\n%\n% See also wmean, prctile\n\n% BUGS: Accepts only vector valued X\n\n% Copyright (c) 2000-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\nx=sort(x);\np=p./100;\ny=p;\nww=cumsum(w);ww=ww./ww(end);\nfor j=1:length(p)\n wi=min(find(ww>=p(j)));\n if wi==1\n y(j)=x(1);\n else\n w1=ww(wi-1);x1=x(wi-1);\n y(j)=x1+(x(wi)-x1).*(p(j)-w1)./(ww(wi)-w1);\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/misc/wprctile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217589, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7510101222497606}} {"text": "function d=sqdist(a,b)\n% SQDIST - computes squared Euclidean distance matrix\n% computes a rectangular matrix of pairwise distances\n% between points in A (given in columns) and points in B\n\n% NB: very fast implementation taken from Roland Bunschoten\n\naa = sum(a.*a,1); bb = sum(b.*b,1); ab = a'*b; \nd = abs(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab);\n\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/sqdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.751010116316974}} {"text": "function q=rotMat2Quat(R,handed)\n%%ROTMAT2QUAT Get a unit quaternion corresponding to a particular rotation\n% matrix. The quaternion can be chosen to support standard\n% right-handed quaternion multiplication rules, or non-standard\n% left-handed rules that some authors choose to use.\n%\n%INPUTS: M A 3X3 orthonormal real rotation matrix.\n% handed The handedness of the quaternion. If omitted, it is assumed\n% that the quaternion is right-handed (the standard). Possible\n% values are:\n% 'right' The default if omitted. The quaternion multiplication\n% is assumed right-handed (standard).\n% 'left' The quaternion multiplication is assumed left-handed.\n% This is used in someplaces, including the reference\n% from Shuster, below.\n%\n%OUTPUTS: q A 4X1 unit quaternion corresponding to the rotation matrix. The\n% quaternion is ordered [cos(theta/2);sin(theta/2)u'] where u is\n% a unit vector for the axis of rotation and theta is the\n% counterclockwise (right-handed) or clockwise (left-handed)\n% rotation angle about that unit vector.\n%\n%The formulae for converting a rotation matrix are from [1], where a minor\n%change has been performed to support both right and left-handed\n%quaternions. Both q and -q represent the same rotations. Here, the\n%solution is chosen so that when considering a left-handed rotation, the\n%sign of the largest magnitude element is positive. When considering a\n%right handed rotation, the sign of the largest element may or may not be\n%positive.\n%\n%A quaternion of form q(1)+i*q(2)+j*q(3)+k*q(4) that obeys right-handed\n%multiplication rules supports the following rules for multiplication of i,\n%j, and k, where an item in a row is multiplied by an item in the column to\n%get the result:\n% i, j, k\n%i -1, k,-j\n%j -k,-1, i\n%k j,-i,-1\n%On the other hand, left-handed multiplication rules flip the signs of the\n%off-diagonal terms:\n% i, j, k\n%i -1,-k, j\n%j k,-1,-i\n%k -j, i,-1\n%\n%REFERENCES:\n%[1] W. F. Phillips, C. E. Hailey, and G. A. Gebert, \"Review of attitude\n% representations used for aircraft kinematics,\" Journal of Aircraft,\n% vol. 38, no. 4, pp. 718-737, Jul. - Aug. 2001.\n%\n%August 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(handed))\n handed='right';\nend\n\nR11=R(1,1);\nR22=R(2,2);\nR33=R(3,3);\nR12=R(1,2);\nR21=R(2,1);\nR13=R(1,3);\nR31=R(3,1);\nR23=R(2,3);\nR32=R(3,2);\n\n%The square of the quaternion...\nq2=(1/4)*[1+R11+R22+R33;\n 1+R11-R22-R33;\n 1-R11+R22-R33;\n 1-R11-R22+R33];\n\nq2Max=max(q2);\n\nif(q2Max==q2(1))\n q0=0.5*sqrt(1+R11+R22+R33);\n q1=(1/(4*q0))*(R23-R32);\n q2=(1/(4*q0))*(R31-R13);\n q3=(1/(4*q0))*(R12-R21);\nelseif(q2Max==q2(2))\n q1=0.5*sqrt(1+R11-R22-R33);\n q0=(1/(4*q1))*(R23-R32);\n q2=(1/(4*q1))*(R12+R21);\n q3=(1/(4*q1))*(R31+R13);\nelseif(q2Max==q2(3))\n q2=0.5*sqrt(1-R11+R22-R33);\n q0=(1/(4*q2))*(R31-R13);\n q1=(1/(4*q2))*(R12+R21);\n q3=(1/(4*q2))*(R23+R32);\nelse\n q3=0.5*sqrt(1-R11-R22+R33);\n q0=(1/(4*q3))*(R12-R21);\n q1=(1/(4*q3))*(R31+R13);\n q2=(1/(4*q3))*(R23+R32);\nend\n\n%The above implementation provides a left-handed quaternion, so the sign of\n%the vector part needs to be flipped if the standard right-handed system is\n%used.\nswitch(handed)\n case 'right'\n q=[q0;-q1;-q2;-q3];\n case 'left'\n q=[q0;q1;q2;q3];\n otherwise\n error('Invalid handedness provided.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Rotations/rotMat2Quat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7510101157476078}} {"text": "function h = qqPlot(varargin)\n%QQPLOT Quantile-quantile plot with patch option\n%\n% IOSR.STATISTICS.QQPLOT(Y) displays a quantile-quantile plot of the\n% sample quantiles of Y versus theoretical quantiles from a normal\n% distribution. If the distribution of Y is normal, the plot will be\n% close to linear.\n% \n% IOSR.STATISTICS.QQPLOT(X,Y) displays a quantile-quantile plot of two\n% samples. If the samples come from the same distribution, the plot will\n% be linear.\n% \n% The inputs X and Y should be numeric and have an equal number of\n% elements; every element is treated as a member of the sample.\n% \n% The plot displays the sample data with the plot symbol 'x'.\n% Superimposed on the plot is a dashed straight line connecting the first\n% and third quartiles.\n% \n% IOSR.STATISTICS.QQPLOT(...,MODE) allows the appearance of the plot to\n% be configured. With MODE='line' (default), the plot appears as\n% described above. With MODE='patch', the data are plotted as a patch\n% object, with the area bound by the x-distribution and the linear fit\n% shaded grey. With mode='both' the two appearances are combined.\n% \n% IOSR.STATISTICS.QQPLOT(...,MODE,METHOD) and\n% IOSR.STATISTICS.QQPLOT(...,[],METHOD) allows the method for calculating\n% the quartiles, used for the fit line, to be specified. The default is\n% 'R-8'. Type 'help iosr.statistics.quantile' for more information. The\n% latter form of the function call uses the default mode.\n% \n% H = IOSR.STATISTICS.QQPLOT(...) returns a two- or three-element vector\n% of handles to the plotted object. The nature of the handles depends\n% upon the mode. In all cases, the first handle is to the sample data,\n% the second handle is to the fit line. With MODE='patch' or MODE='both',\n% there is third handle to the patch object.\n% \n% Example\n% \n% % Display Q-Q plots for the rand and randn functions\n% figure\n% subplot(2,1,1)\n% iosr.statistics.qqPlot(rand(20),'patch')\n% subplot(2,1,2)\n% h = iosr.statistics.qqPlot(randn(20),'patch');\n% set(h(3),'FaceColor','r') % change fill color\n% \n% See also IOSR.STATISTICS.QUANTILE, IOSR.STATISTICS.BOXPLOT.\n\n% Copyright 2016 University of Surrey.\n\n %% determine X and Y\n\n IXn = cellfun(@(x) isnumeric(x) & ~isempty(x),varargin);\n\n switch sum(IXn)\n case 0\n error('iosr:qqPlot:noData','No input data specified')\n case 1\n % compare to normal distrbution\n Y = get_input_sample(varargin,IXn);\n p = (.5:length(Y))/length(Y);\n X = sqrt(2)*erfinv(2*p - 1);\n x_label = 'Standard normal quantiles';\n y_label = 'Sample quantiles';\n case 2\n % compare to input data distribution\n Y = get_input_sample(varargin,find(IXn,1,'last'));\n X = get_input_sample(varargin,find(IXn,1,'first'));\n assert(isequal(size(X),size(Y)), 'iosr:quantile:invalidInput', 'Input data must be the same size')\n x_label = 'X quantiles';\n y_label = 'Y quantiles';\n otherwise\n error('iosr:qqPlot:unkonwnInput','Unknown input specified')\n end\n\n %% determine mode and method\n\n % find inputs\n IXc = cellfun(@(x) ischar(x) | isempty(x),varargin);\n switch sum(IXc)\n case 0\n mode = [];\n method = [];\n case 1\n mode = varargin{IXc};\n method = [];\n case 2\n mode = varargin{find(IXc,1,'first')};\n method = varargin{find(IXc,1,'last')};\n otherwise\n error('iosr:qqPlot:unknownString','Unknown string specified')\n end\n\n % defaults\n if isempty(mode)\n mode = 'line';\n end\n if isempty(method)\n method = 'R-8';\n end\n\n %% calculate fit to first and third quartile\n\n % quartiles\n q1x = iosr.statistics.quantile(X,.25,[],method);\n q3x = iosr.statistics.quantile(X,.75,[],method);\n q1y = iosr.statistics.quantile(Y,.25,[],method);\n q3y = iosr.statistics.quantile(Y,.75,[],method);\n\n % slope\n slope = (q3y-q1y)./(q3x-q1x);\n centerx = (q1x+q3x)/2;\n centery = (q1y+q3y)/2;\n\n % fit\n maxx = max(X);\n minx = min(X);\n maxy = centery + slope.*(maxx - centerx);\n miny = centery - slope.*(centerx - minx);\n\n % lines\n X_fit = linspace(minx,maxx,length(X));\n Y_fit = linspace(miny,maxy,length(X));\n\n %% plot data\n\n hold on\n\n if strcmpi(mode,'patch') || strcmpi(mode,'both')\n Hp = patch([X fliplr(X_fit)],[Y fliplr(Y_fit)],[0.5 0.5 0.5]);\n set(Hp,'edgecolor','none')\n else\n Hp = NaN;\n end\n\n switch lower(mode)\n case 'line'\n linestyle = 'xk';\n case 'patch'\n linestyle = '-k';\n case 'both'\n linestyle = 'xk';\n otherwise\n error('iosr:qqPlot:unknownMode','Unknown mode specified')\n end\n\n H = plot(X,Y,linestyle,X_fit,Y_fit,'--k');\n\n hold off\n\n % axis labels\n xlabel(x_label)\n ylabel(y_label)\n\n box on; axis tight\n set(gca,'layer','top')\n\n % return handle\n if nargout>0\n h = H;\n if isobject(Hp) || ishandle(Hp)\n h = [h; Hp];\n end\n end\n\nend\n\nfunction Z = get_input_sample(z,IX)\n%GET_INPUT_SAMPLE get sample, order, and convert to vector\n Z = z{IX};\n Z = sort(Z(:))';\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/+statistics/qqPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.7509895241981577}} {"text": "function [tm,D2]=momftfr(tfr,tmin,tmax,time);\n%MOMFTFR Frequency moments of a time-frequency representation.\n%\t[TM,D2]=MOMFTFR(TFR,TMIN,TMAX,TIME) computes the frequeny \n%\tmoments of a time-frequency representation.\n% \n%\tTFR : time-frequency representation ([Nrow,Ncol]size(TFR)). \n%\tTMIN : smallest column element of TFR taken into account\n%\t (default : 1) \n%\tTMAX : highest column element of TFR taken into account\n%\t (default : Ncol)\n%\tTIME : true time instants (default : 1:Ncol)\n%\tTM : averaged time (first order moment)\n%\tD2 : squared time duration (second order moment)\n%\n%\tExample :\n%\t sig=fmlin(128,0.1,0.4); \n%\t [tfr,t,f]=tfrwv(sig); [tm,D2]=momftfr(tfr); \n%\t subplot(211); plot(f,tm); subplot(212); plot(f,D2);\n%\n%\tSee also MOMTTFR, MARGTFR.\n\n%\tF. Auger, August 1995.\n%\tCopyright (c) 1996 by CNRS (France).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n[tfrrow,tfrcol]=size(tfr);\nif (nargin==1),\n tmin=1; tmax=tfrcol; time=tmin:tmax;\nelseif (nargin==2),\n tmax=tfrcol; time=tmin:tmax;\nelseif (nargin==3),\n time=tmin:tmax;\nend;\n\nif (tmin>tmax)|(tmin<=0)|(tmax>tfrcol),\n error('1<=TMIN<=TMAX<=Ncol');\nend;\n\nE = sum(tfr(:,tmin:tmax).');\ntm = (time * tfr(:,tmin:tmax).' ./E).'; \nD2 = (time.^2 * tfr(:,tmin:tmax).' ./E).' - tm.^2;\n\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/momftfr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7509869270649878}} {"text": "function d = distToEpipolarLine(F, p1, p2)\n%% Given a fundamental matrix F, compute the matched point pair to their \n% corresponding epipolarlines' distances, then sum the two distances.\n% Extracted from Matlab built-in function estimateFundamentalMatrix.m\n\n% Very important: F must map a point p1 to an epipolar line in p2 image space, not the other way around.\n% More details: http://stackoverflow.com/questions/26582960/sampson-error-for-five-point-essential-matrix-estimation\n\n%% License\n% ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY\n% Copyright (c) 2018 Bingyao Huang\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 met:\n\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n\n% If you publish results obtained using this software, please cite our paper.\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 THE\n% SOFTWARE.\n\n% convert to homogenious \np1 = [p1, ones(size(p1,1),1)]';\np2 = [p2, ones(size(p2,1),1)]';\n\n% euclidean distance \nd = sum(p2.*(F*p1), 1) .^ 2;\n\n% sampson distance \nepl1 = F * p1;\nepl2 = F' * p2;\nd = d ./ (epl1(1,:).^2 + epl1(2,:).^2 + epl2(1,:).^2 + epl2(2,:).^2);\nend\n", "meta": {"author": "BingyaoHuang", "repo": "single-shot-pro-cam-calib", "sha": "cd7fda6b98d86175ccb4a5a0669998f311c55b00", "save_path": "github-repos/MATLAB/BingyaoHuang-single-shot-pro-cam-calib", "path": "github-repos/MATLAB/BingyaoHuang-single-shot-pro-cam-calib/single-shot-pro-cam-calib-cd7fda6b98d86175ccb4a5a0669998f311c55b00/+Reconstruct/distToEpipolarLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7509260032295896}} {"text": "function [ fx, fy ] = f01_f1 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% F01_F1 returns first derivatives of function 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N,1), Y(N,1), the evalution points.\n%\n% Output, real FX(N,1), FY(N,1), the derivative values.\n%\n t1(1:n,1) = exp ( - ( ( 9.0 * x(1:n,1) - 2.0 ).^2 ...\n + ( 9.0 * y(1:n,1) - 2.0 ).^2 ) / 4.0 );\n t2(1:n,1) = exp ( - ( ( 9.0 * x(1:n,1) + 1.0 ).^2 ) / 49.0 ...\n - ( 9.0 * y(1:n,1) + 1.0 ) / 10.0 );\n t3(1:n,1) = exp ( - ( ( 9.0 * x(1:n,1) - 7.0 ).^2 ...\n + ( 9.0 * y(1:n,1) - 3.0 ).^2 ) / 4.0 );\n t4(1:n,1) = exp ( - ( 9.0 * x(1:n,1) - 4.0 ).^2 ...\n - ( 9.0 * y(1:n,1) - 7.0 ).^2 );\n\n fx(1:n,1) = ...\n - 3.375 * ( 9.0 * x(1:n,1) - 2.0 ) * t1 ...\n - ( 27.0 / 98.0 ) * ( 9.0 * x(1:n,1) + 1.0 ) * t2 ...\n - 2.25 * ( 9.0 * x(1:n,1) - 7.0 ) * t3 ...\n + 3.6 * ( 9.0 * x(1:n,1) - 4.0 ) * t4;\n\n fy(1:n,1) = ...\n - 3.375 * ( 9.0 * y(1:n,1) - 2.0 ) * t1 ...\n - 0.675 * t2 ...\n - 2.25 * ( 9.0 * y(1:n,1) - 3.0 ) * t3 ...\n + 3.6 * ( 9.0 * y(1:n,1) - 7.0 ) * t4;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp_2d/f01_f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7509260003206165}} {"text": "% This is an approximation of random numbers wrt to wrapped Normal Distrib\n%\n% Any neater, faster, more precise and accurate generator is very welcome.\n%\n% Copyright (c) 2012 University of Crete - Computer Science Department (UOC-CSD)\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction wgr = wrappednormrnd(mu, sigma, n, pregen)\n\n if nargin<4; pregen=false; end\n\n % The CDF is symetric around the mean. Thus, just need zero-mean random values\n % of unitary std and scale them wrt sigma.\n wgr = wrappednormrndunitystd(n, pregen);\n\n wgr = sigma.*wgr;\n\n wgr = wrap(wgr + mu);\n\nreturn\n\n\nfunction wgr = wrappednormrndunitystd(n, pregen)\n\n if nargin<2; pregen=0; end\n\n if pregen==1\n global wrappednormrnd;\n\n % If run for the first time, initialize the cumulative distrib fns\n if isempty(wrappednormrnd) || ~isfield(wrappednormrnd, 'icdf')\n fprintf('wrappednormrnd.m: Pre-compute the cumulative distribution function once for all ... ');\n\n xs = -pi:(2*pi)/1e6:pi;\n xs = xs(1:end-1);\n cdf = wrappednormcdf(xs, 0, 1);\n % Resample the inverse CDF with 1 million uniform steps\n % This also assumes that we don't need a thinner resolution of the distribution\n wrappednormrnd.icdf_ys = (0:1e-4:1);\n wrappednormrnd.icdf = interp1(cdf, xs, wrappednormrnd.icdf_ys, 'linear', 'extrap').';\n\n fprintf('done.\\n');\n if nargin==0; return; end\n end\n\n % wgr = interp1(wrappednormrnd.icdf_ys, sigma*wrappednormrnd.icdf, rand(n,1), 'linear', 'extrap');\n % The following is a speed-up version of the above line.\n ri = (length(wrappednormrnd.icdf)-1)*rand(n,1)+1;\n rfi = floor(ri);\n rci = ceil(ri);\n wgr = wrappednormrnd.icdf(rfi);\n wgr = wgr + (ri-rfi).*(wrappednormrnd.icdf(rci)-wgr);\n\n % % Or a faster sampling (implies only 1e4 different random values can be generated).\n % idx = round(length(wrappednormrnd.icdf)*rand(n,1))+1;\n % idx = max(1,min(length(wrappednormrnd.icdf),idx));\n % wgr = wrappednormrnd.icdf(idx);\n else\n % The non-optimized random generator\n xs = -pi:(2*pi)/1e6:pi;\n xs = xs(1:end-1);\n cdf = wrappednormcdf(xs, 0, 1);\n\n wgr = interp1(cdf, xs, rand(n,1), 'linear', 'extrap');\n end\n\nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/misc/wrappednormrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7509260001036934}} {"text": "function [ u_i ] = rotate_b2i( u_b, phi, theta, psi )\n% ROTATE_B2I - Rotation of an object (vector/matrix) from the body to the \n% inertial 3D-space\n%\n%\n%\n\n cr = cos(phi);\n cp = cos(theta);\n cy = cos(psi);\n sr = sin(phi);\n sp = sin(theta);\n sy = sin(psi);\n \n % Rotation matrix from inertial frame to body frame\n\n Rbi = [cp*cy, sr*sp*cy-cr*sy, cr*sp*cy+sr*sy;...\n cp*sy, sr*sp*sy+cr*cy, cr*sp*sy-sr*cy;...\n -sp, sr*cp, cr*cp];\n \n u_i = Rbi*u_b;\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/math_tools/rotate_b2i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7509259982793351}} {"text": "% Steady state transport solutions for one Pe=0 and various values of Da2\nx = [0:0.01:1];\nDa2 = 8; mu1 = sqrt(Da2); mu2 = -mu1;\ns = mu2*exp(mu2)-mu1*exp(mu1);\nc = (mu2*exp(mu2)*exp(mu1*x)-mu1*exp(mu1)*exp(mu2*x))./s\nfor Da2 = [4 2 1 0.5 0.25 0.125];\n s = sqrt(Da2); mu1 = s; mu2 = -s;\n s = mu2*exp(mu2)-mu1*exp(mu1);\n c = [c;(mu2*exp(mu2)*exp(mu1*x)-mu1*exp(mu1)*exp(mu2*x))./s];\nend\nplot (x,c);\nlegend('Da_2=8','Da_2=4','Da_2=2','Da_2=1','Da_2=0.5','Da_2=0.25','Da_2=0.125');\nxlabel ('x/L [-]'); ylabel ('c/c_{in} [-]');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15646-environmental-modeling/analtrans_s1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7509259367742436}} {"text": "function varargout = gallery(name)\n%CHEB.GALLERY Chebfun example functions.\n% F = CHEB.GALLERY(NAME) returns a chebfun or a quasimatrix corresponding to\n% NAME. See the listing below for available names.\n%\n% For example, plot(cheb.gallery('zigzag')) plots a degree 10000 polynomial\n% that doesn't look like a polynomial, and plot(cheb.gallery('gamma')) shows\n% a chebfun with poles. For details of how each function is constructed, try\n% type +cheb/gallery or edit cheb.gallery.\n%\n% [F,FA] = CHEB.GALLERY(NAME) also returns the anonymous function FA used to\n% define the function. Some gallery functions are generated by operations\n% beyond the usual Chebfun constructor (e.g. by solving ODEs), so FA in those\n% cases simply evaluates the chebfun.\n%\n% CHEB.GALLERY with no input argument returns a random function from the\n% gallery.\n%\n% CHEB.GALLERY with no output argument creates a plot of the selected\n% function.\n%\n% airy Airy Ai function on [-40,40]\n% bessel Bessel function J_0 on [-100,100]\n% bump C-infinity function with compact support\n% blasius Blasius function on [0,10]\n% chirp Sine with exponentially increasing frequency\n% daubechies Approximation to Daubechies phi_2 wavelet scaling function\n% erf Error function on [-10,10]\n% fishfillet Wild oscillations from Extreme Extrema example\n% gamma Gamma function on [-4,4]\n% gaussian Gaussian function on [-Inf,Inf]\n% jitter A piecewise constant function generated by ROUND\n% kahaner Challenging integrand with four spikes\n% motto Chebfun motto (Gilbert Strang)\n% random Polynomial interpolant through random data in Chebyshev points\n% rose A complex-valued sinusoid\n% runge Runge function\n% seismograph Tanh plus growing oscillation\n% Si Sine integral on [-50,50]\n% sinefun1 As smooth as it looks\n% sinefun2 Not as smooth as it looks\n% spikycomb 25 peaks, each sharper than the last\n% stegosaurus max(wiggly, x/10)\n% vandercheb Chebyshev-Vandermonde quasimatrix\n% vandermonde Vandermonde quasimatrix\n% wiggly One of the Chebfun team's favorites\n% wild An iteratively defined function on [-1 1]\n% zigzag Degree 10000 polynomial that looks piecewise linear\n%\n% Gallery functions are subject to change in future releases of Chebfun.\n%\n% See also CHEB.GALLERYTRIG, CHEB.GALLERY2, CHEB.GALLERY3, CHEB.GALLERYDISK, CHEB.GALLERYSPHERE.\n\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 random function from the\n% gallery.\nif ( nargin == 0 )\n % NOTE [AB, 2014/12/01]: This is not a particularly scalable way of\n % implementing cheb.gallery. A better approach would be that each gallery\n % function lived in a separate m-file, and could return it's name,\n % description, and the required outputs, F and FA. That way, we would get\n % rid of the switch statement below. Furthermore, this would make the\n % testing of gallery easier, as we wouldn't have to update the list of\n % input options there.\n names = {'airy', 'bessel', 'blasius', 'bump', ...\n 'chirp', 'daubechies', 'erf', 'fishfillet', 'gamma', 'gaussian', ...\n 'jitter', 'kahaner', 'motto', 'random', 'rose', 'runge', ...\n 'seismograph', 'Si', 'sinefun1', 'sinefun2', 'spikycomb', ...\n 'stegosaurus', 'vandercheb', 'vandermonde', 'wiggly', 'wild', 'zigzag'};\n name = names{randi(length(names))};\nend\n\n% If nargout == 0, then the function is plotted. Each function in the gallery\n% has its own plotting preferences.\nylims = [];\naxispref = {};\n\n% The main switch statement.\nswitch lower(name)\n\n % Airy Ai function on [-40,40]:\n case 'airy'\n fa = @airy;\n f = chebfun(fa, [-40 40]);\n ylims = [-.75 .75];\n\n % Bessel function with parameter 0 on [-100,100]:\n case 'bessel'\n fa = @(x) besselj(0, x);\n f = chebfun(fa, [-100 100]);\n ylims = [-.5 1.1];\n\n % Blasius function on [0,10]:\n case 'blasius'\n op = @(u) 2*diff(u,3) + u.*diff(u,2);\n bc = @(x,u) [u(0); feval(diff(u),0); feval(diff(u),10)-1];\n N = chebop(op, [0 10], bc);\n N.init = chebfun([3.55542; 4.25907; 0.43669; -0.21367;\n 0.06382; -0.00118; -0.00865; 0.00306], [0 10], 'coeffs');\n f = N\\0;\n fa = @(x) f(x);\n ylims = [-.5 9];\n\n % Bump function:\n case 'bump'\n fa = @(x) (abs(x) < 1).*exp(-1./(1-x.^2));\n f = chebfun(fa, [-2 2]);\n\n % Sine with exponentially increasing frequency:\n case 'chirp'\n fa = @(x) sin(x.*exp(x));\n f = chebfun(fa, [0 5]);\n ylims = [-2 2];\n\n % Approx to Daubechies phi_2 wavelet scaling function:\n case 'daubechies'\n f = daubechies(10);\n fa = @(x) f(x);\n ylims = [-.5 1.5];\n\n % Error function on [-10,10]:\n case 'erf'\n fa = @erf;\n f = chebfun(fa, [-10 10]);\n\n % Wild oscillations from Extreme Extrema example:\n case 'fishfillet'\n fa = @(x) cos(x).*sin(exp(x));\n f = chebfun(fa, [0 6]);\n ylims = [-1.2 1.2];\n\n % Gamma function on [-4,4]:\n case 'gamma'\n fa = @gamma;\n f = chebfun(fa, [-4 4], 'blowup', 'on', 'splitting', 'on');\n\n % Gaussian function on [-Inf,Inf]:\n case 'gaussian'\n fa = @(x) exp(-x.^2/2)/sqrt(2*pi);\n f = chebfun(fa, [-Inf Inf]);\n ylims = [-.05 .45];\n\n % A piecewise constant function generated by ROUND:\n case 'jitter'\n fa = @(x) round(exp(x)*2.*sin(8*x));\n f = chebfun(fa, 'splitting', 'on');\n ylims = [-5 6];\n\n % Challenging integrand with four spikes:\n case 'kahaner'\n fa = @(x) sech(10*(x-0.2)).^2 + sech(100*(x-0.4)).^4 + ...\n sech(1000*(x-0.6)).^6 + sech(1000*(x-0.8)).^8;\n f = chebfun(fa, [0 1]);\n ylims = [-.1 1.2];\n\n % (Scribbled) Chebfun motto by Gilbert Strang:\n case 'motto'\n f = exp(3i*scribble('there is no fun like chebfun'));\n fa = @(x) f(x);\n axispref = {'equal', [-1 1 -1 1]*1.2, 'off'};\n\n % Polynomial interpolant through random data in Chebyshev points:\n case 'random'\n f = chebfun(rand(100,1));\n fa = @(x) f(x);\n\n % Rose curve:\n case 'rose'\n m = 5;\n n = 4;\n fa = @(t) cos(m/n*t).*cos(t) + 1i*cos(m/n*t).*sin(t);\n f = chebfun(fa, [0, 8*pi], 'trig');\n axispref = {'equal', [-1 1 -1 1]*1.2};\n\n % Runge function:\n case 'runge'\n fa = @(x) 1./(1 + x.^2);\n f = chebfun(fa, [-5 5]);\n ylims = [0 1.2];\n\n % Tanh plus growing oscillation from ATAP, Chapter 5:\n case 'seismograph'\n fa = @(x) tanh(20*sin(12*x)) + .02*exp(3*x).*sin(300*x);\n f = chebfun(fa);\n\n % Sine integral:\n case 'si'\n f = cumsum(chebfun(@(x) sin(x)./(x), [-50, 50]));\n fa = @(x) f(x);\n\n % As smooth as it looks:\n case 'sinefun1'\n fa = @(x) (1.75 + sin(50*x));\n f = chebfun(fa);\n\n % Not as smooth as it looks:\n case 'sinefun2'\n fa = @(x) (1.75 + sin(50*x)).^1.0001;\n f = chebfun(fa);\n\n % 25 peaks, each sharper than the last from ATAP, Chapter 18:\n case 'spikycomb'\n fa = @(x) exp(x).*sech(4*sin(40*x)).^exp(x);\n f = chebfun(fa);\n\n % max(wiggly, x/10):\n case 'stegosaurus'\n fa = @(x) max(sin(x)+sin(x.^2), x/10);\n f = chebfun(fa, [0 10], 'splitting', 'on');\n ylims = [-.2 2.2];\n\n % Chebyshev-Vandermonde quasimatrix:\n case 'vandercheb'\n f = chebpoly(0:5);\n f = simplify(cheb2quasi(f));\n fa = @(x) f(x);\n ylims = [-1.2 1.2];\n\n % Vandermonde quasimatrix:\n case 'vandermonde'\n fa = @(x) x.^(0:5);\n f = chebfun(fa, 'vectorize');\n f = simplify(cheb2quasi(f));\n ylims = [-1.2 1.2];\n\n % One of the Chebfun team's favorites:\n case 'wiggly'\n fa = @(x) sin(x) + sin(x.^2);\n f = chebfun(fa, [0 10]);\n ylims = [-2.4 2.4];\n \n % An example from one of the first Chebfun papers (Trefethen, 2007):\n case 'wild'\n fa = @(x) wild(x); % Defined below.\n f = chebfun(fa, [-1 1]);\n ylims = [5.5 9.5];\n\n % Degree 10000 polynomial that looks piecewise linear from ATAP appendix:\n case 'zigzag'\n f = cumsum(chebfun(@(t) sign(sin(100*t./(2-t))), 10000));\n fa = @(x) f(x);\n\n % Raise an error if the input is unknown.\n otherwise\n error('CHEB:GALLERY:unknown:unknownFunction', ...\n 'Unknown function.')\nend\n\n% Only return something if there is an output argument.\nif ( nargout > 0 )\n varargout = {f, fa};\nelse\n % Otherwise, plot the function.\n plot(f)\n title([name ', length = ' num2str(length(f))])\n if ( ~isempty(ylims) )\n ylim(ylims)\n end\n if ( ~isempty(axispref) )\n axis(axispref{:})\n end\n shg\nend\n\nend\n\n\nfunction f = daubechies(n)\n% nth order polynomial approximation to Daubechies scaling function phi_2\n[x, phi] = daub(n);\nf = chebfun([phi'; 0], [0 3], 'equi');\n\n function [x, phi] = daub(n)\n s = sqrt(3);\n if ( n == 0 )\n % Base case of recursion.\n x = 0:2;\n phi = [0, (1+s)/2, (1-s)/2];\n else\n c = [1+s, 3+s, 3-s, 1-s]/4;\n % Recursively call the daub() method.\n [x2, phi2] = daub(n-1);\n pp = [phi2, 0*phi2];\n N = 2^(n-1);\n ii = 1:6*N;\n phi = c(1)*pp(ii);\n for k = 2:4\n ii = ii([(5*N + 1):6*N, 1:5*N]);\n phi = phi + c(k)*pp(ii);\n end\n x = [x2, x2+3]/2;\n end\n end\n\nend\n\nfunction s = wild(x)\n% The 'wild' function from Computing Numerically with Functions, Trefethen 2007.\nf = sin(pi*x);\ns = f;\nfor j = 1:15\n f = (3/4)*(1 - 2*f.^4);\n s = s + f;\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/+cheb/gallery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.9032942073547149, "lm_q1q2_score": 0.7507667119478757}} {"text": "% 2D Lattice Boltzmann (BGK) model of a fluid.\n% c4 c3 c2 D2Q9 model. At each timestep, particle densities propagate\n% \\ | / outwards in the directions indicated in the figure. An\n% c5 -c9 - c1 equivalent 'equilibrium' density is found, and the densities\n% / | \\ relax towards that state, in a proportion governed by omega.\n% c6 c7 c8\n% Iain Haslam, April 2006.\n\nomega=1.0; density=1.0; t1=4/9; t2=1/9; t3=1/36; c_squ=1/3; nx=1; ny=101;\nF=repmat(density/9,[nx ny 9]); F_EQ=F; msize=nx*ny; qi=[0:msize:msize*7];\nbound=zeros(nx,ny); bound(:,[1 ny])=1;%bound([14:19],[14:16])=1;\nobs=find(bound); \nbounds_to_bounce=[obs+qi(1) obs+qi(2) obs+qi(3) obs+qi(4) ... \n\tobs+qi(5) obs+qi(6) obs+qi(7) obs+qi(8)];\nbounds_bounced=[obs+qi(5) obs+qi(6) obs+qi(7) obs+qi(8) ...\n\tobs+qi(1) obs+qi(2) obs+qi(3) obs+qi(4)];\navu=1; prevavu=1; ts=0; deltaU=1e-9; numactivenodes=sum(sum(1-bound));\n\nwhile (ts<100000 & 1e-10.\n\n% Length of time series\nn = size(x,1);\n\n% De-mean time series\nx = x - ones(size(x))*diag(mean(x));\n\n% Get the autocovariance\nf = fft(x);\nfsq = f.*conj(f);\ny = ifft(fsq)/n;\n\n% Get the autocorrelation (the next line is equivalent to y = y*diag(1./y(1,:));)\ny = y*diag(1./var(x,1));\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_autocorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7507496338344163}} {"text": "function legendre_exactness ( n, x, w, p_max )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_EXACTNESS investigates exactness of Legendre quadrature.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points in the rule.\n%\n% Input, real X(N), the quadrature points.\n%\n% Input, real W(N), the quadrature weights.\n%\n% Input, integer P_MAX, the maximum exponent.\n% 0 <= P_MAX.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Quadrature rule for Legendre integral.\\n' );\n fprintf ( 1, ' Rule of order N = %d\\n', n );\n fprintf ( 1, ' Degree Relative Error\\n' );\n fprintf ( 1, '\\n' );\n\n for p = 0 : p_max\n\n s = legendre_integral ( p );\n\n v(1:n,1) = x(1:n) .^ p;\n\n q = w' * v;\n\n if ( s == 0.0 )\n e = abs ( q - s );\n else\n e = abs ( ( q - s ) / s );\n end\n\n fprintf ( 1, ' %6d %24.16f\\n', p, e );\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/exactness/legendre_exactness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.750749410551883}} {"text": "function plterrel(xo,yo,C,s,ltype)\n% PLTERREL Plots an error ellipse on screen.\n% Note 1: x & y represent north & south (opposite of\n% normal MatLab convention). Note 2: use a square\n% aspect ratio for plot; i.e., use axis('square')\n% command. Non-vectorized.\n% Version: 18 Jan 96\n% Useage: plterrel(xo,yo,C,s,ltype)\n% Input: xo - x (north) origin of ellipse\n% yo - y (east) origin of ellipse\n% C - covariance matrix (2x2)\n% s - ellipse scale factor (default=1)\n% ltype - line type for error ellipse\n% (default=solid,red)\n% Output: Plotted error ellipse centred at (xo,yo)\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nif nargin<3\n error('Too few input arguements');\nend\nif nargin<4\n s=1; % Define default scale factor\nend\nif nargin<5\n ltype='-r'; % Define default color red\nend\ndt=0.1; % Angular resolution\nt=[(0:dt:2*pi)';0];\n[V,D]=eig(C); % Eigenvalues & vectors\nr=sqrt(diag(D)); % Length of axes\nx=s*r(1)*cos(t);\ny=s*r(2)*sin(t);\nxx=xo+[x y]*V(1,:)';\nyy=yo+[x y]*V(2,:)';\nplot(yy,xx,ltype); % Switch x (north) & y (east)\n", "meta": {"author": "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/plterrel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7507424287696359}} {"text": "function fa = cmd3(a, om, omt)\n% calculate the growth factor using 1/(ah)^3\n% t0 is (1 - om)/om with om the relative matter density\n\n\n%fa = (a ./ (1 + a .^3 * t0)) .^ 1.5;\n\nfa = (a ./ (om + (omt - om) .* a.^3 + (1 - omt) .* a)) .^1.5;\n", "meta": {"author": "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/cmd3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.750742425391363}} {"text": "function [intersects, edgeIndices] = intersectLinePolyline(line, poly, varargin)\n%INTERSECTLINEPOLYLINE Intersection points between a line and a polyline.\n%\n% P = intersectLinePolyline(LINE, POLY)\n% Returns the intersection points of the lines LINE with polyline POLY. \n% LINE is a 1-by-4 row vector containing parametric representation of the\n% line (in the format [x0 y0 dx dy], see the function 'createLine' for\n% details). \n% POLY is a NV-by-2 array containing coordinates of the polyline vertices\n% P is a K-by-2 array containing the coordinates of the K intersection\n% points.\n%\n% P = intersectLinePolyline(LINE, POLY, TOL)\n% Specifies the tolerance for geometric tests. Default is 1e-14.\n%\n% [P INDS] = intersectLinePolyline(...)\n% Also returns the indices of edges involved in intersections. INDS is a\n% K-by-1 column vector, such that P(i,:) corresponds to intersection of\n% the line with the i-th edge of the polyline. If the intersection occurs\n% at a polyline vertex, the index of only one of the two neighbor edges\n% is returned. \n% Note that due to numerical approximations, the use of function\n% 'isPointOnEdge' may give results not consistent with this function.\n%\n%\n% Examples\n% % compute intersections between a square and an horizontal line\n% poly = [0 0;10 0;10 10;0 10];\n% line = [5 5 1 0];\n% intersectLinePolyline(line, poly)\n% ans =\n% 10 5\n% % also return indices of edges\n% [inters inds] = intersectLinePolyline(line, poly)\n% inters =\n% 10 5\n% inds =\n% 2\n% \n% % compute intersections between a square and a diagonal line\n% poly = [0 0;10 0;10 10;0 10];\n% line = [5 5 1 1];\n% intersectLinePolyline(line, poly)\n% ans =\n% 0 0\n% 10 10\n%\n% See also \n% lines2d, polylines2d, intersectLines, intersectLinePolygon\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2003-10-31\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n% get computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% create the array of edges\nN = size(poly, 1);\nedges = [poly(1:N-1, :) poly(2:N, :)];\n\n% compute intersections with supporting lines of polyline edges\nsupportLines = edgeToLine(edges);\nintersects = intersectLines(line, supportLines, tol);\n\n% find edges that are not parallel to the input line\ninds = find(isfinite(intersects(:, 1)));\n\n% compute position of intersection points on corresponding lines\npos = linePosition(intersects(inds, :), supportLines(inds, :), 'diag');\n\n% and keep only intersection points located on edges\nb = pos > -tol & pos < 1+tol;\ninds = inds(b);\nintersects = intersects(inds, :);\n\n% remove multiple vertices (can occur for intersections located at polyline\n% vertices)\n[intersects, I, J] = unique(intersects, 'rows'); %#ok\n\nif nargout > 1\n % return indices of edges involved in intersection\n % (in case of intersection located at a vertex, only one of the\n % neighbor edges is returned)\n edgeIndices = inds(I);\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/polygons2d/intersectLinePolyline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7507180570357505}} {"text": "function [N, D] = ratpolyfit(x,y,kn,kd)\n% Ratpolyfit Rational Polynomial Fitting\n%\n% This programs finds 2 polynomials N(x) and D(x),\n% of user given order kn and kd respectively,\n% such that N(xi)/D(xi) ~= y(xi) in a least squares sense.\n%\n%usage: [N, D] = ratpolyfit(x, y, kn, kd)\n%\n%note: kn and kd must be large enough to get a good fit.\n% usually, kn=kd gives good results\n%\n%note: If you \"overfit\" the data, then you will usually have pole-zero\n% cancellations and/or poles and zeros with a very large magnitude.\n% If that happens, then reduce the values of kn and/or kd\n%\n%note: Often, if you have a good fit, you will find that your polynomials\n% have roots where the real function has zeros and poles. \n%\n%note: Polynomial curve fitting becomes ill conditioned\n% as the range of x increases and as kn and kd increase\n%\n%note: If you think that your function goes to infinity at some x value\n% then make sure y(xi) is set equal to Inf at that point.\n% The program will compensate for all +/- Inf values\n%\n%For example, here's a rational polynomial approximation to the Gamma function:\n% x=[-5:1/32:5]'; y=gamma(x);\n% [N, D]=ratpolyfit(x,y,10,10);\n% figure(1); plot(roots(N),'ob'); hold on; plot(roots(D),'xr'); grid on \n% yy=polyval(N,x)./polyval(D,x);\n% figure(2);plot(x,y,'b', x,yy,'dr'); grid on; axis([min(x) max(x) -25 25]);\n%\n%other demos are in the text listing at the end of this program\n%\n%tested under version 6.5 (R13)\n%\n%see also: polyfit, padefit, polyval, vander\n%\n\n%Paul Godfrey\n%pgodfrey@conexant.com\n%May 31, 2006\n\n%default length if none given\nif exist('kn','var')\n kn=round(real(kn));\n if kn<0, kn=0; end\nelse\n kn=5;\nend\nif exist('kd','var')\n kd=round(real(kd));\n if kd<0, kd=0;end\nelse\n kd=5;\nend\n\nx=x(:);\ny=y(:);\n\n% we must remove +/- Inf values from y first\n% and insert those as separate poles at the end\np=find(~isfinite(y)); % find Nan 0/0 and Inf a/0 values\n% or find abs(y) values > than some really big number\n\ndinf=[];\nwhile length(p)>0\n y=y.*(x-x(p(1))); %adjust remaining y values\n y(p(1))=[]; % remove bad y value, now a NaN\n dinf=[dinf; x(p(1))]; % remember where pole was \n x(p(1))=[]; % now remove that x value too\n if kd>0, kd=kd-1; end; %reduce expected order of den\n p=find(~isfinite(y)); % have all Inf values been removed yet?\nend\n\nyy=length(y);\nan=ones(yy,kn+1);\nfor k=kn:-1:1\n an(:,k)=x.*an(:,k+1); % form vandermonde matrix\nend\n\nad=ones(yy,kd+1);\nfor k=kd:-1:1\n ad(:,k)=x.*ad(:,k+1);\nend\nfor k=1:yy\n ad(k,:)=y(k)*ad(k,:);\nend\n\n% A is basically N-y*D\nA=[an -ad]; % LS solution is in the null space of A\n\n[u,s,v]=svd(A); % null space is in the cols of V\nND=v(:,end); % use the \"most null\" vector\n\nN=ND(1:kn+1).';\nD=ND(kn+2:end).';\n\nD1=D(1);\nif D1==0; D1=1; end\n% we have to make the D polynomial monic since thats\n% what poly makes, so we have to first adjust N\nN=N/D1;\nD=D/D1;\n% and then add the removed +/- Inf poles back in\nD=poly([dinf; roots(D)]);\n\nDmax=max(abs(D));\nif Dmax==0; Dmax=1; end\n% normalize max Den value to be +/- 1\nN=N/Dmax;\nD=D/Dmax;\n\nreturn\n\n%a demo of this program is\nclc\nclear all\nclose all\nx=[-5:1/16:5]';\n\ny=gamma(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(1);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -15 15]);\n\ny=erf(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(2);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -1.5 1.5]);\n\ny=1./(1+x.*x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(3);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) 0 1]);\n\ny=tan(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(4);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -5 5]);\n\ny=exp(-x.*x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(5);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) 0 1]);\n\ny=zeta(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(6);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -2 2]);\n\ny=psi(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(7);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -5 5]);\n\nx=x-min(x);\n\ny=log(x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(8);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -5 5]);\n\nx=(x-min(x))*pi/2;\n\ny=besselj(0,x);\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(9);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -0.5 1]);\n\ny=sin(x)./x;\n[N, D]=ratpolyfit(x,y,10,10);\nyy=polyval(N,x)./polyval(D,x);\nfigure(10);plot(x,y,'b', x,yy,'dr');\ngrid on; axis([min(x) max(x) -0.5 1]);\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/11197-rational-polynomial-curve-fitting/ratpolyfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7507180454298374}} {"text": "function [ nin, pi ] = triangle_line_imp_int_2d ( a, b, c, t, nin, pi )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_LINE_IMP_INT_2D finds where an implicit line intersects a triangle in 2D.\n%\n% Discussion:\n%\n% An implicit line is the set of points ( X, Y ) satisfying\n%\n% A * X + B * Y + C = 0\n%\n% where at least one of A and B is not zero.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, determine the equation of the line:\n% A*X + B*Y + C = 0.\n%\n% Input, real T(2,3), the triangle vertices.\n%\n% Output, integer NIN, the number of points of intersection\n% of the line with the triangle. NIN may be 0, 1, 2 or 3.\n%\n% Output, real PI(2,3), contains the intersection points.\n%\n dim_num = 2;\n\n nin = 0;\n\n for i = 1 : 3\n\n j = i4_wrap ( i+1, 1, 3 );\n%\n% Get the implicit form of the line through vertices I and I+1.\n%\n [ a1, b1, c1 ] = line_exp2imp_2d ( t(1:2,i), t(1:2,j) );\n%\n% Seek an intersection with the original line.\n%\n [ ival, p ] = lines_imp_int_2d ( a, b, c, a1, b1, c1 );\n%\n% If there is an intersection, determine if it lies between the two vertices.\n%\n if ( ival == 1 )\n\n test1 = ( p(1:dim_num)' - t(1:dim_num,i) )' ...\n * ( t(1:dim_num,j) - t(1:dim_num,i) );\n test2 = ( t(1:dim_num,j) - t(1:dim_num,i) )' ...\n * ( t(1:dim_num,j) - t(1:dim_num,i) );\n\n if ( 0 <= test1 & test1 <= test2 )\n nin = nin + 1;\n pi(1:dim_num,nin) = p(1:dim_num)';\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/geometry/triangle_line_imp_int_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7507180451274825}} {"text": "function coeffs = fitPolynomialTransform2d(pts, ptsRef, degree)\n%FITPOLYNOMIALTRANSFORM2D Coefficients of polynomial transform between two point sets.\n%\n% COEFFS = fitPolynomialTransform2d(PTS, PTSREF, DEGREE)\n%\n% Example\n% \n% See also \n% polynomialTransform2d, fitAffineTransform2d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@nantes.inra.fr\n% Created: 2013-11-05, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013-2022 INRA - Cepia Software Platform\n\n%% Extract data\n\n% ensure degree is valid\nif nargin < 3\n degree = 3;\nend\n\n% polygon coordinates\nxi = pts(:,1);\nyi = pts(:,2);\nnCoords = size(pts, 1);\n\n% check inputs have same size\nif size(ptsRef, 1) ~= nCoords\n error('fitPolynomialTransform2d:sizeError', ...\n 'input arrays must have same number of points');\nend\n \n\n%% compute coefficient matrix\n\n% number of coefficients of polynomial transform\nnCoeffs = prod(degree + [1 2]) / 2;\n\n% initialize matrix\nA1 = zeros(nCoords, nCoeffs);\n\n% iterate over degrees\niCoeff = 0;\nfor iDegree = 0:degree\n \n % iterate over binomial coefficients of a given degree\n for k = 0:iDegree\n iCoeff = iCoeff + 1;\n A1(:, iCoeff) = ones(nCoords, 1) .* power(xi, iDegree-k) .* power(yi, k);\n end\nend\n\n% concatenate matrix for both coordinates\nA = kron(A1, [1 0;0 1]);\n\n\n%% solve linear system that minimizes least squares\n\n% create the vector of expected values\nb = ptsRef';\nb = b(:);\n\n% solve the system\ncoeffs = (A \\ b)';\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/geom2d/fitPolynomialTransform2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7507180404851174}} {"text": "function [ nfactor, factor, exponent, nleft ] = i4_factor ( n )\n\n%*****************************************************************************80\n%\n%% I4_FACTOR factors an integer into prime factors.\n%\n% Formula:\n%\n% N = NLEFT * Product ( 1 <= I <= NFACTOR ) FACTOR(I)**EXPONENT(I).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the integer to be factored. N may be positive,\n% negative, or 0.\n%\n% Output, integer NFACTOR, the number of prime factors of N discovered\n% by the routine.\n%\n% Output, integer FACTOR(NFACTOR), the prime factors of N.\n%\n% Output, integer EXPONENT(NFACTOR). EXPONENT(I) is the power of\n% the FACTOR(I) in the representation of N.\n%\n% Output, integer NLEFT, the factor of N that the routine could not\n% divide out. If NLEFT is 1, then N has been completely factored.\n% Otherwise, NLEFT represents factors of N involving large primes.\n%\n nfactor = 0;\n\n factor = [];\n exponent = [];\n\n nleft = n;\n\n if ( n == 0 )\n return\n end\n\n if ( abs ( n ) == 1 )\n nfactor = 1;\n factor(1) = 1;\n exponent(1) = 1;\n return;\n end\n%\n% Find out how many primes we stored.\n%\n maxprime = prime ( -1 );\n%\n% Try dividing the remainder by each prime.\n%\n for i = 1 : maxprime\n\n p = prime ( i );\n\n if ( mod ( abs ( nleft ), p ) == 0 )\n\n nfactor = nfactor + 1;\n factor(nfactor) = p;\n exponent(nfactor) = 0;\n\n while ( 1 )\n\n exponent(nfactor) = exponent(nfactor) + 1;\n nleft = floor ( nleft / p );\n\n if ( mod ( abs ( nleft ), p ) ~= 0 ) \n break;\n end\n\n end\n\n if ( abs ( nleft ) == 1 )\n break;\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/i4_factor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7507146402661544}} {"text": "% function to implement the Iterated Extended Kalman Filter (IEKF)\n% Inputs:\n% OBSn - the observations (with noise)\n% xest - initial state space estimates\n% Ouputs:\n% Xp - predicted states\nfunction Xp = f_IEKF(OBSn,xest)\n\nload avar % r1,r2, L, and T\n\ntol = .1; % tolerance for iterations\ndiff = 1;\ncount = 0;\n\nF = [1 T 0 0 0 0 0;\n 0 1 0 0 0 0 0;\n 0 0 1 T 0 0 0;\n 0 0 0 1 0 0 0;\n 0 0 0 0 1 0 T;\n 0 0 0 0 0 1 T;\n 0 0 0 0 0 0 1]; % state transition matrix\n\nn = size(OBSn,2); % number of observations\n\nXp = zeros(7,n); % make room\n\nPkp1 = 1e10*eye(7); %xest*xest'; %.1*ones(7,7);\n\n%Pkp1 = xest*xest';\n%Pkp1 = F*Pkp1*F';\n\n%Pkp1 = (10*randn(7,1))*(10*randn(7,1)).';\n%Pkp1 = F*Pkp1*F';\n\n% for each observation\nfor i = 1:n;\n \n % if this is the first iteration the prior predicted estimate is xest\n % if this is not the first run the prior estimate is in Xp\n if i == 1\n xkm1 = xest;\n else\n xkm1 = Xp(:,i-1);\n end\n \n Pkm1 = Pkp1; % conditional covariance from last iteration\n \n % iterations are started with the predicted estimate from the last run\n xkn = xkm1;\n while ~(diff < tol || count > 9)\n \n count = count + 1; \n \n H = [gradest(@(x)f_h1(x),xkn); gradest(@(x)f_h2(x),xkn)];\n \n R = (.01*randn(2,1))*(.01*randn(2,1)).';\n \n Rdiag = diag(R); R = diag(Rdiag);\n \n K = Pkm1*H'*(H*Pkm1*H'+R)^-1;\n \n xkn_temp = xkm1 + K*(OBSn(:,i)-f_h(xkn)-H*(xkm1-xkn));\n \n diff = norm(abs(xkn_temp-xkn));\n \n fprintf('diff = %g \\n',diff)\n \n xkn = xkn_temp;\n \n end\n \n H = [gradest(@(x)f_h1(x),xkn); gradest(@(x)f_h2(x),xkn)];\n \n Pkk = (eye(7)-K*H)*Pkm1;\n \n Pkp1 = F*Pkk*F';\n \n Xp(:,i) = F*xkn;\n \n clc;\n \n fprintf('i = %g; Count is %g \\n',i,count)\n \n count = 0;\n \n diff = 1;\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/42156-object-tracking-with-an-iterative-extended-kalman-filter-iekf/Code/f_IEKF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7506576637797184}} {"text": "function inv = cauchy_inv(x,m,s)\n%---------------------------------------------------\n% PURPOSE: \n% Estimates the Inverse of the Cumulative Distribution Function of the \n% Cauchy-Lorentz Distribution for a series of x values, with m location \n% parameter and s scale parameter \n%---------------------------------------------------\n% USAGE: \n% inv = cauchy_inv(x,m,s)\n% where: \n% x = (n x 1) or (1 x n) vector\n% m = (n x 1) or (1 x n) vector\n% s = (n x 1) or (1 x n) vector\n%---------------------------------------------------\n% RETURNS: \n% cdf = (n x 1) or (1 x n) vector containing the probability for each\n% element of x with corresponding location and scale parameters\n%---------------------------------------------------\n% Author:\n% Alexandros Gabrielsen, a.gabrielsen@city.ac.uk\n% Date: 06/2010\n%---------------------------------------------------\n\nif nargin == 0 \n error('Data, Location Parameter, Scale Parameter') \nend\n\ninv = m + s.*tan(pi*(x-1/2));\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/29051-distributions/cauchy_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.750562877801183}} {"text": "function N = R1(rad)\n% Suppose right handed coordinate frames A and B have the same x axis, \n% and rotate the A frame along the x axis by rad obtains the B frame, then\n% a point in B, p_B, can be transformed from its coordinates in A frame by\n% p_B = R1(rad) * p_A.\nN = [1 0 0;0 cos(rad) sin(rad);0 -sin(rad) cos(rad)];", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/kinematics/R1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7505628672530074}} {"text": "function posteriori = slposterioritrue(condprops, nums, priori, op)\n%SLPOSTERIORITRUE Computes the posteriori that samples belong to true class\n%\n% $ Syntax $\n% - posteriori = slposterioritrue(condprops, nums, priori)\n% - posteriori = slposterioritrue(condprops, nums, priori, 'log')\n%\n% $ Arguments $\n% - condprods: the conditional probabilities of classes: C x n\n% - nums: the number of samples belong to the classes: 1 x C\n% - priori: the prior probabilities of classes: 1 x C\n% - posteriori: the resulting posterior probabilities: 1 x n\n%\n% $ Description $\n% - posteriori = slposteriori(condprops, nums, priori) Computes the \n% posterior probability that the samples belong to the true class \n% according to the given conditional probabilities of all samples \n% to all classes and the priori of the classes. \n% In the input argument, each column in condprops represent the \n% conditional probabilities of that sample belong to all the \n% C classes. The samples from the same underlying classes should be\n% put together and the ownership is given by nums.\n% The priori can be given by an 1 x C row vector or [], which \n% means that all classes have equal prior.\n%\n% - posteriori = slposterioritrue(condprops, nums, priori, 'log') means\n% that the input condprops are given by its logarithm.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 16th, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n raise_lackinput('slposterioritrue', 2);\nend\n\nif ~isnumeric(condprops) || ndims(condprops) ~= 2\n error('sltoolbox:invalidarg', ...\n 'The condprops should be a 2D numeric matrix');\nend\n[C, n] = size(condprops);\n\nif ~isequal(size(nums), [1, C])\n error('sltoolbox:sizmismatch', ...\n 'The nums should be an 1 x C row vector');\nend\nif nargin < 3 || isempty(priori)\n priori = [];\nelse\n if ~isequal(size(priori), [1, C])\n error('sltoolbox:sizmismatch', ...\n 'The priori should be a an 1 x C row vector');\n end\nend\n\nif nargin >= 4 && strcmpi(op, 'log')\n is_log = true;\nelse\n is_log = false;\nend\n\n%% compute\n\nif is_log\n if isempty(priori)\n P = sladdvec(condprops, -max(condprops, [], 1), 2);\n else\n P = sladdvec(condprops, log(priori)', 1);\n P = sladdvec(P, -max(condprops, [], 1), 2);\n end\n P = exp(P);\nelse\n if isempty(priori)\n P = condprops;\n else\n P = slmulvec(condprops, priori', 1);\n end\nend\n\ntP = sum(P, 1);\n[sp, ep] = slnums2bounds(nums);\nposteriori = zeros(1, n);\n\nfor k = 1 : C\n sk = sp(k);\n ek = ep(k);\n posteriori(sk:ek) = P(k, sk:ek);\nend\nposteriori = posteriori ./ tP;\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/stat/slposterioritrue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7505240214462303}} {"text": "function [center,rad,v1n,v2nb] = circlefit3d(p1,p2,p3)\n% circlefit3d: Compute center and radii of circles in 3d which are defined by three points on the circumference\n% usage: [center,rad,v1,v2] = circlefit3d(p1,p2,p3)\n%\n% arguments: (input)\n% p1, p2, p3 - vectors of points (rowwise, size(p1) = [n 3])\n% describing the three corresponding points on the same circle.\n% p1, p2 and p3 must have the same length n.\n%\n% arguments: (output)\n% center - (nx3) matrix of center points for each triple of points in p1, p2, p3\n%\n% rad - (nx1) vector of circle radii.\n% if there have been errors, radii is a negative scalar ( = error code)\n%\n% v1, v2 - (nx3) perpendicular vectors inside circle plane\n%\n% Example usage:\n%\n% (1)\n% p1 = rand(10,3);\n% p2 = rand(10,3);\n% p3 = rand(10,3);\n% [center, rad] = circlefit3d(p1,p2,p3);\n% % verification, result should be all (nearly) zero\n% result(:,1)=sqrt(sum((p1-center).^2,2))-rad;\n% result(:,2)=sqrt(sum((p2-center).^2,2))-rad;\n% result(:,3)=sqrt(sum((p3-center).^2,2))-rad;\n% if sum(sum(abs(result))) < 1e-12,\n% disp('All circles have been found correctly.');\n% else,\n% disp('There had been errors.');\n% end\n%\n%\n% (2)\n% p1=rand(4,3);p2=rand(4,3);p3=rand(4,3);\n% [center,rad,v1,v2] = circlefit3d(p1,p2,p3);\n% plot3(p1(:,1),p1(:,2),p1(:,3),'bo');hold on;plot3(p2(:,1),p2(:,2),p2(:,3),'bo');plot3(p3(:,1),p3(:,2),p3(:,3),'bo');\n% for i=1:361,\n% a = i/180*pi;\n% x = center(:,1)+sin(a)*rad.*v1(:,1)+cos(a)*rad.*v2(:,1);\n% y = center(:,2)+sin(a)*rad.*v1(:,2)+cos(a)*rad.*v2(:,2);\n% z = center(:,3)+sin(a)*rad.*v1(:,3)+cos(a)*rad.*v2(:,3);\n% plot3(x,y,z,'r.');\n% end\n% axis equal;grid on;rotate3d on;\n%\n% \n% Author: Johannes Korsawe\n% E-mail: johannes.korsawe@volkswagen.de\n% Release: 1.0\n% Release date: 26/01/2012\n\n% Default values\ncenter = [];rad = 0;v1n=[];v2nb=[];\n\n% check inputs\n% check number of inputs\nif nargin~=3,\n fprintf('??? Error using ==> cirlefit3d\\nThree input matrices are needed.\\n');rad = -1;return;\nend\n% check size of inputs\nif size(p1,2)~=3 || size(p2,2)~=3 || size(p3,2)~=3,\n fprintf('??? Error using ==> cirlefit3d\\nAll input matrices must have three columns.\\n');rad = -2;return;\nend\nn = size(p1,1);\nif size(p2,1)~=n || size(p3,1)~=n,\n fprintf('??? Error using ==> cirlefit3d\\nAll input matrices must have the same number or rows.\\n');rad = -3;return;\nend\n% more checks are to follow inside calculation\n\n% Start calculation\n% v1, v2 describe the vectors from p1 to p2 and p3, resp.\nv1 = p2 - p1;v2 = p3 - p1;\n% l1, l2 describe the lengths of those vectors\nl1 = sqrt((v1(:,1).*v1(:,1)+v1(:,2).*v1(:,2)+v1(:,3).*v1(:,3)));\nl2 = sqrt((v2(:,1).*v2(:,1)+v2(:,2).*v2(:,2)+v2(:,3).*v2(:,3)));\nif find(l1==0) | find(l2==0), %#ok\n fprintf('??? Error using ==> cirlefit3d\\nCorresponding input points must not be identical.\\n');rad = -4;return;\nend\n% v1n, v2n describe the normalized vectors v1 and v2\nv1n = v1;for i=1:3, v1n(:,i) = v1n(:,i)./l1;end\nv2n = v2;for i=1:3, v2n(:,i) = v2n(:,i)./l2;end\n% nv describes the normal vector on the plane of the circle\nnv = [v1n(:,2).*v2n(:,3) - v1n(:,3).*v2n(:,2) , v1n(:,3).*v2n(:,1) - v1n(:,1).*v2n(:,3) , v1n(:,1).*v2n(:,2) - v1n(:,2).*v2n(:,1)];\nif find(sum(abs(nv),2)<1e-5),\n fprintf('??? Warning using ==> cirlefit3d\\nSome corresponding input points are nearly collinear.\\n');\nend\n% v2nb: orthogonalization of v2n against v1n\ndotp = v2n(:,1).*v1n(:,1) + v2n(:,2).*v1n(:,2) + v2n(:,3).*v1n(:,3);\nv2nb = v2n;for i=1:3,v2nb(:,i) = v2nb(:,i) - dotp.*v1n(:,i);end\n% normalize v2nb\nl2nb = sqrt((v2nb(:,1).*v2nb(:,1)+v2nb(:,2).*v2nb(:,2)+v2nb(:,3).*v2nb(:,3)));\nfor i=1:3, v2nb(:,i) = v2nb(:,i)./l2nb;end\n\n% remark: the circle plane will now be discretized as follows\n%\n% origin: p1 normal vector on plane: nv\n% first coordinate vector: v1n second coordinate vector: v2nb\n\n% calculate 2d coordinates of points in each plane\n% p1_2d = zeros(n,2); % set per construction\n% p2_2d = zeros(n,2);p2_2d(:,1) = l1; % set per construction\np3_2d = zeros(n,2); % has to be calculated\nfor i = 1:3,\n p3_2d(:,1) = p3_2d(:,1) + v2(:,i).*v1n(:,i);\n p3_2d(:,2) = p3_2d(:,2) + v2(:,i).*v2nb(:,i);\nend\n\n% calculate the fitting circle \n% due to the special construction of the 2d system this boils down to solving\n% q1 = [0,0], q2 = [a,0], q3 = [b,c] (points on 2d circle)\n% crossing perpendicular bisectors, s and t running indices:\n% solve [a/2,s] = [b/2 + c*t, c/2 - b*t]\n% solution t = (a-b)/(2*c)\n\na = l1;b = p3_2d(:,1);c = p3_2d(:,2);\nt = 0.5*(a-b)./c;\nscale1 = b/2 + c.*t;scale2 = c/2 - b.*t;\n\n% centers\ncenter = zeros(n,3);\nfor i=1:3,\n center(:,i) = p1(:,i) + scale1.*v1n(:,i) + scale2.*v2nb(:,i);\nend\n\n% radii\nrad = sqrt((center(:,1)-p1(:,1)).^2+(center(:,2)-p1(:,2)).^2+(center(:,3)-p1(:,3)).^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/34792-circlefit3d-fit-circle-to-three-points-in-3d-space/circlefit3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7504817195335228}} {"text": "function [M, F, b, x, e_conn] = assemb_co ( param )\n\n% The FEM equation for the steady state temperature distribution is\n%\n% M_2 z^{ss} + F + b = 0\n\n%\n%% Initialization\n%---------------------------------------------------------------------\n\n n_nodesx = param.nodesx; % number of nodes in the x direction\n n_nodesy = param.nodesy; % number of nodes in the y direction\n\n n_gauss = 7; % number of points used in Gauss integration\n%\n%% Geometry Module\n%-----------------------------------------------------------------------\n%\n% Generate a mesh of the L \\times W rectangle with quadratic elements\n%\n n_nodes = n_nodesx*n_nodesy;\n n_elements = 2*(n_nodesx-1)*(n_nodesy-1)/4;\n\n x_nodes = linspace(0.0, param.L, n_nodesx);\n y_nodes = linspace(0.0, param.W, n_nodesy);\n%\n% Generate node coordinates.\n%\n x = zeros(n_nodes, 2);\n for ii=1:n_nodesx\n x_i = x_nodes(ii); k = ii - n_nodesx;\n for jj=1:n_nodesy\n k = k + n_nodesx;\n x(k,:) = [ x_i y_nodes(jj)];\n end\n end\n%\n% Generate element connectivity\n%\n e_conn = zeros(n_elements, 6);\n ie = 0;\n%\n% Template for odd numbered triangles\n%\n elmt_odd = [ 0 ; 2+2*n_nodesx; 2*n_nodesx; \n 1+n_nodesx ; 1+2*n_nodesx; n_nodesx];\n%\n% Template for even numbered triangles\n%\n elmt_evn = [ 0 ; 2 ; 2+2*n_nodesx; \n 1; 2+n_nodesx ; 1+n_nodesx];\n\n for jj=1:2:n_nodesy-1\n for ii=1:2:n_nodesx-1\n k = ii + (jj-1)*n_nodesx;\n ie = ie + 1;\n e_conn(ie,:) = k + elmt_odd;\n ie = ie + 1;\n e_conn(ie,:) = k + elmt_evn;\n end\n end\n%\n% Set up arrays for elements with faces on left/right boundary.\n%\n Omega_left = 1:(n_nodesx-1):n_elements;\n Omega_right = (n_nodesx-1):(n_nodesx-1):n_elements;\n%\n% With Neumann/Robins bc all nodes are unknown.\n%\n n_equations = n_nodes;\n%\n% Begin the SPMD block:\n%\n spmd\n%\n% Set up codistributed structure\n%\n% Column pointers and such for codistributed arrays.\n%\n Vc = codistributed.colon(1, n_equations);\n lP = getLocalPart(Vc);\n lP_1 = lP(1); lP_end = lP(end); % first and last columns of M on this lab\n \n fid = fopen(['out' int2str(labindex)], 'w');\n fprintf(fid, 'Lab %d : column range %d %d \\n', labindex, lP_1, lP_end);\n\n co_dist_Vc = getCodistributor(Vc); \n dPM = co_dist_Vc.Partition;\n col_shft = [0 cumsum(dPM(1:end-1))];\n%\n% sparse arrays on each lab\n%\n M_lab = sparse(n_equations, dPM(labindex));\n b_lab = sparse(dPM(labindex), 1); F_lab = b_lab;\n\n [n_elements, nel_dof] = size(e_conn);\n [r, s, w] = twod_gauss(n_gauss);\n%\n% Build the finite element matrices - Begin loop over elements\n%\n n_el_lab = 0;\n fprintf(fid, 'Lab %d : begin n_el loop \\n', labindex);\n\n for n_el=1:n_elements\n%\n% Which nodes are in this element?\n%\n nodes_local = e_conn(n_el,:);\n%\n% subset of nodes/columns on this lab\n%\n lab_nodes_local = extract( nodes_local, lP_1, lP_end);\n\n% fprintf(fid, '\\n \\n n_el = %d \\n', n_el);\n% fprintf(fid, 'lab_nodes_local has %d rows \\n', size(lab_nodes_local, 1));\n\n if ~isempty(lab_nodes_local) % continue the calculation for this elmnt\n n_el_lab = n_el_lab + 1;\n% fprintf(fid, 'Lab %d : n_el loop location 1 \\n', labindex);\n%\n% coordinates, shape functions & gradients evaluated at the Gauss pts.\n%\n x_local = x(nodes_local,:);\n [x_g, w_g, phi, p_x, p_y] = twod_shape(x_local, r, s, w);\n\n%-------------------------------------------------------------------\n%% Element contributions to the weak form of the equations\n% First we evaluate the surface integral (2D) terms\n%-------------------------------------------------------------------\n M_loc = twod_bilinear(param.k_x, p_x, p_x, w_g) + ...\n twod_bilinear(param.k_y, p_y, p_y, w_g);\n src_g = source(x_g, param); % distributed source term\n F_loc = twod_f_int( src_g , phi, w_g );\n%\n% pre-allocate boundary arrays\n%\n b_loc = zeros(nel_dof,1);\n% fprintf(fid, 'Lab %d : n_el loop location 2 \\n', labindex);\n\n%---------------------------------------------------------------------\n%% Add boundary terms\n%---------------------------------------------------------------------\n%\n% Add boundary-integral terms for left and right bounary elements\n% Left boundary n_el = [1:2*(n_nodesx-1):n_elements\n% Right boundary n_el = [2*(n_nodesx-1):2*(n_nodesx-1):n_elements\n%\n if any(Omega_left == n_el);\n%\n% Here we impose Robin boundary term. The node points on the boundary\n% are nodes_local([3 6 1]) and are at x_local([3 6 1],:)\n%\n [phi_g1, ip, x_g1, w_g1] = boundary(3, x_local, 5); % n_gauss=5\n alpha_g1 = steps(x_g1(:,2), param.yh, param.ep, param.alpha );\n phi_a = diag(alpha_g1)*phi_g1; % mult. each row by alpha(y_g)\n beta_g1 = steps(x_g1(:,2), param.yh, param.ep, param.beta );\n%\n% 1D integrals are from y = w to y = 0\n%\n for ii=1:3\n for jj=1:3\n M_loc(ip(ii),ip(jj)) = M_loc(ip(ii),ip(jj)) + ...\n oned_f_int( phi_g1(:, jj), phi_a(:,ii), w_g1 );\n end\n b_loc(ip(ii),1) = b_loc(ip(ii),1) + ...\n oned_f_int( beta_g1, phi_a(:,ii), w_g1 );\n end\n\n elseif any(Omega_right == n_el);\n%\n% Here we impose boundary term for a specified flux\n% The node points on the boundary are nodes_local([2 3 5]) and\n% are at x_local([2 3 5],:)\n% We need \\int f(y) \\phi(L, y) dy along the right boundary.\n%\n [phi_g1, ip, ~ , w_g1] = boundary(2, x_local, 5); % n_gauss=5;\n for ii=1:3\n b_loc(ip(ii),1) = b_loc(ip(ii),1) + ...\n oned_f_int( param.flux, phi_g1(:,ii), w_g1 );\n end\n end\n\n%-----------------------------------------------------------------\n%% Assemble contributions into the global system matrices\n%-----------------------------------------------------------------\n% For M_lab we want all the rows (test functions) but only the\n% columns associated with nodes on this lab\n%\n for n_t = 1:nel_dof % local DOF - test fcn\n t_glb = nodes_local(n_t); % global DOF - test fcn\n for n_u = 1:size(lab_nodes_local, 1)\n n_locj = lab_nodes_local(n_u, 1); % local DOF in current n_el\n n_glbj = lab_nodes_local(n_u, 2) ...\n - col_shft(labindex); % global DOF\n M_lab(t_glb,n_glbj) = M_lab(t_glb,n_glbj) ...\n + M_loc(n_t,n_locj);\n end\n%\n% Some triangles have nodes on more than one lab;\n% we want only the rows associated with nodes on this lab \n%\n if t_glb >= lP_1 && t_glb <= lP_end \n t_loc = t_glb - col_shft(labindex); \n b_lab(t_loc,1) = b_lab(t_loc,1) + b_loc(n_t,1);\n F_lab(t_loc,1) = F_lab(t_loc,1) + F_loc(n_t,1);\n end\n\n end % for n_t\n\n end % if not empty\n\n end % n_el\n\n fprintf(fid,'Fraction of elements evaluated on this lab is %8.6f \\n',...\n n_el_lab/n_elements);\n%\n% Assemble the 'lab' parts in a codistributed format.\n% syntax for version R2009b\n%\n codist_matrix = codistributor1d( 2, dPM, [n_equations, n_equations]);\n M = codistributed.build(M_lab, codist_matrix );\n codist_vector = codistributor1d( 1, dPM, [n_equations, 1]);\n b = codistributed.build(b_lab , codist_vector );\n F = codistributed.build(F_lab , codist_vector );\n \n fclose(fid);\n\n end\n%\n% This terminates the SPMD block.\n%\n return\nend\n", "meta": {"author": "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/assemb_co.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7504817143977573}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% [JX, Jq, Jphi]=compute_jacobians_5R(robot, q)\n%\n% Compute Jacobians for the for the 5R planar parallel robot\n%\n% JX is the 4x2 Jacobian with respect to the cartesian coordinates (x, y)\n% Jq is the 4x2 Jacobian with respect to the active joints (q1, q2)\n% Jphi is the 4x2 Jacobian with respect to the passive joints (phi1, phi2)\n%\n% Author: Arturo Gil Aparicio arturo.gil@umh.es\n% Date: 13/09/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 .\n\nfunction [JX, Jq, Jphi]=compute_jacobians_5R(robot, q)\n\n% The geometric parameters of this robot can be retrieved from \n% the two DOF planar arms that form it\na1=eval(robot.robot1.DH.a);\na2=eval(robot.robot2.DH.a);\n \n%Link lengths\nl1=abs(a1(1));\nl2=abs(a1(2));\nl3=abs(a2(1)); \nl4=abs(a2(2));\n%distance along X that separate both arms\nL=robot.L;\n\n%retrieve the active and passive joints from the vector q\nq1=q(1);\nphi1=q(2);\nq2=q(3);\nphi2=q(4);\n\n%The loop closure equations for this robot can be written as:\n%\n% \\begin{bmatrix}\n% \\Gamma_1\\\\\n% \\Gamma_2\\\\\n% \\Gamma_3\\\\\n% \\Gamma_4\n% \\end{bmatrix}=\n% \\begin{bmatrix}\n% x-l_1\\cos(q_1)-l_2\\cos(q_1+\\varphi_1)\\\\\n% y-l_1\\sin(q_1)-l_2\\sin(q_1+\\varphi_1)\\\\\n% x-l_4\\cos(q_2)-l_3\\cos(q_2+\\varphi_2)-L\\\\\n% y-l_4\\sin(q_2)-l_3\\sin(q_2+\\varphi_2)\n% \\end{bmatrix}\n\n%In this matrix, JX11 is the partial derivative of Gamma1 with respect to x\n% JX12 is the partial derivative of Gamma1 with respect to y\n% JX21 is the partial derivative of Gamma2 with respect to x\n%...\nJX=[1 0;\n 0 1;\n 1 0;\n 0 1];\n\n%In this matrix, Jq11 is the partial der. of Gamma1 with respect to q1\n% Jq12 is the partial der. of Gamma1 with respect to q2\n% Jq21 is the partial der. of Gamma2 with respect to q1\n%etc...\nJq = [l1*sin(q1)+l2*sin(q1+phi1) 0;\n -l1*cos(q1)-l2*cos(q1+phi1) 0;\n 0 l4*sin(q2)+l3*sin(q2+phi2);\n 0 -l4*cos(q2)-l3*cos(q2+phi2)];\n\n\n%In this matrix, Jphi11 is the partial der. of Gamma1 with respect to phi1\n% Jphi12 is the partial der. of Gamma1 with respect to phi2\n% Jphi21 is the partial der. of Gamma2 with respect to phi1\n%etc...\nJphi = [l2*sin(q1+phi1) 0;\n -l2*cos(q1+phi1) 0;\n 0 l3*sin(q2+phi2);\n 0 -l3*cos(q2+phi2)];\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/5R/compute_jacobians_5R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7504817121966404}} {"text": "function s1 = sigma_8(k, k1, psm1, h)\n% sigma_8.m calculates the integrant for the expected rms mass overdensity in a sphere of radius 8 Mpc/h.\n% input : k, wavenumber in units h/Mpc and the vectors k1 resp psm1, the mass power spectrum as a \n% function of k1\n% output : the integrant to obtain sigma_8, the rms mass overdensity sampled with\n% a sphere of radius 8/h Mpc.\n\n% D Vangheluwe 15 july 2005\n\n% radius of the sphere in units Mpc/h\nr0 = 8/h;\nx = k * r0;\n% calculate the point in the mass power spectrum at k :\npsm = spline(k1, psm1, k);\n\n% calculate the integrant:\ns1 = (3*(sin(x) - x .* cos(x)) ./ (x .^3)) .^2 .* psm .* k .^2; \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/8491-cmbaccur/sigma_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7504817026586407}} {"text": "function index = tileIndex3d(tile)\n% Return the index of a 2-by-2-by-2 3D binary configuration tile.\n%\n% INDEX = tileIndex3d(TILE)\n% Compute the index of a tile, given as a 2x2x2 binary image, by adding\n% powers of two mutliplied by values of the tile. The result is comprised\n% between 0 and 255.\n% Iterate on x, y, then z directions, corresponding to directions 2, 1,\n% and 3.\n%\n% Example\n% tile = zeros([2 2 2]);\n% tile(1,1:2,1) = 1;\n% tileIndex3d(tile)\n% 3\n%\n% See also\n% createTile3d, tileIndex\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2009-05-25, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\ntile = tile>0;\nindex = ...\n tile(1,1,1) + 2*tile(1,2,1) + 4*tile(2,1,1) + 8*tile(2,2,1) + ...\n 16*tile(1,1,2) + 32*tile(1,2,2) + 64*tile(2,1,2) + 128*tile(2,2,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/imFilters/tileIndex3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297887874624, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7504336199439141}} {"text": "function fx = p03_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P03_FUN evaluates the integrand for problem 3.\n%\n% Discussion:\n%\n% D&R gives \"exact\" value as 13.628...\n% Mathematica returns 13.440045415012575106...\n% D&R gives Laguerre(16) as 0.44996932...\n%\n% Integral:\n%\n% exp ( -2 ) Integral ( 2 <= x < +oo ) 1 / ( x^1.01 ) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the function values.\n%\n fx(1:n) = exp ( - 2.0 ) * 1.0 ./ x(1:n).^1.01;\n\n return\nend\n", "meta": {"author": "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/p03_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7504336184408923}} {"text": "%% Analyzing Neural Time Series Data\n% Matlab code for Chapter 25\n% Mike X Cohen\n% \n% This code accompanies the book, titled \"Analyzing Neural Time Series Data\" \n% (MIT Press). Using the code without following the book may lead to confusion, \n% incorrect data analyses, and misinterpretations of results. \n% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code. \n\n%% setup for figure 25.3\n\n% generate a random signal of 3 seconds\nsrate = 1000;\n\nrandsig1 = randn(1,3*srate); % 3 seconds, with this sampling rate\nrandsig2 = randn(1,3*srate);\n\n% now filter at 5 Hz\nf = 5; % frequency of wavelet in Hz\ntime = -1:1/srate:1; % time for wavelet, from -1 to 1 second in steps of 1/sampling-rate\ns = 6/(2*pi*f); % width of Gaussian\nwavelet = exp(2*pi*1i*f.*time) .* exp(-time.^2./(2*s^2)); \n\n% FFT parameters\nn_wavelet = length(wavelet);\nn_data = length(randsig1);\nn_convolution = n_wavelet+n_data-1;\nhalf_of_wavelet_size = (length(wavelet)-1)/2;\n\n% FFT of wavelet and EEG data\nconvolution_result_fft = ifft(fft(wavelet,n_convolution).*fft(randsig1,n_convolution),n_convolution)*sqrt(s)/10;\nfiltsig1 = real(convolution_result_fft(half_of_wavelet_size+1:end-half_of_wavelet_size));\nanglesig1 = angle(convolution_result_fft(half_of_wavelet_size+1:end-half_of_wavelet_size));\n\nconvolution_result_fft = ifft(fft(wavelet,n_convolution).*fft(randsig2,n_convolution),n_convolution)*sqrt(s)/10;\nfiltsig2 = real(convolution_result_fft(half_of_wavelet_size+1:end-half_of_wavelet_size));\nanglesig2 = angle(convolution_result_fft(half_of_wavelet_size+1:end-half_of_wavelet_size));\n\n\nfigure\nfor i=1:2\n subplot(2,1,i)\n eval([ 'plot(randsig' num2str(i) ')' ]) % \"eval\" can be useful for increasing control over commands\n hold on\n eval([ 'plot(filtsig' num2str(i) ',''r'')' ])\nend\n\n%% Figure 25.3\n\n% initialize output correlation matrix\ncorrelations = zeros(5,round(1000/f));\n\nfor i=1:round(1000/f)\n \n % correlation of unfiltered random signal\n temp = corrcoef(randsig1(1:end-i),randsig1(i+1:end));\n correlations(1,i) = temp(1,2);\n \n % correlation of filtered signal\n temp = corrcoef(filtsig1(1:end-i),filtsig1(i+1:end));\n correlations(2,i) = temp(1,2);\n \n % phase clustering\n correlations(3,i) = abs(mean(exp(1i*( angle(anglesig1(1:end-i)-anglesig1(i+1:end))))));\n \n % difference of correlations of filtered signal\n temp = corrcoef(filtsig2(1:end-i),filtsig2(i+1:end));\n correlations(4,i) = temp(1,2) - correlations(2,i);\n \n % difference of phase clusterings\n correlations(5,i) = abs(mean(exp(1i*( angle(anglesig2(1:end-i)-anglesig2(i+1:end)))))) - correlations(3,i);\nend\n\nfigure\nplot(correlations')\nxlabel('Lag (ms)')\nylabel('Connectivity strength')\nlegend({'unfiltered';'power corr';'ISPC';'corr diffs';'ISPC diffs'})\n\n%% end.\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/chapter25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7504171821459031}} {"text": "function [suspicious_index lof] = LOF(A, k)\n%\n% Local Outlier Factor \n% Authors: Markus M. Breunig, Hans-Peter Kriegel, \n% Raymond T. Ng, J?rg Sander \n% Original paper : \n% LOF: Identifying Density-Based Local Outliers \n% e-mail : { breunig | kriegel | sander } \n% @dbs.informatik.uni-muenchen.de \n% rng@cs.ubc.ca \n% Programmer: Yi-Ren Yeh(yirenyeh@gmail.com) \n% modified by: Zi-Wen Gui(evan176@hotmail.com) \n% \n% \n% Inputs \n% A: the data matrix, each row represents an instance \n% k: the number of nearest neighbors, specified as an integer or \n% as a fraction of the total number of data points \n% \n% Outputs \n% lof: the local outlier factor for each instance \n% suspicious_index: the ranking of instances according to their \n% suspicious score \n% For example, suspicious_index(i)=j means the \n% ith instance is in jth position in the ranking\n%\n\nif k < 1\n [numrows ~] = size(A);\n k = round(k*numrows);\nend\n \ntry\n %Find the nearest neighbors by \"KDTree\" for each elements\n [k_index, k_dist] = knnsearch(A,A,'k',k+1,'nsmethod','kdtree','IncludeTies',true);\n %Ignore first element(itself) at nearest neighbors \n k_index = cellfun(@(x) x(2:end),k_index,'UniformOutput',false);\n numneigh = cellfun('length',k_index);\n %Get k-distance\n k_dist1 = cell2mat(cellfun(@(x) x(end),k_dist,'UniformOutput',false));\n %Get row length of matrix A\n n = length(A(:,1));\n %Initialize lrd_value vector\n lrd_value = zeros(n,1);\n %Calculate lrd for each elements\n for i = 1:n\n lrd_value(i) = lrd(A, i, k_dist1, k_index, numneigh(i));\n end\n %Initialize lof vector\n lof = zeros(n,1);\n %Calculate LOF\n for i = 1:n\n lof(i) = sum(lrd_value(k_index{i})/lrd_value(i))/numneigh(i);\n end\n %Indices from sorting lof are the suspicious score rankings\n [~,suspicious_index]=sort(lof,'descend');\n \ncatch err\n if (strcmp(err.message, 'Invalid parameter name: IncludeTies.'))\n warning('MATLAB:LOF', 'Matlab not newest version? Falling back to old version.')\n [suspicious_index lof] = LOF_old(A, k);\n else\n rethrow(err)\n end\n \nend\n\n%=========================================================================\nfunction lrd_value = lrd(A, index_p, k_dist,k_index, numneighbors)\n%Calculate the reachability distance for nearest neighbors\nTemp = repmat(A(index_p,:), numneighbors, 1) - A(k_index{index_p}, :);\nTemp = sqrt(sum(Temp.^2,2));\nreach_dist = max([Temp k_dist(k_index{index_p})],[],2);\n%Calculate the local reachability density for each elements\nlrd_value = numneighbors/sum(reach_dist);\n\n\n", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/distributionBased/LOF/LOF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7503975265954134}} {"text": "function y = normpdfg(x,scale,shape,center,max)\n% y = normpdfg(x,scale,shape,center,max)\n%\n% Evalute the generalized gaussian pdf at point(s) x\n% the pdf is defined by the given scale (2*variance) and shape and mean\n% (center)\n%\n% Note the variance of the distribution is scale/2\n%\n% As shape --> Inf we get a (step function) uniform distribution over [center-scale, center+scale]\n% As shape --> 0 we get a delta function\n% Beta = 1 is the Laplace \n% Beta = 2 is gaussian\n%\n% (C) Tim Mullen, 2011. SCCN/INC UCSD\n\nA = shape./(2.*scale.*gamma(1/shape));\nC = max./A;\n\ny = C.*A.*exp(-((abs(x-center)/scale).^shape));", "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/normpdfg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7502264004221556}} {"text": "% Minimize transition bandwidth of a linear phase lowpass FIR filter\n% \"Filter design\" lecture notes (EE364) by S. Boyd\n% (figures are generated)\n%\n% Designs a linear phase FIR lowpass filter such that it:\n% - minimizes the transition band width (i.e. minimize w_stop)\n% - has a constraint on the maximum passband ripple\n% - has a constraint on the maximum stopband attenuation\n%\n% This is a quasiconvex problem and is solved using a bisection.\n%\n% minimize w_stop\n% s.t. 1/delta <= H(w) <= delta for w in the passband\n% |H(w)| <= atten_level for w in the stopband\n%\n% where H is the frequency response function and variable is\n% the filter impulse response h (and its order/length).\n% Data is delta (max passband ripple) and atten_level (max stopband\n% attenuation level).\n%\n% Written for CVX by Almir Mutapcic 02/02/06\n\n%********************************************************************\n% user's filter specifications\n%********************************************************************\n% starting point for the stopband (needs to be feasible)\nwstop = 0.24*pi; % stopband start freq (in radians)\nTOL = 1e-3; % precision to which we should run bisection\n\nn = 10; % filter order (2n+1 is the full order)\nwpass = 0.12*pi; % passband cutoff freq (in radians)\ndelta = 1; % max (+/-) passband ripple in dB\natten_level = -30; % stopband attenuation level in dB\n\n%********************************************************************\n% create optimization parameters\n%********************************************************************\nm = 30*n; % freq samples (rule-of-thumb)\nw = linspace(0,pi,m);\n\n%*********************************************************************\n% use bisection algorithm to solve the problem\n%*********************************************************************\n\nwstop_bot = wpass;\nwstop_top = wstop;\n\nwhile( wstop_top - wstop_bot > TOL)\n % try to find a feasible design for given specs\n wstop_cur = (wstop_top + wstop_bot)/2;\n\n % create optimization matrices (matrix of cosines)\n A = [ones(m,1) 2*cos(kron(w',[1:n]))];\n\n % passband 0 <= w <= w_pass\n ind = find((0 <= w) & (w <= wpass)); % passband\n Ap = A(ind,:);\n\n % transition band is not constrained (w_pass <= w <= w_stop)\n\n % stopband (w_stop <= w) (this is the changing constraint)\n ind = find((wstop_cur <= w) & (w <= pi)); % stopband\n As = A(ind,:);\n\n % formulate and solve the feasibility linear-phase lp filter design\n cvx_begin quiet\n variable h_cur(n+1,1);\n % feasibility problem\n % passband bounds\n Ap*h_cur <= 10^(delta/20);\n Ap*h_cur >= 10^(-delta/20);\n % stopband bounds\n abs( As*h_cur ) <= 10^(atten_level/20);\n cvx_end\n\n % bisection\n if strfind(cvx_status,'Solved') % feasible\n fprintf(1,'Problem is feasible for stopband freq = %3.4f rads\\n',wstop_cur);\n wstop_top = wstop_cur;\n % construct the full impulse response\n h = [flipud(h_cur(2:end)); h_cur];\n else % not feasible\n fprintf(1,'Problem is not feasible for stopband freq = %3.4f rads\\n',wstop_cur);\n wstop_bot = wstop_cur;\n end\nend\n\nwstop = wstop_top;\nfprintf(1,['\\nOptimum stopband frequency for given specs is %3.4f*pi rads\\n' ...\n 'and the minimum transition width is %3.4f*pi radians.\\n'],...\n wstop/pi, (wstop-wpass)/pi);\n\n\n%********************************************************************\n% plots\n%********************************************************************\nfigure(1)\n% FIR impulse response\nplot([0:2*n],h','o',[0:2*n],h','b:')\nxlabel('t'), ylabel('h(t)')\n\nfigure(2)\n% frequency response\nH = exp(-j*kron(w',[0:2*n]))*h;\n% magnitude\nsubplot(2,1,1)\nplot(w,20*log10(abs(H)),...\n [wstop pi],[atten_level atten_level],'r--',...\n [0 wpass],[delta delta],'r--',...\n [0 wpass],[-delta -delta],'r--');\naxis([0,pi,-40,10])\nxlabel('w'), ylabel('mag H(w) in dB')\n% phase\nsubplot(2,1,2)\nplot(w,angle(H))\naxis([0,pi,-pi,pi])\nxlabel('w'), ylabel('phase H(w)')\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/filter_design/fir_lin_phase_lowpass_min_trans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.75021671784964}} {"text": "function J=vl_imwhiten(I,alpha,cutoff)\n% VL_IMWHITEN Whiten an image\n% J = VL_IMWHITEN(I,ALPHA) approximatively whitens the power spectrum\n% of the natural image I. The algorithm assumes that the modulus of\n% the spectrum decays as 1/f^ALPHA (f is the frequency).\n%\n% VL_IMWHITEN(I) uses ALPHA=1 (a typical value for natural images).\n%\n% VL_IMWHITEN(I,ALPHA,CUTOFF) also applies a low-pass filter with\n% cutoff frequency equal to CUTOFF x FN, where FN is the Nyquist\n% frequency (half of the sampling frequency).\n%\n% See also: VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif ~exist('alpha','var'), alpha = 1 ; end\nif ~exist('cutoff','var'), cutoff = [] ; end\n\n[M,N]=size(I) ;\n\n% Frequency domain\nfn = 0.5 ; % Nyquist freq (=1/2T, T=1)\nfx_range=linspace(-fn, fn, N) ;\nfy_range=linspace(-fn, fn, M) ;\n[fx fy]=meshgrid(fx_range, fy_range) ;\n\n% Whitening filter\nrho=sqrt(fx.*fx+fy.*fy);\nfilt=rho.^alpha ;\n\n% Low-pass filter\nif ~isempty(cutoff)\n fcut = cutoff * fn ;\n filt = filt .* exp(-(rho/fcut).^4);\n %filt = filt .* exp( - 0.5 * (rho / fcut) .^ 2);\nend\n\n% Apply filter\nJ = real(ifft2(fft2(I).*fftshift(filt))) ;\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/imop/vl_imwhiten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7501950993424582}} {"text": "function [tuples,gain]=kCard2DAssign(C,k,maximize)\n%%KCARD2DASSIGN Solve the two-dimensional k-cardinality assignment problem\n% with a rectangular cost matrix C. The problem being solved can\n% be formulated as minimize (or maximize)\n% \\sum_{i=1}^{numRow}\\sum_{j=1}^{numCol}C_{i,j}*x_{i,j}\n% subject to\n% \\sum_{j=1}^{numCol}x_{i,j}<=1 for all i\n% \\sum_{i=1}^{numRow}x_{i,j}<=1 for all j\n% \\sum_{i=1}^{numRow}\\sum_{j=1}^{numCol}x_{i,j}=k\n% x_{i,j}=0 or 1.\n%\n%INPUTS: C A numRowXnumCol cost matrix that does not contain any NaNs and\n% where the largest finite element minus the smallest element is a\n% finite quantity (does not overflow) when performing minimization\n% and where the smallest finite element minus the largest\n% element is finite when performing maximization. Forbidden\n% assignments can be given costs of +Inf for minimization and -Inf\n% for maximization.\n% k The integer number of assignments to make.\n% k<=min(numRow,numCol).\n% maximize If true, the minimization problem is transformed into a\n% maximization problem. The default if this parameter is omitted\n% or an empty matrix is passed is false.\n%\n%OUTPUTS: tuples A 2XnumRow set of assignment values. This is ordered\n% [rowIndex;columnIndex]. If no feasible solution exists,\n% then an empty matrix will be returned. \n% gain This is the value of the cost. This is the sum of the\n% values in C corresponding to the tuples.\n%\n%As noted in [1], the k-cardinality 2D assignment problem can be\n%transformed into a standard rectangular 2D assignment problem. This\n%function implements that transformation and calls assign2D. \n%\n%EXAMPLE:\n% C=[7, 51, 52, 87;\n% 50, 12, 0, 64;\n% 27, 77, 0, 18;\n% 62, 0, 3, 8];\n% k=4;\n% [tuples4,gain4]=kCard2DAssign(C,4)\n% [tuples3,gain3]=kCard2DAssign(C,3)\n% [tuples2,gain2]=kCard2DAssign(C,2)\n% [tuples1,gain1]=kCard2DAssign(C,1)\n%One will see optimal gains of 25, 7, 0, and 0.\n%\n%REFERENCES:\n%[1] A. Volgenant, \"Solving the k-cardinality assignment problem by\n% transformation,\" European Journal of Operational Research, vol. 157,\n% no. 2, pp. 322-331, 1 Sep. 2004.\n%\n%June 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(nargin<3||isempty(maximize))\n maximize=false;\n end\n \n numRow=size(C,1);\n numCol=size(C,2);\n \n if(k==0)\n tuples=[];\n gain=0;\n return;\n end\n \n if(k<0||k~=fix(k))\n error('k is invalid.')\n end\n \n if(k>numRow||k>numCol)\n %The problem is not feasible.\n tuples=[];\n gain=-1;\n return\n end\n \n COrig=C;\n \n if(maximize==true)\n CDelta=max(C(:));\n \n %If C is all negative, do not shift.\n if(CDelta<0)\n CDelta=0;\n end\n \n C=-C+CDelta;\n else\n CDelta=min(C(:));\n \n %If C is all positive, do not shift.\n if(CDelta>0)\n CDelta=0;\n end\n \n C=C-CDelta;\n end\n \n %The minimum value in C is now 0 or something positive. We shall shift\n %the values to guarantee that 0 is less than every value in C.\n %Find the maximum finite value in C.\n CMax=max(max(C(isfinite(C))));\n\n %We shall now offset everything by a small fraction of the maximum\n %value. This is so that we guarantee that values will be assigned\n %to the zero padded rows that shall be added to C.\n COffset=CMax*1e-10;\n C=C+COffset;\n\n %Perform 2D assignment on the augmented matrix. An algorithm that does\n %not explicitely construct that assignment matrix is also possible.\n [~,row4Col]=assign2D([C;zeros(numCol-k,numCol)],false);\n \n if(isempty(row4Col))\n %If the problem is infeasible.\n tuples=[];\n gain=-1;\n return\n end\n \n tuples=zeros(2,k);\n curTuple=1;\n gain=0;\n for curCol=1:numCol\n \n curRow=row4Col(curCol);\n \n if(curRow<=numRow)\n gain=gain+COrig(curRow,curCol);\n tuples(:,curTuple)=[curRow;curCol];\n curTuple=curTuple+1;\n\n if(curTuple>k)\n break;\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/Assignment_Algorithms/2D_Assignment/kCard2DAssign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7501836830216672}} {"text": "function b = int(a,x,L,U)\n% function B = int(A,X,L,U)\n%\n% DESCRIPTION\n% Element-by-element integration of a polynomial with respect\n% to a single variable.\n%\n% INPUTS\n% A: polynomial\n% X: Scalar polynomial variable [Optional with default X = A.varname{1}]\n% L: Lower limit of definite integral\n% U: Upper limit of definite integral\n%\n% OUTPUTS\n% B: polynomial\n%\n% SYNTAX\n% B = int(A,X)\n% Indefinite integral of the polynomial, A, with respect to X.\n% X should be a polynomial variable or string. Integration is done\n% element-by-element if A is a matrix.\n% B = int(A,X,L,U)\n% Definite integral of A with respect to X from lower limit L to\n% upper limit U.\n% B = int(A,X,[L U]);\n% Equivalent to B = diff(A,X,L,U)\n%\n% EXAMPLE\n% pvar x y z;\n% a = 2*x^3 - 2*x*z^2 + 5*y*z;\n% b = int(a,x)\n% diff(b,x)-a\n% c = int(a,[0 1])\n%\n% See also: diff, jacobian\n\n% 12/6/2010 PJS Initial Coding\n\n% Process Inputs/ Error Checking\nif nargin==1\n x = a.varname{1};\n L = []; U = [];\nelseif nargin==2\n if isa(x,'double')\n % B = int(A,[L,U])\n L = x(1);\n U = x(2);\n x = a.varname{1};\n else\n % B = int(A,X)\n L = []; U = [];\n end\nelseif nargin==3\n if isa(x,'double')\n % B = int(A,L,U)\n U = L;\n L = x;\n x = a.varname{1};\n else\n % B = int(A,X,[L U])\n U = L(2);\n L = L(1);\n end\nelseif nargin~=4\n error(['Invalid syntax for the \"int\" command. ' ...\n 'Type \"help int\" for more information.'])\nend\n\nif ispvar(x) && length(x)==1\n x = x.varname{1};\nelseif ~ischar(x)\n error('X must be a single polynomial variable or a string');\nend\n\n% Get polynomial info about A\nacoef = a.coefficient;\nadeg = a.degmat;\navar = a.varname;\nsza = a.matdim;\nNaterms = size(acoef,1);\n\n% Find variable we are differentiating with respect to.\nvarnumb = find( strcmp(avar,x) );\n\n% Perform indefinite integral\nszb = sza;\nif isempty(varnumb)\n % int a(y) dx = a(y)*x\n bcoef = acoef;\n bdeg = [adeg ones(Naterms,1)];\n bvar = [avar; x];\nelse\n % int a(y)*x^n dx = a(y)*x^(n+1) / (n+1)\n bdeg = adeg;\n nplus1 = bdeg(:,varnumb)+1;\n bdeg(:,varnumb) = nplus1;\n \n bcoef = acoef;\n bcoef = lrscale( bcoef, 1./nplus1 , []);\n \n bvar = avar;\nend\n \nchkval = 0; % skip validity check\nb = polynomial(bcoef,bdeg,bvar,szb,chkval);\n\n% Evaluate definite integral\nif ~isempty(L)\n bU = subs(b,{x},U);\n bL = subs(b,{x},L);\n b = bU-bL;\nend\n\n% Combine any common terms\nb = combine(b);\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/int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7501802287139079}} {"text": "function ray = createRay(varargin)\n%CREATERAY Create a ray (half-line), from various inputs\n%\n% RAY = createRay(POINT, ANGLE)\n% POINT is a N*2 array giving starting point of the ray, and ANGLE is the\n% orientation of the ray.\n%\n% RAY = createRay(X0, Y0, ANGLE)\n% Specify ray origin with 2 input arguments.\n%\n% RAY = createRay(P1, P2)\n% Create a ray starting from point P1 and going in the direction of point\n% P2.\n%\n% Ray is represented in a parametric form: [x0 y0 dx dy]\n% x = x0 + t*dx\n% y = y0 + t*dy;\n% for all t>0\n%\n% Example\n% origin = [3 4];\n% theta = pi/6;\n% ray = createRay(origin, theta);\n% figure(1); clf; hold on;\n% axis([0 10 0 10]);\n% drawRay(ray);\n%\n% See also:\n% rays2d, createLine, points2d\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-10-18\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\nif length(varargin)==2\n p0 = varargin{1};\n arg = varargin{2};\n if size(arg, 2)==1\n % second input is the ray angle\n ray = [p0 cos(arg) sin(arg)];\n else\n % second input is another point\n ray = [p0 arg-p0];\n end\n \nelseif length(varargin)==3 \n x = varargin{1};\n y = varargin{2};\n theta = varargin{3};\n ray = [x y cos(theta) sin(theta)]; \n\nelse\n error('Wrong number of arguments in ''createRay'' ');\nend\n", "meta": {"author": "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/createRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7501802199173302}} {"text": "function a = r8vec_normalize_l1 ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_NORMALIZE_L1 normalizes an R8VEC to have unit sum.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A(N), the vector to be normalized.\n%\n% Output, real A(N), the entries of A should have unit sum. However, \n% if the input vector has zero sum, the routine halts.\n%\n a_sum = sum ( a(1:n) );\n\n if ( a_sum == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_NORMALIZE_L1 - Fatal error!\\n' );\n fprintf ( 1, ' The vector entries sum to 0.\\n' );\n error ( 'R8VEC_NORMALIZE_L1 - Fatal error!' );\n end\n\n a(1:n) = a(1:n) / a_sum;\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_normalize_l1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7501802107967214}} {"text": "function h = r8mat_house_post ( n, a, row, col )\n\n%*****************************************************************************80\n%\n%% R8MAT_HOUSE_POST computes a Householder post-multiplier matrix.\n%\n% Discussion:\n%\n% H(ROW,COL) has the property that the ROW-th column of\n% A*H(ROW,COL) is zero from entry COL+1 to the end.\n%\n% In the most common case, where a QR factorization is being computed,\n% ROW = COL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrices.\n%\n% Input, real A(N,N), the matrix whose Householder matrix\n% is to be computed.\n%\n% Input, integer ROW, COL, specify the location of the\n% entry of the matrix A which is to be preserved. The entries in\n% the same row, but higher column, will be zeroed out if\n% A is postmultiplied by H.\n%\n% Output, real H(N,N), the Householder matrix.\n%\n\n%\n% Set up the vector V.\n%\n a_row(1,1:col-1) = 0.0;\n a_row(1,col:n) = a(row,col:n);\n\n a_row = a_row';\n\n v = r8vec_house_column ( n, a_row, col );\n%\n% Form the matrix H(V).\n%\n h = r8mat_house_form ( n, v );\n\n return\nend\n", "meta": {"author": "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_post.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7501422423642576}} {"text": "function [label, model, llh] = mixLinReg(X, y, k, lambda)\n% Mixture of linear regression\n% input:\n% X: d x n data matrix\n% y: 1 x n responding vector\n% k: number of mixture component\n% lambda: regularization parameter\n% output:\n% label: 1 x n cluster label\n% model: trained model structure\n% llh: loglikelihood\n% Written by Mo Chen (sth4nth@gmail.com).\nif nargin < 4\n lambda = 1;\nend\nn = size(X,2);\nX = [X;ones(1,n)]; % adding the bias term\nd = size(X,1);\nlabel = ceil(k*rand(1,n)); % random initialization\nR = full(sparse(label,1:n,1,k,n,n));\ntol = 1e-6;\nmaxiter = 500;\nllh = -inf(1,maxiter);\nLambda = lambda*eye(d);\nW = zeros(d,k);\nXy = bsxfun(@times,X,y);\nbeta = 1;\nfor iter = 2:maxiter\n % maximization\n nk = sum(R,2);\n alpha = nk/n;\n for j = 1:k\n Xw = bsxfun(@times,X,sqrt(R(j,:)));\n U = chol(Xw*Xw'+Lambda);\n W(:,j) = U\\(U'\\(Xy*R(j,:)')); % 3.15 & 3.28\n end\n D = bsxfun(@minus,W'*X,y).^2;\n % expectation\n logRho = (-0.5)*beta*D;\n logRho = bsxfun(@plus,logRho,log(alpha));\n T = logsumexp(logRho,1);\n logR = bsxfun(@minus,logRho,T);\n R = exp(logR);\n llh(iter) = sum(T)/n;\n if abs(llh(iter)-llh(iter-1)) < tol*abs(llh(iter)); break; end\nend\nllh = llh(2:iter);\nmodel.alpha = alpha; % mixing coefficient\nmodel.beta = beta; % mixture component precision\nmodel.W = W; % linear model coefficent\n[~,label] = max(R,[],1);\nmodel.label = label;\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter14/mixLinReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7501212096688731}} {"text": "function [ triangle_index, alpha, beta, gamma, edge, step_num ] = ...\n triangulation_search_delaunay ( node_num, node_xy, triangle_order, ...\n triangle_num, triangle_node, triangle_neighbor, p )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_SEARCH_DELAUNAY searches a Delaunay triangulation for a point.\n%\n% Purpose:\n%\n% The algorithm \"walks\" from one triangle to its neighboring triangle,\n% and so on, until a triangle is found containing point P, or P is found \n% to be outside the convex hull. \n%\n% The algorithm computes the barycentric coordinates of the point with \n% respect to the current triangle. If all three quantities are positive,\n% the point is contained in the triangle. If the I-th coordinate is\n% negative, then P lies on the far side of edge I, which is opposite\n% from vertex I. This gives a hint as to where to search next.\n%\n% For a Delaunay triangulation, the search is guaranteed to terminate.\n% For other triangulations, a cycle may occur.\n%\n% Note the surprising fact that, even for a Delaunay triangulation of\n% a set of points, the nearest point to P need not be one of the\n% vertices of the triangle containing P. \n%\n% The code can be called for triangulations of any order, but only\n% the first three nodes in each triangle are considered. Thus, if\n% higher order triangles are used, and the extra nodes are intended\n% to give the triangle a polygonal shape, these will have no effect,\n% and the results obtained here might be misleading.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 October 2012\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 vertices.\n%\n% Input, integer TRIANGLE_ORDER, the order of the triangles.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles in the triangulation.\n%\n% Input, integer TRIANGLE_NODE(TRIANGLE_ORDER,TRIANGLE_NUM), \n% the nodes that make up each triangle.\n%\n% Input, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle \n% neighbor list.\n%\n% Input, real P(2), the coordinates of a point.\n%\n% Output, integer TRIANGLE_INDEX, the index of the triangle where the \n% search ended. If a cycle occurred, then TRIANGLE_INDEX = -1.\n%\n% Output, real ALPHA, BETA, GAMMA, the barycentric\n% coordinates of the point relative to triangle TRIANGLE_INDEX.\n%\n% Output, integer EDGE, indicates the position of the point P in\n% triangle TRIANGLE_INDEX:\n% 0, the interior or boundary of the triangle;\n% -1, outside the convex hull of the triangulation, past edge 1;\n% -2, outside the convex hull of the triangulation, past edge 2;\n% -3, outside the convex hull of the triangulation, past edge 3.\n%\n% Output, integer STEP_NUM, the number of steps.\n%\n persistent triangle_index_save;\n\n dim_num = 2;\n\n step_num = - 1;\n edge = 0;\n\n if ( length ( triangle_index_save ) == 0 )\n triangle_index_save = -1;\n end\n\n if ( triangle_index_save < 1 | triangle_num < triangle_index_save )\n triangle_index = floor ( ( triangle_num + 1 ) / 2 );\n else\n triangle_index = triangle_index_save;\n end\n\n while ( 1 )\n\n step_num = step_num + 1;\n\n if ( triangle_num < step_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATION_SEARCH_DELAUNAY - Fatal error!\\n' );\n fprintf ( 1, ' The algorithm seems to be cycling.\\n' );\n triangle_index = -1;\n alpha = -1.0;\n beta = -1.0;\n gamma = -1.0;\n edge = -1;\n return\n end\n%\n% Get the vertices of triangle TRIANGLE_INDEX.\n%\n a = triangle_node(1,triangle_index);\n b = triangle_node(2,triangle_index);\n c = triangle_node(3,triangle_index);\n%\n% Using vertex C as a base, compute the distances to vertices A and B,\n% and the point P.\n%\n dxa = node_xy(1,a) - node_xy(1,c);\n dya = node_xy(2,a) - node_xy(2,c);\n\n dxb = node_xy(1,b) - node_xy(1,c);\n dyb = node_xy(2,b) - node_xy(2,c);\n\n dxp = p(1) - node_xy(1,c);\n dyp = p(2) - node_xy(2,c);\n\n det = dxa * dyb - dya * dxb;\n%\n% Compute the barycentric coordinates of the point P with respect\n% to this triangle.\n%\n alpha = ( dxp * dyb - dyp * dxb ) / det;\n beta = ( dxa * dyp - dya * dxp ) / det;\n gamma = 1.0 - alpha - beta;\n%\n% If the barycentric coordinates are all positive, then the point\n% is inside the triangle and we're done.\n%\n if ( 0.0 <= alpha && 0.0 <= beta && 0.0 <= gamma )\n break\n end\n%\n% At least one barycentric coordinate is negative.\n%\n% If there is a negative barycentric coordinate for which there exists\n% an opposing triangle neighbor closer to the point, move to that triangle.\n%\n% (Two coordinates could be negative, in which case we could go for the\n% most negative one, or the most negative one normalized by the actual\n% distance it represents).\n%\n if ( alpha < 0.0 && 0 < triangle_neighbor(2,triangle_index) )\n triangle_index = triangle_neighbor(2,triangle_index);\n continue;\n elseif ( beta < 0.0 && 0 < triangle_neighbor(3,triangle_index) )\n triangle_index = triangle_neighbor(3,triangle_index);\n continue;\n elseif ( gamma < 0.0 && 0 < triangle_neighbor(1,triangle_index) )\n triangle_index = triangle_neighbor(1,triangle_index);\n continue;\n end\n%\n% All negative barycentric coordinates correspond to vertices opposite\n% sides on the convex hull.\n%\n% Note the edge and exit.\n%\n if ( alpha < 0.0 )\n edge = -2;\n break\n elseif ( beta < 0.0 )\n edge = -3;\n break\n elseif ( gamma < 0.0 )\n edge = -1;\n break\n end\n\n end\n\n triangle_index_save = triangle_index;\n\n return\nend\n", "meta": {"author": "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/triangulation_search_delaunay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7501211979220933}} {"text": "function [r,spherCent]=osculatingSpher4LatLon(latLon,a,f,is2D)\n%%OSCULATINGSPHER4LATLON Given the latitude and longitude of a point on an\n% ellipsoid, determine the radius and center location of an\n% osculating sphere going through that point. The osculating\n% sphere is such that the azimuth equals the longitude and the\n% elevation equals the latitude of the point on the ellipsoid.\n% Additionally, the local tangent planes at the point are the\n% same. The radius of curvature of the sphere at that point\n% should nominally equal the radius of curvature of the ellipsoid\n% at that point. However, since the ellipsoid has two radii of\n% curvature, the geometric mean is used (the mean radius of\n% curvature). On the other hand, if is2D is true, then just the\n% radius of curvature in the meridian will be used, which is what\n% perfectly matches a cut of the ellipsoid through the origin and\n% pole (A 2D ellipse in the x-z plane).\n%\n%INPUTS: latLon The 2X1 point of the format [latitude;longitude] in radians\n% where the osculating sphere should touch the ellipsoid.\n% a The semi-major axis length of the ellipsoid. If this\n% argument is omitted or an empty matrix is passed, the value\n% in Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the ellipsoid. If this argument is\n% omitted or an empty matrix is passed, the value in\n% Constants.WGS84Flattening is used.\n% is2D Indicates whether one just cares about a 2D cut of the\n% ellipsoid. If so, then the radius used will be the radius\n% of curvature in the meridian. The default if omitted or an\n% empty matrix is passed is false.\n%\n%OUTPUTS: r The radius of the osculating sphere.\n% spherCent The location of the center of the osculating sphere with\n% respect to the center of the ellipsoid.\n%\n%The formulae in Section 3 of [1] are used.\n%\n%EXAMPLE:\n%Here, we consider a 2D slice of an ellipsoid that goes through\n%longitude=0, we choose a point. We then find the osculating sphere. The\n%ellipse cut of the ellipsoid and the circle cut of the sphere are then\n%plotted with the point. We ALSO plot the circle cut obtained with\n%is2D=true. Since we are only considering a 2D cut, one will see that that\n%circle is actually better aligned with the curvature of the ellipse at\n%that point. However, if one were to take a 2D cut in other directions, it\n%would appear to be a worse fit.\n% a=20;%Semi-major axis.\n% f=0.5;%Flattening factor.\n% b=a*(1-f);%The semi-minor axis of the ellipsoid.\n% \n% figure(1)\n% clf\n% hold on\n% %Draw a 2D cut of the ellipsoid.\n% A=inv([a^2,0;\n% 0,b^2]);\n% drawEllipse([0;0],A,1,'linewidth',4)\n% latLon=[50;0]*(pi/180);\n% oscPt=ellips2Cart([latLon;0],a,f);\n% [r,spherCent]=osculatingSpher4LatLon(latLon,a,f,false);\n% [r2D,spherCent2D]=osculatingSpher4LatLon(latLon,a,f,true);%is2D=true\n% %Draw the both 2D cuts of the sphere:\n% A=inv([r^2,0;\n% 0,r^2]);\n% drawEllipse([spherCent(1);spherCent(3)],A,1,'-.','linewidth',4)\n% A=inv([r2D^2,0;\n% 0,r2D^2]);\n% drawEllipse([spherCent2D(1);spherCent2D(3)],A,1,'--','linewidth',2)\n% \n% %Note that spherCent(2)==0.\n% scatter(oscPt(1),oscPt(3),100,'filled')\n% legend('Ellipsoid Cut','Osculating Sphere','Osculating Sphere 2D','location','southwest')\n% h1=xlabel('x');\n% h2=ylabel('y');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] P. Williams and D. Last, \"On Loran-C time-difference to co-ordinate\n% converters,\" in Proceedings of the 32nd Annual Convention & Technical\n% Symposium of the International Loran Association, Boulder, CO, 3-7\n% Nov. 2003.\n%\n%August 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(is2D))\n is2D=false;\nend\n\nif(nargin<3||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<2||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\n%The squared eccentricity of the ellipsoid.\ne2=f*(2-f);\n\nlat=latLon(1);%Latitude.\nlon=latLon(2);\n\nPhi=lat;\n\ndenomTerm=sqrt(1-e2*sin(Phi)^2);\n%Equation 3.17 in [1]. The radius of curvature in the meridian.\nM0=a*(1-e2)/denomTerm^3;\n\nif(is2D)\n r=M0;\nelse\n %Equation 3.18 in [1]. The radius of curvature in the prime vertical.\n N0=a/denomTerm;\n\n %Equation 3.16 in [1].\n r=sqrt(M0*N0);\nend\n\nxCartEllips=ellips2Cart([latLon(1:2);0],a,f);\nxCartSpher=spher2Cart([r;lon;lat]);\n\nspherCent=-(xCartSpher-xCartEllips);\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/Osculating_Coordinates/osculatingSpher4LatLon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7501211823704745}} {"text": "% ========================= \n% Robust Bayesian allocation in the stock market, as described in\n% Meucci, A., (2005) \"Robust Bayesian Allocation\"\n% \n% Most recent version of article and code available at http://symmys.com/node/102\n% =========================\n\nclear; clc; close all;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% inputs\np_m=.1; % robustness parameter location\np_s=.1; % robustness parameter scatter\nload SectorsSnP500\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute weekly returns\nPs=P(1:5:end,:);\nR=Ps(2:end,:)./Ps(1:end-1,:)-1;\nDates_P=DP(1:5:end);\nDates_R=Dates_P(2:end);\n[Ttot,N]=size(R);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% estimation\nW=52; % rolling estimation period\nNumPortf=10;\nRet_hat=[];\nRet_rB=[];\nDates=[];\nfor t=W+1:Ttot-1\n Ttot-t+2\n Rets=R(t-W:t,:);\n\n % sample estimate\n m_hat=mean(Rets)';\n S_hat=cov(Rets);\n [de_hat,ds_hat,w_hat] = EfficientFrontier(NumPortf, S_hat, m_hat);\n\n % Bayesian prior\n S0=diag(diag(S_hat));\n m0=.5*S0*ones(N,1)/N;\n T=size(Rets,1);\n T0=2*T;\n nu0=2*T;\n\n % Bayesian posterior parameters\n T1=T+T0;\n m1=1/T1*(m_hat*T+m0*T0);\n nu1=T+nu0;\n S1=1/nu1*( S_hat*T + S0*nu0 + (m_hat-m0)*(m_hat-m0)'/(1/T+1/T0) );\n [d,d,w1] = EfficientFrontier(NumPortf, S1, m1);\n\n % robustness parameters\n q_m2=chi2inv(p_m,N);\n g_m=sqrt(q_m2/T1*nu1/(nu1-2));\n q_s2=chi2inv(p_s,N*(N+1)/2);\n PickVol=round(.8*NumPortf);\n v=(ds_hat(PickVol))^2;\n g_s=v/( nu1/(nu1+N+1)+sqrt( 2*nu1*nu1*q_s2/((nu1+N+1)^3)));\n \n Target=[];\n \n wu=w_hat(PickVol,:)';\n Ret_hat=[Ret_hat R(t+1,:)*wu];\n\n for k=1:NumPortf-1\n NewTarget=-(10^10);\n if wu'*S1*wu <= g_s\n NewTarget = m1'*wu-g_m*sqrt(wu'*S1*wu);\n end\n Target=[Target NewTarget];\n end\n\n [Best,k]=max(Target);\n wu=w1(k,:)';\n Ret_rB=[Ret_rB R(t+1,:)*wu];\n \n Dates=[Dates Dates_R(t+1)];\nend\n\nNAV_hat=cumprod(1+Ret_hat);\nNAV_rB=cumprod(1+Ret_rB);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plots\n\nfigure\nsubplot(2,1,1)\nh=plot(Dates,Ret_hat);\nxlim([Dates(1) Dates(end)])\nYLim=get(gca,'ylim');\nDatetick('x','mmmyy','keeplimits','keepticks');\ngrid on\nsubplot(2,1,2)\nh=plot(Dates,Ret_rB);\nset(gca,'ylim',YLim,'xlim',[Dates(1) Dates(end)]);\nDatetick('x','mmmyy','keeplimits','keepticks');\ngrid on\n\nfigure\nsubplot(2,1,1)\nh=plot(Dates,NAV_hat);\nxlim([Dates(1) Dates(end)])\nYLim=get(gca,'ylim');\nDatetick('x','mmmyy','keeplimits','keepticks');\ngrid on\nsubplot(2,1,2)\nh=plot(Dates,NAV_rB);\nset(gca,'ylim',YLim,'xlim',[Dates(1) Dates(end)]);\nDatetick('x','mmmyy','keeplimits','keepticks');\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/31419-robust-bayesian-allocation/Meucci_RobustBayesian/S_SnPCaseStudy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7501206090769444}} {"text": "function b = r83p_vxm ( n, a, x )\n\n%*****************************************************************************80\n%\n%% R83P_VXM multiplies a vector by a R83P matrix.\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% 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% 16 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(3,N), the R83P matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(N), the product X * A.\n%\n b(1) = a(1,1) * x(n) + a(2,1) * x(1) + a(3,1) * x(2);\n\n for i = 2 : n-1\n b(i) = a(1,i) * x(i-1) + a(2,i) * x(i) + a(3,i) * x(i+1);\n end\n\n b(n) = a(1,n) * x(n-1) + a(2,n) * x(n) + a(3,n) * x(1);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r83p_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7500857143032894}} {"text": "function proj2d = compute_one_projection_method_2(xs,ys,zs,data3d,psrc,pcdet,su,sv,nu,nv)\n%\n%\tproj2d = compute_one_projection_method_2(xs,ys,zs,data3d,psrc,pcdet,su,sv,nu,nv)\n%\n%\tMethod 2: compute the project based on the stack of planes perpendicular to the src-detector line\n%\tThis method should be faster than the line-integral method\n%\n% Deshan Yang, PhD\n%\tDepartment of radiation oncology\n%\tWashington University in Saint Louis\n% 01/16/2011, Saint Louis, MO, USA\n%\n\ncorner_points = [...\n\txs(1) ys(1) zs(1);...\n\txs(1) ys(1) zs(end);...\n\txs(1) ys(end) zs(1);...\n\txs(1) ys(end) zs(end);...\n\txs(end) ys(1) zs(1);...\n\txs(end) ys(1) zs(end);...\n\txs(end) ys(end) zs(1);...\n\txs(end) ys(end) zs(end)...\n\t];\n\ncorner_points_t = zeros(8,1);\nfor k =1:8\n\tp = corner_points(k,:);\n\t[q,corner_points_t(k)] = project_1_point_to_a_line(psrc,pcdet,p);\nend\n\nt_min = min(corner_points_t);\nt_max = max(corner_points_t);\n\ndist = norm(psrc-pcdet);\n\nN = ceil(dist*(t_max-t_min));\t% N planes\ndt = (t_max-t_min)/N;\nts = t_min:dt:t_max;\n\n\nproj2d = zeros(nv,nu,'single');\nvecu = [0 0 1];\n\nvecn = psrc-pcdet;\nvecv = cross(vecn,vecu);\nvecv = vecv/norm(vecv);\n\nus = ((-nu/2+0.5):1:(nu/2-0.5))*su/nu;\nvs = ((-nv/2+0.5):1:(nv/2-0.5))*sv/nv;\n[uu,vv] = meshgrid(us,vs);\n\nfor T = 1:N\n\tvecu_t = vecu*ts(T);\n\tvecv_t = vecv*ts(T);\n\tpcdet_t = psrc+ts(T)*(pcdet-psrc);\n\n\tvdet_t_xs = pcdet_t(1) + vecu_t(1)*uu + vecv_t(1)*vv;\n\tvdet_t_ys = pcdet_t(2) + vecu_t(2)*uu + vecv_t(2)*vv;\n\tvdet_t_zs = pcdet_t(3) + vecu_t(3)*uu + vecv_t(3)*vv;\n\t\n\tproj2d = proj2d + interp3(xs,ys,zs,data3d,vdet_t_xs,vdet_t_ys,vdet_t_zs,'linear',0)*dt*dist;\nend\n\n% adjust the value according to the projection path length\nvdet_t_xs = pcdet(1) + vecu(1)*uu + vecv(1)*vv;\nvdet_t_ys = pcdet(2) + vecu(2)*uu + vecv(2)*vv;\nvdet_t_zs = pcdet(3) + vecu(3)*uu + vecv(3)*vv;\n\ndists = sqrt((vdet_t_xs-psrc(1)).^2+(vdet_t_ys-psrc(2)).^2+(vdet_t_zs-psrc(3)).^2);\ndists = dists / min(dists(:));\nproj2d = proj2d .* dists;\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30207-cone-beam-ct-simulation/compute_one_projection_method_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7500857102944514}} {"text": "function deg = rad2deg(rad)\n\n% RAD2DEG Radians to degrees conversion.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\ndeg = rad/pi*180;\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Math/rad2deg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7500382529859045}} {"text": " function pgd_step_test\n%function pgd_step_test\n% test the PGD algorithm using 2D LS cost function\n\n% cost function terms\nkap = 4;\nA = [1 0; 0 sqrt(kap)];\nW = eye(2);\nM = eye(2);\nyy = 0;\n\nf.niter = 10;\nx = [-kap; 1];\n\n% run PSD\nxpsd = qpwls_psd(x, A, W, yy, 0, 'precon', 1, 'niter', f.niter, 'isave', 'all');\n\n% run PGD\ndata = {yy, A, W};\nf.step = 3.3; % best step is 0.4, so illustrate suboptimal step\n[xpgd1 steps] = pgd_step(x, data, @costgrad, 'precon', M, ...\n\t\t'step_method', 'user', 'step', f.step, ...\n\t\t'niter', f.niter, 'isave', 'all', 'chat', 0);\n\t\n%pr steps\n[xpgd2 steps] = pgd_step(x, data, @costgrad, 'precon', M, ...\n\t\t'step_method', 'der2', ...\n\t\t'niter', f.niter, 'isave', 'all', 'chat', 0);\n%pr steps\n\nif im\n\tclf, subplot(211)\n\tplot(\txpsd(1,:), xpsd(2,:), 'y-o', ...\n\t\txpgd1(1,:), xpgd1(2,:), 'b--+', ...\n\t\txpgd2(1,:), xpgd2(2,:), 'm:.')\n\txlabel x1, ylabel x2\n\ttitle 'QPWLS example'\n\tleg = {'PSD', sprintf('PGD:%g', f.step), 'PGD:Newton'};\n\tlegend(leg{:}, 3)\nend\n\n% cost function map\nif ~isvar('qq')\n\tx1 = linspace(-4.5,0.5,41)';\n\tx2 = linspace(-1,1.5,43)';\n\t[xx1 xx2] = ndgrid(x1,x2);\n\tqq = 0 * xx1;\n\tfor i1=1:length(x1)\n\t\tfor i2=1:length(x2)\n\t\t\tx = [x1(i1) x2(i2)]';\n\t\t\tqq(i1,i2) = norm(sqrtm(W) * (yy - A * x)).^2;\n\t\tend\n\tend\nend\n\nif im\n\thold on\n\tcontour(x1, x2, qq', 8)\n\tplot(0,0, 'rx')\n\thold off\n\taxis equal\n\taxis([-4.5 0.5 -1 1.5])\n\txtick(-4:0)\n\tytick(-1:1)\n\tcolormap(0.3+0.7*gray)\nend\n\nif im\n\tsubplot(212)\n\tplot(\t0:f.niter, sum(abs(xpsd), 1), 'y-o', ...\n\t\t0:f.niter, sum(abs(xpgd1)), 'b--x', ...\n\t\t0:f.niter, sum(abs(xpgd2)), 'm:.')\n\txlabel 'iteration', ylabel '||x||_1'\n\tlegend(leg{:}, 1)\nend\n\n\n% cost function and gradient for basic WLS\nfunction [cost, grad] = costgrad(x, data)\ny = data{1};\nA = data{2};\nW = data{3};\n\np = A * x;\ncost = 0.5 * norm(sqrtm(W) * (y - p)).^2;\nif nargout > 1\n\tgrad = -A' * (W * (y - p));\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/general/pgd_step_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7500192083605199}} {"text": "function mean = f_mean ( m, n )\n\n%*****************************************************************************80\n%\n%% F_MEAN returns the mean of the F central PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the parameters of the PDF.\n% 1 <= M,\n% 1 <= N.\n% Note, however, that the mean is not defined unless 3 <= N.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'F_MEAN - Fatal error!\\n' );\n fprintf ( 1, ' The mean is not defined for N < 3.\\n' );\n error ( 'F_MEAN - Fatal error!' );\n end\n\n mean = n / ( 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/prob/f_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7500096415682259}} {"text": "% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc % clean the command prompt\nL = 0.1; % 10 cm length\nW = 0.01; % 1 cm thickness\nNx = 50; % number of cell in x direction\nNy = 20; % number of cells in the y direction\nm = createMesh2D(Nx, Ny, L, W); % creates a 2D Cartesian grid\n% m = createMesh3D(Nx, Ny,Ny, L, W,W); % creates a 3D Cartesian grid, activate this line if you are curious\nT_inf = 25+273.15; % [K] ambient temperature\nT_base = 100+273.15; % [K] temperature at the base of the fin\nk_val = 237; % W/(m.K) thermal conductivity\nh_val = 10; % W/(m^2.K) heat transfer coefficient\nk = createCellVariable(m, k_val); % assign thermal cond. value to all cells\nk_face = geometricMean(k); % geometric average of the thermal conductivity values on the cell faces\nBC = createBC(m); % creates a BC structure for the domain m; all Neumann boundaries\nBC.left.a(:)=0; BC.left.b(:)=1; BC.left.c(:)=T_base; % convert the left boundary to constant temperature\nBC.right.a(:)=k_val/h_val; BC.right.b(:)=1; BC.right.c(:)=T_inf; % right boundary to Robin\nBC.top.a(:)=k_val/h_val; BC.top.b(:)=1; BC.top.c(:)=T_inf; % top boundary to Robin\nBC.bottom.a(:)=-k_val/h_val; BC.bottom.b(:)=1; BC.bottom.c(:)=T_inf; % bottom boundary to Robin (don't forget the normal vector sign)\nM_cond = diffusionTerm(k_face); % matrix of coefficients for the heat diffusion\n[M_bc, RHS_bc] = boundaryCondition(BC); % matrix of coefficients and RHS vector for the boundary conditions\nT = solvePDE(m, M_cond+M_bc, RHS_bc); % solve the linear system of discretized PDE\nvisualizeCells(T); % visualize the results\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Tutorial/heatconductionfin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7500027251305625}}