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.