1

Is there any short way to stack d outputs of ndgrid(x1,..,xd) into a d+1-dimensional array without using workarounds like cycles

cgrid=cell(1,d);
[cgrid{:}]=ndgrid(x1, x2, ... , xd);
agrid=zeros([d, size(cgrid{1})]);
for jj=1:d
    agrid(jj,:)=reshape(cgrid{jj},size(agrid(jj,:)));
end

or agrid=reshape(cell2mat(cellfun(@(c) c{:},cgrid)),[d, size(cgrid{1})])?

It seems to me that even simple operations with multidimensional arrays require lots of low-level commands.

1

1 Answer 1

1

You can use cat to do this:

buffer = cell(1, 3);
[buffer{:}] = ndgrid(1:10, 1:10, 1:10);
stacked = cat(length(buffer + 1), buffer{:});

Note that this is not exactly equivalent to the code you posted, since in this version the new index is in the last dimension (so stacked(:, :, :, i) is buffer{i}). You can use shiftdim to shift the dimensions around:

shifted = shiftdim(stacked, ndims(stacked) - 1);

Then squeeze(shifted(i, :, :, :)) is equal to buffer{i}.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! That's what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.