subscript.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. function varargout = subscript(m,range,wantc)
  2. % function varargout = subscript(m,range,wantc)
  3. %
  4. % <m> is a matrix (of numbers) or a string referring to a matrix
  5. % variable in the base workspace. cell matrices are okay.
  6. % <range> is:
  7. % (1) vector index range that does not use
  8. % the 'end' keyword, e.g., 4, [5 6]
  9. % (2) a logical indexing matrix
  10. % (3) the string ':'
  11. % (4) a cell vector where elements can be of types (1), (2), (3),
  12. % e.g., {':' 4:5}
  13. % <wantc> (optional) is whether to perform cell de-referencing. default: 0.
  14. %
  15. % return something like m(range), or m{range} when <wantc>.
  16. %
  17. % this function is useful for cases where you want
  18. % to get a range of elements from something that
  19. % already has parentheses or brackets.
  20. % it is also useful for working with string-variable
  21. % representations of matrices. it is also useful
  22. % for writing functions that make no assumption about
  23. % the size of the matrices used as input.
  24. %
  25. % example:
  26. % isequal(size(subscript(randn(10,10),{1:2 ':'})),[2 10])
  27. % a = [1 2; 3 4];
  28. % subscript('a',1)
  29. % subscript('a',a<1.5)
  30. % input
  31. if ~exist('wantc','var') || isempty(wantc)
  32. wantc = 0;
  33. end
  34. % do it
  35. if wantc
  36. if iscell(range)
  37. if ischar(m)
  38. varargout = evalin('base',['subscript(',m,',',cell2str(range),',1);']);
  39. else
  40. varargout = m(range{:});
  41. end
  42. else
  43. if ischar(m)
  44. if ischar(range) && isequal(range,':')
  45. varargout = evalin('base',[m,'(:);']);
  46. else
  47. varargout = evalin('base',[m,'(',mat2str(range),');']);
  48. end
  49. else
  50. if ischar(range) && isequal(range,':')
  51. varargout = m(:);
  52. else
  53. varargout = m(range);
  54. end
  55. end
  56. end
  57. else
  58. varargout = cell(1,1);
  59. if iscell(range)
  60. if ischar(m)
  61. varargout{1} = evalin('base',['subscript(',m,',',cell2str(range),');']);
  62. else
  63. varargout{1} = m(range{:});
  64. end
  65. else
  66. if ischar(m)
  67. if ischar(range) && isequal(range,':')
  68. varargout{1} = evalin('base',[m,'(:);']);
  69. else
  70. varargout{1} = evalin('base',[m,'(',mat2str(range),');']);
  71. end
  72. else
  73. if ischar(range) && isequal(range,':')
  74. varargout{1} = m(:);
  75. else
  76. varargout{1} = m(range);
  77. end
  78. end
  79. end
  80. end