Indexing (querying) the ndgrid output without actually building it
I believe you are looking for a 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 that dimensional hypertom. k^n
...
PS,
Better not to use i
as variable name in Matlab .
source to share
I got it over with, so I am posting a complete answer. Write the following function in 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 like, just like you go to ndgrid
. It's just that the last argument should be the index (in your case the element i^th
, 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 saved a{1}(10),...,a{3}(10)
as you like.
You get [4 6 5]
as answer that matches ndgrid
by manually creating .
source to share