Matlab:如何实现动态向量
我指的是这样的例子 我有一个函数来分析向量“输入”的元素。如果这些元素具有特殊属性,我会将它们的值存储在向量“输出”中。 问题是,一开始我不知道它需要存储在“输出”中的元素数量,所以我不知道它的大小。 我有一个循环,在里面我绕过向量,通过索引“输入”。当我考虑特殊时,该向量的某些元素捕获“输入”的值,并通过如下句子将其存储在向量“输出”中:
For i=1:N %Where N denotes the number of elements of 'input'
...
output(j) = input(i);
...
end
问题是,如果我之前不“声明”,我会收到错误输出'。我不喜欢在到达循环之前“声明”“输出”,因为输出=输入,因为它存储我不感兴趣的输入值,我应该想一些方法来删除我存储的所有不感兴趣的值与我相关。 有人向我解释这个问题吗? 谢谢。
I am refering to an example like this
I have a function to analize the elements of a vector, 'input'. If these elements have a special property I store their values in a vector, 'output'.
The problem is that at the begging I don´t know the number of elements it will need to store in 'output'so I don´t know its size.
I have a loop, inside I go around the vector, 'input' through an index. When I consider special some element of this vector capture the values of 'input' and It be stored in a vector 'ouput' through a sentence like this:
For i=1:N %Where N denotes the number of elements of 'input'
...
output(j) = input(i);
...
end
The problem is that I get an Error if I don´t previously "declare" 'output'. I don´t like to "declare" 'output' before reach the loop as output = input, because it store values from input in which I am not interested and I should think some way to remove all values I stored it that don´t are relevant to me.
Does anyone illuminate me about this issue?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
for循环中的逻辑有多复杂?
如果很简单,这样的事情会起作用:
或者,如果逻辑很复杂并且您正在处理大向量,我会预先分配一个向量来存储是否保存元素。这是一些示例代码:
How complicated is the logic in the for loop?
If it's simple, something like this would work:
Alternatively, if the logic is complicated and you're dealing with big vectors, I would preallocate a vector that stores whether to save an element or not. Here is some example code:
简单的解决方案是:
虽然我不知道这是否具有良好的性能
The trivial solution is:
Though I don't know if this has good performance or not
如果
N
不是太大而导致内存问题,您可以将output
预先分配给与input
大小相同的向量>,并在循环结束时删除所有无用的元素。有两种选择:
如果
output
被分配了N
的大小,或者如果您不知道的大小上限,那么
,您可以执行以下操作output
会太大输出最后,如果 N 很小,则完全可以调用
注意,如果 N 变大(例如 >1000),性能会急剧下降。
If
N
is not too big so that it would cause you memory problems, you can pre-assignoutput
to a vector of the same size asinput
, and remove all useless elements at the end of the loop.There are two alternatives
If
output
would be too big if it was assigned the size ofN
, or if you didn't know the upper limit of the size ofoutput
, you can do the followingFinally, if N is small, it is perfectly fine to call
Note that performance degrades dramatically if N becomes large (say >1000).