/code_oth/som_eucdist2.m

http://research-code-base-animesh.googlecode.com/ · MATLAB · 94 lines · 44 code · 14 blank · 36 comment · 10 complexity · 58b004792cf03d6d1993e5ab2aaf1b46 MD5 · raw file

  1. function d=som_eucdist2(Data, Proto)
  2. %SOM_EUCDIST2 Calculates matrix of squared euclidean distances between set of vectors or map, data struct
  3. %
  4. % d=som_eucdist2(D, P)
  5. %
  6. % d=som_eucdist(sMap, sData);
  7. % d=som_eucdist(sData, sMap);
  8. % d=som_eucdist(sMap1, sMap2);
  9. % d=som_eucdist(datamatrix1, datamatrix2);
  10. %
  11. % Input and output arguments ([]'s are optional):
  12. % D (matrix) size Nxd
  13. % (struct) map or data struct
  14. % P (matrix) size Pxd
  15. % (struct) map or data struct
  16. % d (matrix) distance matrix of size NxP
  17. %
  18. % IMPORTANT
  19. %
  20. % * Calculates _squared_ euclidean distances
  21. % * Observe that the mask in the map struct is not taken into account while
  22. % calculating the euclidean distance
  23. %
  24. % See also KNN, PDIST.
  25. % Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg
  26. % Copyright (c) by Johan Himberg
  27. % http://www.cis.hut.fi/projects/somtoolbox/
  28. % Version 2.0beta Johan 291000
  29. %% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  30. if isstruct(Data);
  31. if isfield(Data,'type') & ischar(Data.type),
  32. ;
  33. else
  34. error('Invalid map/data struct?');
  35. end
  36. switch Data.type
  37. case 'som_map'
  38. data=Data.codebook;
  39. case 'som_data'
  40. data=Data.data;
  41. end
  42. else
  43. % is already a matrix
  44. data=Data;
  45. end
  46. % Take prototype vectors from prototype struct
  47. if isstruct(Proto),
  48. if isfield(Proto,'type') & ischar(Proto.type),
  49. ;
  50. else
  51. error('Invalid map/data struct?');
  52. end
  53. switch Proto.type
  54. case 'som_map'
  55. proto=Proto.codebook;
  56. case 'som_data'
  57. proto=Proto.data;
  58. end
  59. else
  60. % is already a matrix
  61. proto=Proto;
  62. end
  63. % Check that inputs are matrices
  64. if ~vis_valuetype(proto,{'nxm'}) | ~vis_valuetype(data,{'nxm'}),
  65. error('Prototype or data input not valid.')
  66. end
  67. % Record data&proto sizes and check their dims
  68. [N_data dim_data]=size(data);
  69. [N_proto dim_proto]=size(proto);
  70. if dim_proto ~= dim_data,
  71. error('Data and prototype vector dimension does not match.');
  72. end
  73. % Calculate euclidean distances between classifiees and prototypes
  74. d=distance(data,proto);
  75. %%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  76. function d=distance(X,Y);
  77. % Euclidean distance matrix between row vectors in X and Y
  78. U=~isnan(Y); Y(~U)=0;
  79. V=~isnan(X); X(~V)=0;
  80. d=abs(X.^2*U'+V*Y'.^2-2*X*Y');