[英]In an assignment A(:) = B, the number of elements in A and B must be the same
When trying to run my code, for example例如,当尝试运行我的代码时
for ii= 1:10
output(ii)=rand(3);
end
I get the error我收到错误
In an assignment A(:) = B, the number of elements in A and B must be the same
or或者
In an assignment A(I) = B, the number of elements in B and I must be the same.
What does this error mean?这个错误是什么意思? What is the approach to get rid of it?摆脱它的方法是什么?
This error comes because you are trying to fill a variable chunk with more (or less) values than its size.出现此错误是因为您试图用比其大小更多(或更少)的值来填充变量块。 In other words, you have a statement A(:)=B
on where size(A(:))
is different to size(B)
.换句话说,您有一个语句A(:)=B
,其中size(A(:))
与size(B)
。
In the example in the question, rand(3)
returns a 3x3
matrix, however, output(ii)
is just a single value (even if output
may be bigger, output(ii)
is just a single value of output
), thus the value returned by rand(3)
does not fit inside output
.在问题的示例中, rand(3)
返回一个3x3
矩阵,但是, output(ii)
只是一个值(即使output
可能更大, output(ii)
也只是output
的一个值),因此rand(3)
返回的值不适合output
。
In order to solve this problem, you need to change the the size of the output
variable, so you have space to fit all the result.为了解决这个问题,你需要改变output
变量的大小,这样你就有空间来容纳所有的结果。
There are 2 ways of doing this.有两种方法可以做到这一点。 One of them is by creating a Matrix that fits the return, eg output=zeros(3,3,10)
.其中之一是创建一个适合返回值的矩阵,例如output=zeros(3,3,10)
。
Then we can change the code to然后我们可以把代码改成
for ii= 1:10
output(:,:,ii)=rand(3);
end
Alternatively, you can fill the output
as a cell array .或者,您可以将output
填充为元胞数组。 This is particularly useful when the return of the function changes sizes each time, eg rand(ii);
当函数的返回值每次都改变大小时,这特别有用,例如rand(ii);
In that case, the following would work在这种情况下,以下将起作用
for ii= 1:10
output{ii}=rand(ii);
end
It is probable that unlike in the example in the question, in the real case you do not know the size of what the output returns, thus you do not know which of the two options to use to fix your code.很可能与问题中的示例不同,在实际情况下,您不知道输出返回的大小,因此您不知道使用两个选项中的哪一个来修复您的代码。
On possible way of learning that, is activating debugging help when the code errors, by typing dbstop if error
in your command line.在可能的学习方式中,通过在命令行中键入dbstop if error
在代码错误时激活调试帮助。 This will trigger a debugging stop when MATLAB throws an error, and you can type size(rand(ii))
and size(output(ii))
to see the sizes of both.这将在 MATLAB 抛出错误时触发调试停止,您可以键入size(rand(ii))
和size(output(ii))
以查看两者的大小。
Often, reading the documentation of the function being used also helps, to see if different sizes are possible.通常,阅读正在使用的函数的文档也有帮助,看看是否可以使用不同的大小。
That said, the second option, cell arrays, will always ensure everything will fit.也就是说,第二个选项,单元阵列,将始终确保一切都适合。 However matrices are generally a faster and easier to use in MATLAB, thus you should aim for the matrix based solution if you can.然而,矩阵在 MATLAB 中通常更快更容易使用,因此如果可以,您应该瞄准基于矩阵的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.