Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I preallocate a non-numeric vector in MATLAB?
    primarykey
    data
    text
    <p>I've often found myself doing something like this:</p> <pre><code>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 </code></pre> <p>Which, whilst functional, isn't optimal - the <code>processedData</code> vector is growing inside the loop. Even <code>mlint</code> warns me that I should consider preallocating for speed.</p> <p>Were data a vector of <code>int8</code>, I could do this:</p> <pre><code>% preallocate processed data array to prevent growth in loop processedData = zeros(length(unprocessedData), 1, 'int8'); </code></pre> <p>and modify the loop to fill vector slots rather than concatenate.</p> <p><strong>is there a way to preallocate a vector so that it can subsequently hold structs or objects?</strong></p> <hr> <p><strong>Update:</strong> inspired by <a href="https://stackoverflow.com/questions/591495/matlab-preallocate-a-non-numeric-vector/591569#591569">Azim's answer</a>, 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:</p> <pre><code>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 </code></pre> <p><strong>This requires that any objects returned by <code>process()</code> have a valid zero-args constructor</strong> since MATLAB initialises <code>processedData</code> on the first write to it with real objects.</p> <p><code>mlint</code> still complains about possible array growth, but I think that's because it can't recognise the reversed loop iteration...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload