Suji  Lee
Suji Lee

Reputation: 11

Define multiple variables at the same time in MATLAB

I want to define multiple variables at the same time. For example, I want to define

a = 1
b = 2
c = 3

like this.

So I made a matrix with [a,b,c]:

x = [a, b, c];

y = [1, 2, 3];

x = y

So I want to get the following answer.

a = 1
b = 2
c = 3

If I use

[a, b, c] = deal(1, 2, 3)

then, I can get

a = 1
b = 2
c = 3

But I want to use matrix x instead of [a, b, c]

So if I use,

x = deal(1,2,3)

there is an error.

Is there any solution?

Upvotes: 1

Views: 1157

Answers (2)

IKavanagh
IKavanagh

Reputation: 6187

Maybe I don't understand the question but if you want to use the matrix x instead of [a, b, c] why don't you just define it as

x = [1, 2, 3];

From your question it sounds to me as if you are overcomplicating the problem. You begin by wanting to declare

a = 1;
b = 2;
c = 3;

but what you want instead according to the end of your question is

x = [1, 2, 3];

If you define x as above you can the refer to the individual elements of x like

>> x(1), x(2), x(3)
ans =
     1

ans =
     2

ans =
     3

Now you have the best of both worlds with 1 definition. You can refer to a, b and c using x(1), x(2), x(3) instead and you've only had to define x once with x = [1, 2, 3];.

Upvotes: 4

drhagen
drhagen

Reputation: 9600

You cannot deal into a numeric array, but you can deal into a cell array and then concatenate all the elements in the cell array, like this:

[x{1:3}] = deal(1, 2, 3); % x is a cell array {1, 2, 3}
x = [x{:}]; % x is now a numeric array [1, 2, 3]

Upvotes: 2

Related Questions