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!