Shortening if/elseif loop for value segregation
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Amere
el 3 de Feb. de 2022
Comentada: Amere
el 3 de Feb. de 2022
I'm constructing a script that involves locating the centroid of circles and adding their area to matrix that contains the cumulative area of cirlces in 50 pixel intervals (x-direction).
The if loop that I have written works fine but is incredibly long and not easily altered without going through each line. I know that there's a more efficient and easily altered method of doing what I want. Could someone please help me?
Please note that cumulativeData(i,5) is the x-coordinate of the circles centroid and cumulativeData(i,2) is the area of circles.
nRows=size(cumulativeData,1);
cumulativeArea=zeros(25,1);
for i=1:nRows
if (0<cumulativeData(i,5))&&(cumulativeData(i,5)<50)
cumulativeArea(1,1)=cumulativeArea(1,1)+cumulativeData(i,2);
elseif (50<cumulativeData(i,5))&&(cumulativeData(i,5)<100)
cumulativeArea(2,1)=cumulativeArea(2,1)+cumulativeData(i,2);
elseif (100<cumulativeData(i,5))&&(cumulativeData(i,5)<150)
cumulativeArea(3,1)=cumulativeArea(3,1)+cumulativeData(i,2);
elseif (150<cumulativeData(i,5))&&(cumulativeData(i,5)<200)
cumulativeArea(4,1)=cumulativeArea(4,1)+cumulativeData(i,2);
elseif (200<cumulativeData(i,5))&&(cumulativeData(i,5)<250)
cumulativeArea(5,1)=cumulativeArea(5,1)+cumulativeData(i,2);
etc...
0 comentarios
Respuesta aceptada
Stephen23
el 3 de Feb. de 2022
Editada: Stephen23
el 3 de Feb. de 2022
What you are doing can be broken into two parts: the first part is generally known as data binning. You can do data binning quite simply and very efficiently using the HISTCOUNTS command:
Basically you need to feed it a vector of the bin edges (e.g. [0,50,100,...]) and the data that you want to place into those bins. HISTCOUNTS replaces all of your FOR loop and IFs.
Then for the second part you want to sum all of the data together that are within in one bin. There are several approaches you could try, but I would start by using HISTCOUNTS third output argument (the indices) and supply that to ACCUMARRAY, which will give you the sum of the bins.
Lets try it on some fake data, where M is your matrix of data:
M = 200*rand(10,5)
V = 0:50:200; % vector of bin edges
[N,~,X] = histcounts(M(:,5),V);
S = accumarray(X,M(:,2),[],@sum) % sum of each bin
Más respuestas (0)
Ver también
Categorías
Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!