Write multiple function output in one variable

I'm writing a function ind = myfun(N,k) where i need the coordinates of a single index k. My input is k and the number of elements for every dimension in vector N. The Matlab routine ind2sub would work perfectly for my problem, but it writes every coordinate in an extra variable, so I would have to write [ind1, ind2, ...] = ind2sub(N,k) and then ind = [ind1, ind2, ... ]. My problem is that the number of variables is not fixed, it is an input for my function. Is it possible to write the function output of ind2sub not in several variables but in one vector?

 採用された回答

Voss
Voss 2022 年 11 月 17 日

0 投票

function ind = myfun(N,k)
[temp{1:numel(N)}] = ind2sub(N,k);
ind = [temp{:}];
end

3 件のコメント

the cyclist
the cyclist 2022 年 11 月 18 日
Great solution. I think the output might be more intuitive if you reshape it:
function ind = myfun(N,k)
[temp{1:numel(N)}] = ind2sub(N,k);
ind = reshape([temp{:}],[],numel(N))';
end
StefSter
StefSter 2022 年 11 月 18 日
Thank you very much, that worked perfectly.
Voss
Voss 2022 年 11 月 18 日
Very good point, @the cyclist. Thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2022 年 11 月 17 日

コメント済み:

2022 年 11 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by