1

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?

2
  • Can you give a use case? Quite often in any situation where you think you need to define multiple named variables, in Matlab it's better not to and use large matrices, cell arrays, or structs. Commented Aug 27, 2015 at 9:18
  • the deal function maps the right-hand-side to the left-hand-side. In your example, the right-hand-side has 3 elements, while the left-hand-side has only 1 vector. Your intention is for matlab to map each of the 3 element to 3 variables named 'a' , 'b' and 'c', but this would not work using the deal function. Commented Aug 27, 2015 at 9:19

2 Answers 2

4

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];.

Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.