Can I store multiple outputs of a function into a cell?

I am using the function 'ndgrid' to construct a n-dimensional mesh. But I would like to generalize my programme for n-dimensions.
Is there any way where I could store the outputs of the function into a cell, as the number of outputs depends on the number of dimensions.
Something like :
X{:} = ndgrid(x{:})

4 Comments

by the way, x is a cell array containing all the 1-D meshes for each direction. So, in general,
x{i} = linspace(0,1,Nnodes{i})
It sounds like you should look into the function size. I don't really understand what it is that you want to do, so if you could explain a bit more what the code should do, I can see if I can help you further.
Why you want like that? Are you really going to give long dimensions?
@Rik, KSSV, this is indeed commonly used with ndgrid when you want to generate the cartesian product of an unknown number of vectors:
function p = cartprod(c)
%returns the cartesian products of the vectors contained in cell array v
p = cell(size(c));
[p{:}] = ndgrid(c{:});
p = cell2mat(cellfun(@(x) x(:), p, 'UniformOutput', false));
end

Sign in to comment.

 Accepted Answer

KSSV
KSSV on 30 Mar 2017
Edited: KSSV on 30 Mar 2017
x = [{1:10} {1:10}] ;
[I{1:numel(x)}] = ndgrid(x{:}) ;
I

4 Comments

Your syntax.....works if you make this change:
[X{:}] = ndgrid(x{:})
your first suggestion works. Not, the second one.
This is bizarre:
x = [{1:10} {1:10}] ;
Why not simply write this?:
x = {1:10,1:10};
KSSV
KSSV on 30 Mar 2017
Edited: KSSV on 30 Mar 2017
@Stephen yes..you are right.. @ Kiran..the second one will not work you are right. I executed it in my pc without clearing variables. So it worked.

Sign in to comment.

More Answers (1)

Your syntax was almost correct, you just need to preallocate the output cell array and use square brackets:
>> inp = {1:3,4:5,6:7};
>> out = inp;
>> [out{:}] = ndgrid(inp{:});

Categories

Community Treasure Hunt

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

Start Hunting!