How to set multiple values at the same time from a vector?

There is a vector v = [1,2,3], and I want to set a=1, b=2, c=3 in a compact form. I tried [a,b,c] = deal(v), but it is not working, because the result is a = [1,2,3]. deal(1,2,3) is ok, but I dont know how to make 1,2,3 from [1,2,3]. In Maple od(v) makes this. Is there any solution for this in MATLAB?

 採用された回答

Manoj
Manoj 2014 年 11 月 14 日

0 投票

This is one way I could think of , but maybe there is an easier way
v=[1,2,3];
vv=num2cell(v);
[a,b,c]=deal(vv{:});

7 件のコメント

Guillaume
Guillaume 2014 年 11 月 14 日
You actually don't need the deal in this case:
[a,b,c] = vv{:};
Mr M.
Mr M. 2014 年 11 月 14 日
I hope there is a fast solution without cell array, which is often used to deal with mixed type of data (usually strings).
Guillaume
Guillaume 2014 年 11 月 14 日
Cell arrays are used for all sort of things. One of its use is conversion to comma separated lists as shown here and as used by varargout and varargin
I'm not sure why you're talking about fast. The operation is instantaneous.
Answer to the question mistakenly asked in another answer: It is not possible to write it into one line somehow? num2cell(v){:}
No that is not possible. You can't index into the return value of a function in matlab. You always have to store that return value in a variable. There is no way around that.
Mr M.
Mr M. 2014 年 11 月 14 日
The getfield function is a solution, isn't it?
Guillaume
Guillaume 2014 年 11 月 14 日
I don't see what getfield has got to do with the subject at hand.
Mr M.
Mr M. 2014 年 11 月 27 日
OK, thanks: [a,b,c]=deal(vv{:}); is a solution. But what if I don't know the number of parameters? For example the maximum is three (a,b,c) but v maybe contains only two, and I want to set c to a default value in this case. How to solve this problem?
Guillaume
Guillaume 2014 年 11 月 28 日
As I said, you don't need the deal,
[a,b,c] = vv{:};
works just as well.
As for your other question, please start a new question so that whoever answers it can get the credits for it.

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

2014 年 11 月 14 日

コメント済み:

2014 年 11 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by