Assign Multiple Variables

1,401 views (last 30 days)
Zach on 28 Sep 2011
Commented: Brent F on 19 Jun 2021
I have a array for example [1,2,3,4]. I want to assign a variable to each number in the array such that a=1, b=2, c=3, and d=4. I know I can do each one separately but I want to know if it is possible to this in one line.
  1 Comment
Image Analyst
Image Analyst on 29 Sep 2011
Kind of reminded me of the FAQ: though I'm not saying you don't have a valid reason for doing that - you may well have.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 28 Sep 2011
It is not possible in one statement. It is possible in two statements, which you could combine on one line.
t = num2cell([1,2,3,4]);
[a,b,c,d] = deal(t{:});
Daniel Bridges
Daniel Bridges on 25 Jan 2018
Edwin, have you seen Mathematica? From the introductory documentation I've read, it seems Wolfram wants users to code like that from the beginning ...

Sign in to comment.

More Answers (3)

Raziman Thottungal Valapu
It is now possible to do this in one line cleanly
[a,b,c] = deal(1, "test", [1:5])
Gives me
a =
b =
c =
1 2 3 4 5
As expected
  1 Comment
Stephen23 on 1 Oct 2020
@Raziman Thottungal Valapu: no, that is not what the question is about. The question specifies that there is only one input array, but your code uses multiple separate inputs to deal. Not the same thing at all.

Sign in to comment.

Jeff Miller
Jeff Miller on 15 Aug 2018
matsplit does this.
Brent F
Brent F on 19 Jun 2021
Much cleaner than deal(a(1), a(2), a(3), a(4), ...)

Sign in to comment.

Viktor on 1 Sep 2018
Edited: Viktor on 1 Sep 2018
The one-liner I have been using is the following:
[a,b,c,d] = feval(@(x) x{:}, num2cell([1,2,3,4]));
(Don't claim it is my original idea, just felt it belongs to this thread. If it is posted elsewhere feel free to link it.)
Stephen23 on 12 Sep 2018
Edited: Stephen23 on 12 Sep 2018
That is just subsref wrapped up in an anonymous function, which is then called by feval.
Here it is with subsref called directly:
>> [a,b,c,d] = subsref({rand(2), 5, 'hello', pi}, substruct('{}',{':'}))
a =
0.103676 0.814128
0.208758 0.092132
b = 5
c = hello
d = 3.1416

Sign in to comment.


Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!