Performance improvement array of class instances

7 visualizaciones (últimos 30 días)
Niklas Braun
Niklas Braun el 3 de Feb. de 2021
Respondida: Niklas Braun el 6 de Feb. de 2021
Hey there,
i have created a class called Test:
classdef test
properties
a
b
var1
var2
ID
end
methods
function obj = test(a,b,var1,var2)
obj.a = a;
obj.b = b;
obj.var1 = var1;
obj.var2 = var2;
end
end
end
Multiple Instances of this class are stored in a vector:
test1 = test(1,2,3,4);
test2 = test(1,3,5,7);
test3 = test(2,4,6,8);
all_tests = [test1,test2,test3];
I want to search for the test instance in all_tests, which has the a value of 1 and (of those remaining) the lowest possible b value.
This test instance is then used for further calculation and creation of additional test instances, which will be added to all_tests.
After that, this instance shall be deleted from all_tests.
I am currently using a probably very complicated method to accomplish all this:
% Search for instance with lowest possible b, while a==1
[curr_min, curr_min_index] = min([all_tests([all_tests().a]==1).b]); % finding the Minimum in a subset of all_tests
IDs = [all_tests([all_tests().a]==1).ID]; % I have used a unique ID, to find the index of the minimum in all_tests
currID = IDs(curr_min_index); %finding the ID of the Minimum
current_test = all_tests([all_tests().ID]==currID); %returns my desired test instance
% Next, i use this instance for calculations and create a new test instance
temp = test(current_test.var1,current_test.var2,1,2);
%This new instance is then added to all_tests:
all_tests(end+1,1)=temp;
%The old instance gets deleted from all_tests:
all_tests([all_tests().ID]==currID)=[];
It all works, but it is really slow.
I am pretty sure, there is a better way to do, what i tried to do.
Thank you

Respuesta aceptada

Niklas Braun
Niklas Braun el 6 de Feb. de 2021
I solved my slow Minimum index search with this:
curr_min_index = find([test.b]==min([test([test().a]==1).b]) & [test.a]==1, 1, 'first');

Más respuestas (1)

Steven Lord
Steven Lord el 3 de Feb. de 2021
I would probably create a method of the class that accepts an array of instances of the class and does the extraction / deletion. See the remove method of the attached class for a basic example.
test1 = test735052(1,2,3,4);
test2 = test735052(1,3,5,7);
test3 = test735052(2,4,6,8);
all_tests = [test1,test2,test3]
all_tests2 = remove(all_tests, 20)
  1 comentario
Niklas Braun
Niklas Braun el 4 de Feb. de 2021
Thank you very much for your input. Do you have any suggestions on how I could optimize the minimum index search? 4 Lines of code and the Introduction of IDs feels rather complicated.

Iniciar sesión para comentar.

Categorías

Más información sobre Testing Frameworks en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by