|
"Jan Simon" <matlab.THIS_YEAR@nMINUSsimon.de> wrote in message <hbo2pl$aso$1@fred.mathworks.com>...
> Dear Matt!
>
> > I have an array of structures, P(1)...P(N), where N is a large number.
> > Then I want to remove an element, P(M), where M is between 1 and N. Then I could shift all elements P(K) with K>M down an index but that is kind of a pain.
> > Or I could use linked lists and then just unlink an element. But I would still be left with a huge array.
> > Is there a better way to remove elements and shrink an array without having to shift everything around?
>
> Please explain, what "kind of pain" means. Usually Matlab shifts the data for you and for the array of structures this is not really slow: even the pointers to the structs are shifted, not the contents itself.
>
> Another, faster, idea is using logical indices. Then you do not operate on the whole array P, but just on the subarray P(ActiveIndex) with:
> ActiveIndex = true(1, numel(P));
> Then "deleting" an element is done by:
> ActiveIndex(M) = false.
> No shifting, no re-allocation. And using P(ActiveIndex) e.g. for searching does usually not create a copy of the array, so it is not slower than the method of removing elements from P --- at least for large arrays and with some limitations: if almost all ActiveIndex are false, a refresh of P is helpful:
> P = P(ActiveIndex); ActiveIndex = true(1, numel(P));
>
> Have fun, Jan
Hi Jan, Thanks for excellent answer. Let me make the problem a little more complicated and see how that goes.
You have 10 churches and 100 members. Each member belongs to 1 church.
So the Church structure has the church name, and a list of who belongs to that church and it could have the active index.
Church(1).Name='Trinity'
Church(1).Members=[1 3 4 6];
Church(1).ActiveIndex=1;
Church(2).Name='Quadrinity'
Church(2).Members=[2 3 19 50];
Church(2).ActiveIndex=1;
Church(3).Name='Pentitude'
Church(3).Members=[45 50 55];
Church(3).ActiveIndex=1;
...
and the MyChurch array tells us which Church a certain member belongs to.
MyChurch(1)=1
MyChurch(2)=1
MyChurch(3)=2
Now if Church(2) closes and all its members shift to Church(3),we could update the Church array as suggested above, Church=Church(ActiveIndex). But then all the indices would shift, so the MyChurch array would have to be updated as well? How would that be done. Thanks Matt
|