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

15 ビュー (過去 30 日間)
Kiran Sagar Kollepara
Kiran Sagar Kollepara 2017 年 3 月 30 日
編集済み: KSSV 2017 年 3 月 30 日
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 件のコメント
KSSV
KSSV 2017 年 3 月 30 日
Why you want like that? Are you really going to give long dimensions?
Guillaume
Guillaume 2017 年 3 月 30 日
@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

サインインしてコメントする。

採用された回答

KSSV
KSSV 2017 年 3 月 30 日
編集済み: KSSV 2017 年 3 月 30 日
x = [{1:10} {1:10}] ;
[I{1:numel(x)}] = ndgrid(x{:}) ;
I
  4 件のコメント
Stephen23
Stephen23 2017 年 3 月 30 日
This is bizarre:
x = [{1:10} {1:10}] ;
Why not simply write this?:
x = {1:10,1:10};
KSSV
KSSV 2017 年 3 月 30 日
編集済み: KSSV 2017 年 3 月 30 日
@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.

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 3 月 30 日
編集済み: Stephen23 2017 年 3 月 30 日
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 = cell(size(inp));
>> [out{:}] = ndgrid(inp{:});

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by