Why can't I put the 1x3 matrix into 1x3 variable?
조회 수: 7 (최근 30일)
이전 댓글 표시
Hi, I am trying to read the data and studying it.
By the way, as I know, if I have a 2x1 matrix, it could be put into the variables as 1x2 matrix. Following is the example I saw.
(A is 4x5 matrix)
[m,n] = size(A) %Because size(A) returns 4 5, so m will be 4 and n will be 5.
So, I tried different. I made a matrix called 'buf' which contains 1 2 3. And then, I put it into a variable a, b and c.
buf = [1 2 3]
[a b c] = buf
But, the code doesn't work, expressing the error, which was 'righthandside's number of output is different with the left one.'(mine was Korean version, so I translated it of my own accord.) Anyway, it shows the error. Why?
Thank you.
댓글 수: 0
채택된 답변
Stephen23
2021년 5월 1일
편집: Stephen23
2021년 5월 2일
"Why?"
Because the square brackets have different meanings on the Left Hand Side (LHS) and Right Hand-Side (RHS) of the equals sign. This is explained in the MATLAB documentation:
On the RHS the square brackets are a concatenation operator: with the code [1,2,3] you concatenate three scalar numerics into one 1x3 numeric vector. Note that a numeric vector uses contiguous (virtual) memory, and like all array types contains only elements of the same class (MATLAB does not have a "list" type, the closest is the cell array).
On the LHS the square brackets are used to group separate variables into a comma-separated list. Each item in the comma-separated list refers to a separate array (although they may be contained in the same container array (e.g. a cell array or a structure array)). In the documentation this is called "multiple output argument assignment".
So you are mixing up two different things: the RHS refers to one variable with three elements, the LHS refers to allocating data (of any size) to three variables or to three arrays.
Note that Python's similar looking syntax is actually quite different, because the "list" and "tuple" types are actually container types (i.e. are more similar to cell arrays) and are nothing like numeric contiguous arrays at all: for contiguous numeric arrays you need to use numpy or something similar. And notably you cannot unpack a contiguous numpy array using that syntax either.
댓글 수: 0
추가 답변 (2개)
Matt J
2021년 5월 1일
편집: Matt J
2021년 5월 1일
Because a, b, and c do not exist yet, Matlab can't know what their eventual sizes are supposed to be. Suppose you had done this instead:
buf=[1,2,3,4,5,6,7]
[a,b,c] = buf
Which of the numbers in buf should a, b, c each get? Should the result be
a=[1,2,3],
b=[4,5,6],
c=7
or should it be
a=[1,2]
b=3,
c=[4,5,6,7]
Matlab has no way of knowing what you want.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!