声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 2281|回复: 5

[编程技巧] 实验变差函数,输入变量赋值的问题!

[复制链接]
发表于 2012-6-26 17:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
各位高手,我现在有一个关于实验变差函数的代码,现在遇到一个问题:该如何给输入变量赋值?希望懂的人能帮我看看,多谢了! variogram.rar (4.42 KB, 下载次数: 13)
  1. function S = variogram(x,y,varargin)

  2. % isotropic and anisotropic experimental (semi-)variogram
  3. %
  4. % Syntax:
  5. % d = variogram(x,y)
  6. % d = variogram(x,y,'propertyname','propertyvalue',...)
  7. %
  8. % Description:
  9. % variogram calculates the experimental variogram in various
  10. % dimensions.
  11. %
  12. % Input:
  13. % x - array with coordinates. Each row is a location in a
  14. % size(x,2)-dimensional space (e.g. [x y elevation])
  15. % y - column vector with values of the locations in x.
  16. %
  17. % Propertyname/-value pairs:
  18. % nrbins - number bins the distance should be grouped into
  19. % (default = 20)
  20. % maxdist - maximum distance for variogram calculation
  21. % (default = maximum distance in the dataset / 2)
  22. % type - 'gamma' returns the variogram value (default)
  23. % 'cloud1' returns the binned variogram cloud
  24. % 'cloud2' returns the variogram cloud
  25. % plotit - true -> plot variogram
  26. % false -> don't plot (default)
  27. % subsample - number of randomly drawn points if large datasets are used.
  28. % scalar (positive integer, e.g. 3000)
  29. % inf (default) = no subsampling
  30. % anisotropy - false (default), true (works only in two dimensions)
  31. % thetastep - if anisotropy is set to true, specifying thetastep
  32. % allows you the angle width (default 30?
  33. %
  34. %
  35. % Output:
  36. % d - structure array with distance and gamma - vector
  37. %
  38. % Example: Generate a random field with periodic variation in x direction
  39. %
  40. % x = rand(1000,1)*4-2;
  41. % y = rand(1000,1)*4-2;
  42. % z = 3*sin(x*15)+ randn(size(x));
  43. %
  44. % subplot(2,2,1)
  45. % scatter(x,y,4,z,'filled'); box on;
  46. % ylabel('y'); xlabel('x')
  47. % title('data (coloring according to z-value)')
  48. % subplot(2,2,2)
  49. % hist(z,20)
  50. % ylabel('frequency'); xlabel('z')
  51. % title('histogram of z-values')
  52. % subplot(2,2,3)
  53. % d = variogram([x y],z,'plotit',true,'nrbins',50);
  54. % title('Isotropic variogram')
  55. % subplot(2,2,4)
  56. % d2 = variogram([x y],z,'plotit',true,'nrbins',50,'anisotropy',true);
  57. % title('Anisotropic variogram')
  58. %
  59. % Requirements:
  60. % The function uses (objectId=10670)
  61. % by Malcolm wood as subfunction.
  62. %
  63. % See also: KRIGING, VARIOGRAMFIT
  64. %
  65. % Date: 21. July, 2011
  66. % Author: Wolfgang Schwanghart (w.schwanghart[at]unibas.ch)


  67. % error checking
  68. if size(y,1) ~= size(x,1);
  69. error('x and y must have the same number of rows')
  70. end

  71. % check for nans(非数值数)
  72. II = any(isnan(x),2) | isnan(y);%这的关于x和y的表达为什么不同;
  73. x(II,:) = [];
  74. y(II) = [];

  75. % extent of dataset(数据范围)
  76. minx = min(x,[],1);
  77. maxx = max(x,[],1);
  78. maxd = sqrt(sum((maxx-minx).^2));%变差函数最大计算距离
  79. nrdims = size(x,2);%2表示返回x的列数

  80. % check input using PARSEARGS
  81. params.nrbins = 20;
  82. params.maxdist = maxd/2;
  83. params.type = {'default','gamma','cloud1','cloud2'};
  84. params.plotit = false;
  85. params.anisotropy = false;
  86. params.thetastep = 30;
  87. params.subsample = inf;
  88. params = parseargs(params,varargin{:});

  89. if params.maxdist > maxd;
  90. warning('Matlab:Variogram',...
  91. ['Maximum distance exceeds maximum distance \n' ...
  92. 'in the dataset. maxdist was decreased to ' num2str(maxd) ]);
  93. params.maxdist = maxd;
  94. end

  95. if params.anisotropy && nrdims ~= 2
  96. params.anisotropy = false;
  97. warning('Matlab:Variogram',...
  98. 'Anistropy is only supported for 2D data');
  99. end

  100. % take only a subset of the data;
  101. if ~isinf(params.subsample) && numel(y)>params.subsample;
  102. IX = randperm(numel(y));%randperm:随机排列,随即置换
  103. x = x(IX(1:params.subsample),:);
  104. y = y(IX(1:params.subsample),:);
  105. end

  106. % calculate bin tolerance
  107. tol = params.maxdist/params.nrbins;

  108. % calculate distance matrix
  109. iid = distmat(x,params.maxdist);

  110. % calculate squared difference between values of coordinate pairs
  111. lam = (y(iid(:,1))-y(iid(:,2))).^2;

  112. % anisotropy
  113. if params.anisotropy
  114. nrthetaedges = floor(180/params.thetastep);

  115. % calculate with radians, not degrees
  116. params.thetastep = params.thetastep/180*pi;

  117. % calculate angles, note that angle is calculated clockwise from top
  118. theta = atan2(x(iid(:,2),1)-x(iid(:,1),1),...
  119. x(iid(:,2),2)-x(iid(:,1),2));

  120. % only the semicircle is necessary for the directions
  121. I = theta < 0;
  122. theta(I) = theta(I)+pi;
  123. I = theta >= pi-params.thetastep/2;
  124. theta(I) = 0;

  125. % create a vector with edges for binning of theta
  126. % directions go from 0 to 180 degrees;
  127. thetaedges = linspace(-params.thetastep/2,pi-params.thetastep/2,nrthetaedges);

  128. % bin theta
  129. [ntheta,ixtheta] = histc(theta,thetaedges);

  130. % bin centers
  131. thetacents = thetaedges(1:end)+params.thetastep/2;
  132. thetacents(end) = pi; %[];
  133. end

  134. % calculate variogram
  135. switch params.type
  136. case {'default','gamma'}
  137. % variogram anonymous function
  138. fvar = @(x) 1./(2*numel(x)) * sum(x);

  139. % distance bins
  140. edges = linspace(0,params.maxdist,params.nrbins+1);
  141. edges(end) = inf;

  142. [nedge,ixedge] = histc(iid(:,3),edges);

  143. if params.anisotropy
  144. S.val = accumarray([ixedge ixtheta],lam,...
  145. [numel(edges) numel(thetaedges)],fvar,nan);
  146. S.val(:,end)=S.val(:,1);
  147. S.theta = thetacents;
  148. S.num = accumarray([ixedge ixtheta],ones(size(lam)),...
  149. [numel(edges) numel(thetaedges)],@sum,nan);
  150. S.num(:,end)=S.num(:,1);
  151. else
  152. S.val = accumarray(ixedge,lam,[numel(edges) 1],fvar,nan);
  153. S.num = accumarray(ixedge,ones(size(lam)),[numel(edges) 1],@sum,nan);
  154. end
  155. S.distance = (edges(1:end-1)+tol/2)';
  156. S.val(end,:) = [];
  157. S.num(end,:) = [];

  158. case 'cloud1'
  159. edges = linspace(0,params.maxdist,params.nrbins+1);
  160. edges(end) = inf;

  161. [nedge,ixedge] = histc(iid(:,3),edges);

  162. S.distance = edges(ixedge) + tol/2;
  163. S.distance = S.distance(:);
  164. S.val = lam;
  165. if params.anisotropy
  166. S.theta = thetacents(ixtheta);
  167. end
  168. case 'cloud2'
  169. S.distance = iid(:,3);
  170. S.val = lam;
  171. if params.anisotropy
  172. S.theta = thetacents(ixtheta);
  173. end
  174. end


  175. % create plot if desired
  176. if params.plotit
  177. switch params.type
  178. case {'default','gamma'}
  179. marker = 'o--';
  180. otherwise
  181. marker = '.';
  182. end

  183. if ~params.anisotropy
  184. plot(S.distance,S.val,marker);
  185. axis([0 params.maxdist 0 max(S.val)*1.1]);
  186. xlabel('h');
  187. ylabel('\gamma (h)');
  188. title('(Semi-)Variogram');
  189. else
  190. [Xi,Yi] = pol2cart(repmat(S.theta,numel(S.distance),1),repmat(S.distance,1,numel(S.theta)));
  191. surf(Xi,Yi,S.val)
  192. xlabel('h y-direction')
  193. ylabel('h x-direction')
  194. zlabel('\gamma (h)')
  195. title('directional variogram')
  196. % set(gca,'DataAspectRatio',[1 1 1/30])
  197. end
  198. end

  199. end


  200. % subfunction distmat

  201. function iid = distmat(X,dmax)

  202. % constrained distance function
  203. %
  204. % iid -> [rows, columns, distance]


  205. n = size(X,1);
  206. nrdim = size(X,2);
  207. if size(X,1) < 1000;
  208. [i,j] = find(triu(true(n)));
  209. if nrdim == 1;
  210. d = abs(X(i)-X(j));
  211. elseif nrdim == 2;
  212. d = hypot(X(i,1)-X(j,1),X(i,2)-X(j,2));
  213. else
  214. d = sqrt(sum((X(i,:)-X(j,:)).^2));
  215. end
  216. I = d<=dmax;
  217. iid = [i(I) j(I) d(I)];
  218. else
  219. ix = (1:n)';
  220. if nrdim == 1;
  221. iid = arrayfun(@distmatsub1d,(1:n)','UniformOutput',false);
  222. elseif nrdim == 2;
  223. % if needed change distmatsub to distmatsub2d which is numerically
  224. % better but slower
  225. iid = arrayfun(@distmatsub,(1:n)','UniformOutput',false);
  226. else
  227. iid = arrayfun(@distmatsub,(1:n)','UniformOutput',false);
  228. end
  229. nn = cellfun(@(x) size(x,1),iid,'UniformOutput',true);
  230. I = nn>0;
  231. ix = ix(I);
  232. nn = nn(I);
  233. nncum = cumsum(nn);
  234. c = zeros(nncum(end),1);
  235. c([1;nncum(1:end-1)+1]) = 1;
  236. i = ix(cumsum(c));
  237. iid = [i cell2mat(iid)];

  238. end

  239. function iid = distmatsub1d(i)
  240. j = (i+1:n)';
  241. d = abs(X(i)-X(j));
  242. I = d<=dmax;
  243. iid = [j(I) d(I)];
  244. end

  245. function iid = distmatsub2d(i) %#ok<DEFNU>
  246. j = (i+1:n)';
  247. d = hypot(X(i,1) - X(j,1),X(i,2) - X(j,2));
  248. I = d<=dmax;
  249. iid = [j(I) d(I)];
  250. end

  251. function iid = distmatsub(i)
  252. j = (i+1:n)';
  253. d = sqrt(sum(bsxfun(@minus,X(i,:),X(j,:)).^2,2));
  254. I = d<=dmax;
  255. iid = [j(I) d(I)];
  256. end
  257. end



  258. % subfunction parseargs

  259. function X = parseargs(X,varargin)

  260. %PARSEARGS - Parses name-value pairs
  261. %
  262. % Behaves like setfield, but accepts multiple name-value pairs and provides
  263. % some additional features:
  264. % 1) If any field of X is an cell-array of strings, it can only be set to
  265. % one of those strings. If no value is specified for that field, the
  266. % first string is selected.
  267. % 2) Where the field is not empty, its data type cannot be changed
  268. % 3) Where the field contains a scalar, its size cannot be changed.
  269. %
  270. % X = parseargs(X,name1,value1,name2,value2,...)
  271. %
  272. % Intended for use as an argument parser for functions which multiple options.
  273. % Example usage:
  274. %
  275. % function my_function(varargin)
  276. % X.StartValue = 0;
  277. % X.StopOnError = false;
  278. % X.SolverType = {'fixedstep','variablestep'};
  279. % X.OutputFile = 'out.txt';
  280. % X = parseargs(X,varargin{:});
  281. %
  282. % Then call (e.g.):
  283. %
  284. % my_function('OutputFile','out2.txt','SolverType','variablestep');

  285. % The various #ok comments below are to stop MLint complaining about
  286. % inefficient usage. In all cases, the inefficient usage (of error, getfield,
  287. % setfield and find) is used to ensure compatibility with earlier versions
  288. % of MATLAB.

  289. remaining = nargin-1; % number of arguments other than X
  290. count = 1;
  291. fields = fieldnames(X);
  292. modified = zeros(size(fields));
  293. % Take input arguments two at a time until we run out.
  294. while remaining>=2
  295. fieldname = varargin{count};
  296. fieldind = find(strcmp(fieldname,fields));
  297. if ~isempty(fieldind)
  298. oldvalue = getfield(X,fieldname); %#ok
  299. newvalue = varargin{count+1};
  300. if iscell(oldvalue)
  301. % Cell arrays must contain strings, and the new value must be
  302. % a string which appears in the list.
  303. if ~iscellstr(oldvalue)
  304. error(sprintf('All allowed values for "%s" must be strings',fieldname)); %#ok
  305. end
  306. if ~ischar(newvalue)
  307. error(sprintf('New value for "%s" must be a string',fieldname)); %#ok
  308. end
  309. if isempty(find(strcmp(oldvalue,newvalue))) %#ok
  310. error(sprintf('"%s" is not allowed for field "%s"',newvalue,fieldname)); %#ok
  311. end
  312. elseif ~isempty(oldvalue)
  313. % The caller isn't allowed to change the data type of a non-empty property,
  314. % and scalars must remain as scalars.
  315. if ~strcmp(class(oldvalue),class(newvalue))
  316. error(sprintf('Cannot change class of field "%s" from "%s" to "%s"',...
  317. fieldname,class(oldvalue),class(newvalue))); %#ok
  318. elseif numel(oldvalue)==1 & numel(newvalue)~=1 %#ok
  319. error(sprintf('New value for "%s" must be a scalar',fieldname)); %#ok
  320. end
  321. end
  322. X = setfield(X,fieldname,newvalue); %#ok
  323. modified(fieldind) = 1;
  324. else
  325. error(['Not a valid field name: ' fieldname]);
  326. end
  327. remaining = remaining - 2;
  328. count = count + 2;
  329. end
  330. % Check that we had a value for every name.
  331. if remaining~=0
  332. error('Odd number of arguments supplied. Name-value pairs required');
  333. end

  334. % Now find cell arrays which were not modified by the above process, and select
  335. % the first string.
  336. notmodified = find(~modified);
  337. for i=1:length(notmodified)
  338. fieldname = fields{notmodified(i)};
  339. oldvalue = getfield(X,fieldname); %#ok
  340. if iscell(oldvalue)
  341. if ~iscellstr(oldvalue)
  342. error(sprintf('All allowed values for "%s" must be strings',fieldname)); %#ok
  343. elseif isempty(oldvalue)
  344. error(sprintf('Empty cell array not allowed for field "%s"',fieldname)); %#ok
  345. end
  346. X = setfield(X,fieldname,oldvalue{1}); %#ok
  347. end
  348. end
  349. end







复制代码

回复
分享到:

使用道具 举报

 楼主| 发表于 2012-6-27 08:38 | 显示全部楼层
自己先顶一下,希望大家尽快看到,帮忙解决一下,多谢了!!!!
发表于 2012-6-27 11:23 | 显示全部楼层
该如何给输入变量赋值?

个人水平有限, 真不懂LZ的意思!?
LZ的函数裡头不是有说明及例子了?:@)
 楼主| 发表于 2012-6-27 14:53 | 显示全部楼层
