Performance improvement array of class instances
조회 수: 5 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
추가 답변 (1개)
Steven Lord
2021년 2월 3일
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Testing Frameworks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!