How to set multiple variables at once?

I tried [x y] = [1 2]; as I use [x y] when I get multiple variables from function output, but it didn't work.

Is there any way to do this at once? I need this technique because I have many variables to set.

And I have one more question. What should I do if I want a variable change automatically when other variable changes?

for example, x=1;y=2;A=[x y];x=3; but matrix A does not change, it is still [1 2]; The questions seem quite fundamental but it would be a great help if I get the answer. Thank you.
0 Comments

Accepted Answer

Stephen23 on 14 Aug 2018

Direct link to this answer

Cancel Copy to Clipboard

Direct link to this answer

Cancel Copy to Clipboard Edited: Stephen23 on 14 Aug 2018 "I wonder if I can set multiple variables at once"

Not in the way that you are trying to do, because MATLAB is not Python (or whatever language you got that syntax from). It is much more efficient use of MATLAB to put values into arrays, and not to play around with variables like that. You could use a comma-separated list :

"I need this technique because I have many variables to set."

Then you should put them into one numeric array, or one cell array, or one structure, or one table. Magically assigning lots of values to variable names will force you into writing slow, complex, buggy MATLAB code. Read this to know why:

"What should I do if I want a variable change automatically when other variable changes?"

You can't, not like how you show: in MATLAB the value itself is assigned, not a handle or a reference to a value like in Python. If you want to learn how to use MATLAB effectively, then do not try to write code as if it was Python/yourFavoriteLanguage. In particular, forget about putting all of your data into lots of separate variables and learn to use arrays properly . Only then will MATLAB make any sense, and only then will you start to write efficient MATLAB code.