回复 3 # ChaChing 的帖子

实例是一个script文件,这个程序本身是函数文件,输入变量x,y不是随机生成的量,是要从外部输入的,是大批量数据,在command窗口直接输入不现实,所以我就想问如何给输入变量赋值。
发表于 2012-6-27 16:06 | 显示全部楼层
本帖最后由 ChaChing 于 2012-6-27 16:07 编辑

回复 4 # 漠漠之堡 的帖子

Ref: 3.[原创]使用文本文件(.txt)进行数据存取的技巧总结 http://forum.vibunion.com/thread-45622-1-1.html
   也谈在Matlab中读入数字与字符混排的文本数据 http://forum.vibunion.com/thread-8937-1-1.html
   [转帖]matlab中常见txt文件读入的实用方法 http://forum.vibunion.com/thread-2029-1-1.html
   在Matlab中读入数字与字符混排的文本数据 http://forum.vibunion.com/thread-7985-1-1.html
   如何导入大量数据 http://forum.vibunion.com/thread-104333-1-2.html
From http://forum.vibunion.com/home-space-uid-63979-do-blog-id-18250.html
 楼主| 发表于 2012-6-27 23:21 | 显示全部楼层
回复 5 # ChaChing 的帖子

:time:学习下,多谢了!
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-11-24 19:03 , Processed in 0.072640 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表