Borrar filtros
Borrar filtros

How to get the sum of numbers below a desired number in sets?

3 visualizaciones (últimos 30 días)
How to get the sum of the numbers in the array which are below -1 in sets.
For example
a=[1 -2 0 .5 -3 -4 5 7 -2 -3 -4];
so here the numbers which are consecutively less than -1 should be added only.
i.e. The answer should be
b=[-2 -7 -10]
PS: Actual data is very big.

Respuesta aceptada

Image Analyst
Image Analyst el 8 de Dic. de 2018
Editada: Image Analyst el 8 de Dic. de 2018
These two lines of code will do it.
a = [1 -2 0 .5 -3 -4 5 7 -2 -3 -4];
props = regionprops(a < -1, a, 'Area', 'MeanIntensity');
output = [props.Area] .* [props.MeanIntensity]
How big are your arrays? This should be pretty speedy for up to tens or hundreds of millions of elements. If you have gigabyte sized arrays, it could take a few minutes. The code requires the Image Processing Toolbox.

Más respuestas (1)

per isakson
per isakson el 8 de Dic. de 2018
Editada: per isakson el 9 de Dic. de 2018
"data is very big" How big is that? Does it fit in the memory?
Test this function
function b = cssm( a )
%{
b = cssm([-2,0,.5,-3,-4,5,7,-2,-3,-4]);
b = cssm([1,-2,0,.5,-3,-4,5,7,-2,-3,-4]);
b = cssm([1,-2,0,.5,-3,-4,5,7,-2,-3,-4,3]);
a = randn(1,1e6);
tic, b = cssm( a ); toc
%}
%%
b = zeros(size(a));
%%
kk = 1;
for jj = find(a<-1,1,'first') : length(a)
if a(jj) < -1
b(kk) = b(kk) + a(jj);
else
if b(kk) ~= 0
kk = kk+1;
end
end
end
if a(end) < -1
b( kk+1 : end ) = [];
else
b( kk : end ) = [];
end
end
Performance comparison with the solution of Image Analyst
The test below indicates that the solution using a for-loop is significantly faster - in this case.
>> a = randn(1,1e6);
>> [ isEQ, et ] = cssm( a )
isEQ =
logical
1
et =
0.0069 1.0598
>> a = randi([-12,12],1,1e6,'int8');
>> [ isEQ, et ] = cssm( a )
isEQ =
logical
1
et =
0.0138 3.5893
where
function [ isEQ, et ] = cssm( a )
tic
b1 = loop( a );
et(1) = toc;
tic
b2 = ia( a );
et(2) = toc;
isEQ = all(abs(b1-b2)<1e-6);
end
function b = loop( a )
%%
b = zeros(size(a));
%%
kk = 1;
for jj = find(a<-1,1,'first') : length(a)
if a(jj) < -1
b(kk) = b(kk) + a(jj);
else
if b(kk) ~= 0
kk = kk+1;
end
end
end
if a(end) < -1
b( kk+1 : end ) = [];
else
b( kk : end ) = [];
end
end
function output = ia( a )
props = regionprops(a < -1, a, 'Area', 'MeanIntensity');
output = [props.Area] .* [props.MeanIntensity];
end
Caveat: It happens that I maketakes.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Productos


Versión

R2013a

Community Treasure Hunt

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

Start Hunting!

Translated by