Using ndgrid in arbitrary dimensions

Hi,
I have a 3x20 matrix called b. If I use ndgrid like this:
[xx, xy, xz] = ndgrid(b(1,:),b(2,:),b(3,:));
I get 20x20x20 matrices for each parameter xx,xy and xz which is what I want in the case that b has 3 rows. My problem is, I need to generalize this, for example, b might be 4x20 matrix or 5x20 matrix. In these cases I need to write the code like this:
[xx, xy, xz, xa] = ndgrid(b(1,:),b(2,:),b(3,:),b(4,:));
So my question is, how do I generalize this to an arbitrary M dimension, that is, if I have b as a Mx20 matrix, how can I use ndgrid?

Antworten (1)

Sean de Wolski
Sean de Wolski am 13 Aug. 2013
Bearbeitet: Sean de Wolski am 13 Aug. 2013

3 Stimmen

There's a fun exercise in crashing my computer. Don't use a large b ;)
b = magic(3); %example
bc = num2cell(b,1); %cells columnwise
clear bbc; %in case it exists
[bbc{1:numel(bc)}] = ndgrid(bc{:}); %use comma-separated list expansion on both sides
Note, instead of creating four new variables, I create a cell array that contains them. This scales much better!

4 Kommentare

melampyge
melampyge am 13 Aug. 2013
Thanks for the answer but I get the out of memory error automatically, so I couldn't even try :). But from what I can see creating array cells is the way to move forward because I can't use ndgrid in a nested loop I guess.
Sean de Wolski
Sean de Wolski am 13 Aug. 2013
Yes. You will hit memory limitations quickly since these n-nd arrays take a lot of memory!
melampyge
melampyge am 13 Aug. 2013
Actually I want to do it this way. I made my matrix b smaller (after several Matlab and computer crashes) and after that I got an array bcc with 1x15 cells, now I need to create xx, xy, xz 15x15x15 matrices from these cells I guess.
melampyge
melampyge am 13 Aug. 2013
But it seems like I can't seperate them with cell2mat.

Melden Sie sich an, um zu kommentieren.

Produkte

Gefragt:

am 13 Aug. 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by