If I have a column lets imagine T=[105;105;105;106;106;106;107;107;107;107] how can I count the number of different elements in T? in this case 105 is 3 times, 106 appears 3 times and 107 is 4 times in T.
This is reimplementing existing functionality in a roundabout way. Will be much slower (and require exponentially more memory) if you have on the order of millions or more numbers. If you just have 10s or 100s, then who cares, it still works.
Ahmet Cecen is correct: this is a very bizarre, indirect, and totally inefficient solution. Ahmet's solution is much better, neater, and faster (for 1000 iterations):
Elapsed time is 1.607303 seconds. % this answer
Elapsed time is 0.489061 seconds. % Ahmet's answer
Lets take a look at this code in detail. The first line usesunique, which is a good start ( although it ignores the other much more useful outputs):
a = unique(T);
Then the weirdness starts:
b = arrayfun(@(x)(x-T),a,'UniformOutput',false);
giving a relatively large cell array of numeric matrices: this is a total waste of memory, asb is going to have an effective size ofnumel(T)*numel(a). Ouch, this could get very large! Usewhos to check the size or variables in memory: for this answer:
>> whos
Name SizeBytesClass
T 10x180double
a 3x124double
b 3x1420cell<- ouch!
c 3x124double
While it might not cause a problem for small input vectors, this will be a total waste of memory for larger inputs, as it will expand quite quickly.
At this point the numeric matrices have value zero replacing the values of interest.
This is then followed by a slowcellfun call on this large intermediate variableb:
c = cell2mat(cellfun(@(x)(numel(find(x==0))),b,'UniformOutput',false));
which checks where the zeros are in the numeric matrices insideb. Even here things are indirect:
numel(find(x==0))
should really be
nnz(x==0)
which would be much faster and simpler. But then, as Ahmet correctly pointed out, the concept is very indirect anyway: why not simply sum the indices in the firstarrayfun anyway? Why bother converting the points of interest to zero, storing them in a huge matrix, and then checking counting those zeros by usingfind ?
Here is perhaps what the author really intended to write:
z = arrayfun(@(x)nnz(x==T),unique(T));
which takes half the time than the authors answer (although still not as fast as Ahmet's), and simply counts how many values of T match each unique value using onearrayfun call.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
0 件のコメント
サインインしてコメントする。