如何在MATLAB中预分配非数值向量? [英] How can I preallocate a non-numeric vector in MATLAB?
问题描述
我经常发现自己在做这样的事情:
I've often found myself doing something like this:
unprocessedData = fetchData(); % returns a vector of structs or objects
processedData = []; % will be full of structs or objects
for dataIdx = 1 : length(unprocessedData)
processedDatum = process(unprocessedData(dataIdx));
processedData = [processedData; processedDatum];
end
虽然功能强大,但并不是最佳选择-processedData
向量在循环内不断增长.甚至mlint
都警告我,应该考虑预先分配速度.
Which, whilst functional, isn't optimal - the processedData
vector is growing inside the loop. Even mlint
warns me that I should consider preallocating for speed.
数据为int8
的向量,我可以这样做:
Were data a vector of int8
, I could do this:
% preallocate processed data array to prevent growth in loop
processedData = zeros(length(unprocessedData), 1, 'int8');
并修改循环以填充向量槽,而不是串联.
and modify the loop to fill vector slots rather than concatenate.
是否可以预分配矢量,以便随后可以容纳结构或对象?
更新:受 Azim的回答的启发,我只是颠倒了循环顺序.首先处理最后一个元素将在第一次命中时强制整个向量进行预分配,因为调试器确认:
Update: inspired by Azim's answer, I've simply reversed the loop order. Processing the last element first forces preallocation of the entire vector in the first hit, as the debugger confirms:
unprocessedData = fetchData();
% note that processedData isn't declared outside the loop - this breaks
% it if it'll later hold non-numeric data. Instead we exploit matlab's
% odd scope rules which mean that processedData will outlive the loop
% inside which it is first referenced:
for dataIdx = length(unprocessedData) : -1 : 1
processedData(dataIdx) = process(unprocessedData(dataIdx));
end
这要求process()
返回的所有对象都必须具有有效的零参数构造函数,因为MATLAB在第一次使用真实对象对其进行写入时会初始化processedData
.
This requires that any objects returned by process()
have a valid zero-args constructor since MATLAB initialises processedData
on the first write to it with real objects.
mlint
仍然抱怨数组可能增长,但是我认为这是因为它无法识别反向循环迭代...
mlint
still complains about possible array growth, but I think that's because it can't recognise the reversed loop iteration...
推荐答案
由于您知道结构processedData
的字段并且知道其长度,因此一种方法如下:
Since you know the fields of the structure processedData
and you know its length, one way would be the following:
unprocessedData = fetchData();
processedData = struct('field1', [], ...
'field2', []) % create the processed data struct
processedData(length(unprocessedData)) = processedData(1); % create an array with the required length
for dataIdx = 1:length(unprocessedData)
processedData(dataIdx) = process(unprocessedData(dataIdx));
end
这假定process
函数返回的结构与processedData
相同的字段.
This assumes that the process
function returns a struct with the same fields as processedData
.
这篇关于如何在MATLAB中预分配非数值向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!