How to pop the content of a matrix in a way like pop the content of a cell

31 ビュー (過去 30 日間)
raym
raym 2020 年 6 月 19 日
コメント済み: raym 2020 年 6 月 19 日
We know that the arguments of a function can be placed in a cell and call it like this:
aCell = {arg1,arg2,arg3};
myFunction(aCell{:});
Is there a way to do this for a vector instead?
I tried this way, but it does not work
aVector = [2 3 4 5];
myFun(aVector(:)) % this does not work, the argument is a column vector [2;3;4;5] instead.
Similarly,
aVec = [1 2 3];
aCell = {'d','dew',aVec(:)} % I would expect aCell is {'d','dew',1,2,3}, but it is {'d','dew',[1;2;3]},
Thanks.
  2 件のコメント
KSSV
KSSV 2020 年 6 月 19 日
Try num2cell(aVec)
Stephen23
Stephen23 2020 年 6 月 19 日
編集済み: Stephen23 2020 年 6 月 19 日
There is no way to do this with a numeric array (or a char array, logical array, etc.). The only ways to generate a comma-separated list (the proper name for what you are trying to do) are from a cell array or from a field of a structure:

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

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 6 月 19 日
Madhan's answer already shows how to use num2cell. Following just show how can you avoid the creation of a temporary variable
v = [1 2 3];
myFun(struct('a', num2cell(v)).a)
  3 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 6 月 19 日
Timing will be higher because of the additional overhead of struct creation (num2cell() being equivalent in both cases). However, it is only a concern if the function myFun() is itself has very small execution time (in order of microseconds) or the number of input arguments is in millions. If timing is a primary considerations, then it will be faster to just take input as an array rather than splitting it into an argument list. The point about obfuscation seems valid.
raym
raym 2020 年 6 月 19 日
This is what I really want! Thanks!

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

その他の回答 (2 件)

madhan ravi
madhan ravi 2020 年 6 月 19 日
編集済み: madhan ravi 2020 年 6 月 19 日
aVector = [2 3 4 5];
aVector = num2cell(aVector);
myFun(aVector{:}) % ;)

Walter Roberson
Walter Roberson 2020 年 6 月 19 日
No there is not.
You can num2cell the vector and assign that to a variable and do expansion on that.
There are ways to use auxiliary anonymous functions to do the num2cell for you, and even to do cell expansion on the result, but when you proceed that way, the MATLAB parser will not know that multiple outputs are required and will pull out only the first value.

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by