[a,b]=[1,2] why does not work? How I correct it?

10 次查看(过去 30 天)
[a,b]=size(1) works and ismatrix(size(1))=1 is correct but why [a,b]=[1,2] does not work?

采纳的回答

Stephen23
Stephen23 2015-7-31
编辑:Stephen23 2015-8-10
The documentation for [] clearly describes it as being a concatenation operator, not a list operator as many beginners think it is.
  • The code on the RHS [1,2] concatenates two scalars into one vector (i.e. one variable).
  • The code on the LHS is defined in the link that I gave above as " [A1,A2,A3...] = function assigns function output to multiple variables."
So the answer to your question: because [] have a completely different meaning, depending on where you are using them.
It seems that you are also getting a bit confused about the outputs of size: the outputs change, depending on how many outputs you give it. Although beginners seem to be allergic to reading the documentation, it really is a useful place to learn how things work in MATLAB, and in this case it would have helped you to understand what is going on. Lets have a look:
  • [a,b] = size(1) calls size with two outputs, each of which will be a scalar. As discussed above, it does not define the vector [a,b].
  • ismatrix(size(1)) = 1 in this case size has a different output: nesting functions means size will output one output (not two), and size with one output will always be a vector (see the docs), and calling ismatrix on a vector will always be true. You say that this "is correct", but what do you mean by "correct": ismatrix of a vector will always be true.
  • [a,b] = [1,2] makes no sense because you have defined one single vector (containing two elements), and are trying to allocate one vector to two variables. One thing into two == no go.
If you wish to allocate one object into multiple variables, then use deal:
"|[Y1, Y2, Y3, ...] = deal(X)| copies the single input to all the requested outputs. It is the same as Y1 = X, Y2 = X, Y3 = X, .."
You might like to read about comma separated lists and indexing in MATLAB.

更多回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2015-7-31
d={1 2};
[a,b]=d{:}

Community Treasure Hunt

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

Start Hunting!

Translated by