How to set multiple variables at once?
Ältere Kommentare anzeigen
Hi, I wonder if I can set multiple variables at once. As far as I know, I cannot do that and I should set variables like
x = 1; y = 2;
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.
Akzeptierte Antwort
Weitere Antworten (3)
Ruben D. Gonzalez L.
am 1 Sep. 2020
As of Matlab 2019a, the following works for me:
>> [x, y, z] = deal(1, 2, 3)
x =
1
y =
2
z =
3
2 Kommentare
Walter Roberson
am 1 Sep. 2020
This has been possible for a long time. Before 2006.
Personally, I do not feel that using this is of value. It is both longer and less clear than
x = 1; y = 2; z = 3;
There are some useful circumstances for multiple assignment, mostly involving struct expansion or cell expansion. However, a number of years ago, MATLAB was enhanced to not need deal() for that purpose, as demonstrated in https://www.mathworks.com/matlabcentral/answers/414731-how-to-set-multiple-variables-at-once#answer_332664 .
Ruben D. Gonzalez L.
am 20 Sep. 2020
I cannot agree more. Coming from Python, multiple assignment feel more natural to me, and I had just discovered deal() while developing object array interfaces and overriding subsref() and subsasgn() methods.
What I don't understand is why didn't I see your previous response from 2018. Otherwise, I wouldn't have wasted my humble two cents ;-)
Cheers.
Giseon Hong
am 14 Aug. 2018
0 Stimmen
Kategorien
Mehr zu Call Python from MATLAB finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!