how can I count up the number from a specific interval?
27 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
HI,I am pretty new with Mablab and I need some help.
I have created a vector d with a random function and I need to count up the number of instances where di> 8.
How can I do it?
0 Kommentare
Antworten (3)
Nadir Altinbas
am 25 Okt. 2019
hello for instance interval 8 < x > 999
x = 8 : 0.5: 999;
it increases as 0.5 up to 999 example
ok
-nadir altinbas
0 Kommentare
Steven Lord
am 25 Okt. 2019
Generate a logical mask that is true where your data is in your specific interval and false where it is not.
x = 0:10
mask = x > 8
Count the number of nonzero (non-false) values in your mask using the nnz function.
nnz(mask) % 2, corresponding to x = 9 and x = 10
You can use the logical indexing technique shown by ME if you need to extract the elements of x that are in your interval. But if you're just trying to count them, that's extra work you don't have to do.
elementsGreaterThan8 = x(mask)
3 Kommentare
Steven Lord
am 25 Okt. 2019
Try this benchmarking script (with local functions) comparing your approach and mine. You should define a value n before running it. If you don't it'll start off at 0. I increase n after each run so we get different random numbers each run, to simulate a more realistic real-world application.
For sufficiently large vector sizes, I'm seeing MEsol take about 10 times as long as SLsol (they each return the same count.) Extracting about half the elements in the x vector into a temporary array simply to count how many elements it has with numel requires memory copying which slows down MEsol. For small enough vector sizes the time to perform that extra memory copying seems negligible but for larger sizes it can make a difference.
if ~exist('n', 'var')
n = 0;
end
disp("Seed " + n + " for Mersenne Twister")
rng(n, 'twister');
x = randn(1, 1e7);
M = timeit(@() MEsol(x));
disp("Time for MEsol: " + M)
countME = MEsol(x);
S = timeit(@() SLsol(x));
disp("Time for SLsol: " + S)
countSL = SLsol(x);
disp("" + newline)
disp("MESol returned " + countME + newline + ...
"SLSol returned " + countSL + newline);
n = n + 1;
function n = MEsol(x)
n = numel(x(x > 0));
end
function n = SLsol(x)
mask = x > 0;
n = nnz(mask);
end
ME
am 26 Okt. 2019
Bearbeitet: ME
am 26 Okt. 2019
I agreed that your approach was faster! Yes, for the 100 elements I used (i.e. a small example) the time difference was small. I thought it went without saying that this difference would scale up as the number of elements increased but it’s great to get a better handle on these differences.
Siehe auch
Kategorien
Mehr zu NaNs finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!