3

Is there anyway to index a ndgrid output without actually constructing the output, because of memory issues? Suppose we need to construct output and ask for i th element

[output{1:n}] = ndgrid(1:k)  
[output{1}(i) ... output{n}(i)]

Is it possible to avoid the construction?

2 Answers2

2

I believe you are looking for the function ind2sub:

[o{1:n}] = ind2sub( ones(1,n)*k, ii );

The size of your ndgrid is [k, k, ... k] (n times) and you are trying to access the linear index ii into this k^n dimensional hyper-volume.


PS,
It is best not to use i as a variable name in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    One interesting thing is that the reverse operation can be done using [sub2ind](http://www.mathworks.com/help/matlab/ref/sub2ind.html). – Elrond Gimli Nov 19 '14 at 21:34
2

I had worked this out, so I am posting a complete answer. Write the following function in an m-file:

function output=my_ndgrid(varargin)

in=nargin;
sz=zeros(1,in-1);
for i=1:in-1
    sz(i)=length(varargin{i});
end

ind=varargin{in};

[ndgrid_ind{1:length(sz)}] = ind2sub(sz,ind);

for i=1:length(sz)
    output{i}(ind)=varargin{i}(ndgrid_ind{i});
end

end

following command taken from this answer

[ndgrid_ind{1:length(sz)}] = ind2sub(sz,ind);

In the above function, you can pass as many arguments as you want, same as you would pass to ndgrid. Just the last argument has to be the index (in your case the i^th element, so the index will be i).

For example,

a=my_ndgrid(1:3:10,2:2:6,5:1:8,10); %asking for 10th element

It will be stored as a{1}(10),...,a{3}(10), as you wanted.

You get [4 6 5] as the answer which matches by creating ndgrid manually.

Community
  • 1
  • 1
Autonomous
  • 8,935
  • 1
  • 38
  • 77