How to solve preallocating speed of a variable?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
snr matlb
el 21 de En. de 2021
Comentada: snr matlb
el 21 de En. de 2021
I have a variable which is object structure, I mean I define all properties in an m.file classfile and properties structure. Then I use them with a variable for example;
classdef obj<handle>
properties
id = zeros;
end
end
Then, I use for example "car" list in the for loop to fill the all properties, the number of properties is 30.
car = [];
for segment=1:5
for brand = 1:6
car(segment,brand).id = list(brand,'id');
..... till 30 properties like above
end
end
It works but the MATLAB gives suggestion to speed the script. The error*;
*The size of the indicated variable or array appears to be changing with each loop iteration. Commonly, this message appears because an array is growing by assignment or concatenation. Growing an array by assignment or concatenation can be expensive. For large arrays, MATLAB must allocate a new block of memory and copy the older array contents to the new array as it makes each assignment.
*Programs that change the size of a variable in this way can spend most of their run time in this inefficient activity. There is also significant overhead in shrinking an array on each iteration or in changing the size of a variable on each iteration. In such cases, MATLAB must reallocate and copy the contents repeatedly.
*For scripts, Code Analyzer cannot determine whether the array was preallocated before the script was called. Depending on your use of scripts, you might want to enable or disable this message independently of the related message (with message ID AGROW) that applies to functions and class methods.
How to make this done, variable has two indices like car(segment,brand).
2 comentarios
Respuesta aceptada
Más respuestas (1)
Steven Lord
el 21 de En. de 2021
You start off with car an empty double array, then change it to a struct array with your first assignment in the loop. Instead I'd start off with car a struct array of the appropriate size. There are at least two ways to do this.
car1 = repmat(struct('id', NaN), [5 6])
This creates a scalar struct with the appropriate field filled with missing data (NaN) and then replicates it.
car2 = struct('id', cell(5, 6))
This takes advantage of an oft overlooked functionality in struct. If you call it and one of the fields is a cell array, struct will return a struct array the size of that cell array with each cell used to create the corresponding element of the struct array.
These two approaches do fill the id field with different data, but if you're just going to overwrite them that should be okay.
id1 = car1(1, 1).id
id2 = car2(1, 1).id
Ver también
Categorías
Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!