Loop in loop only returns results of first iteration

조회 수: 3 (최근 30일)
Paul Costache
Paul Costache 2021년 8월 14일
댓글: Paul Costache 2021년 8월 15일
Hello,
I used these loops to get the volume of particles from multiple fotos. Each iteration for 'f' is a separate foto. The table 'results' gets the properties for each foto and 'results_total' combines the results. The table 'results' also has different number of rows with each iteration.
I wanted to do the same with the second loop, where 'j' gives the number of particles identified in each picture and with Vol(j) I get the volume of each particle. As I did above I wanted to save the results for all fotos in 'Vol_total' but I get the values from the first foto, so f=1 added 2 times. So for example in the first foto there are 141 particles and in the second 111, Vol_total returns a double array 282x1 instead of 252x1.
How can I change the code to get the right results? Thank you!
Vol_total = table;
for f=1:2
% particles in each foto from a folder are being analyzed and some characteristics measured
% to simplify here number of fotos = 2
% code for calculation of results
results = regionprops('table',lm2, 'Area','Perimeter','MinFeretProperties','MaxFeretProperties');
results_total = vertcat(results,results_total);
for j=1:height(results)
Vol(j) = sum(V(lm2==j)); % V is the volume of each pixel and lm2 is the labelmatrix which shows the pixels that belong to the same particle
end
Vol_total = [Vol_total; Vol'];
end

채택된 답변

darova
darova 2021년 8월 14일
Try to preallocate Vol variable before for loop. Vol has size 141 after first iteration, that's why you have 282 elements
Vol = table(size(results));
for j=1:height(results)
Vol(j) = sum(V(lm2==j)); % V is the volume of each pixel and lm2 is the labelmatrix which shows the pixels that belong to the same particle
end
You should sum in two directions volume value. Don't know why don't you have an error in this line
% Vol(j) = sum(V(lm2==j)); % V is the volume of each pixel and lm2 is the labelmatrix which shows the pixels that belong to the same particle
v1 = V(lm2==j);
Vol(j) = sum(v1(:)); % sum all elements
  댓글 수: 1
Paul Costache
Paul Costache 2021년 8월 15일
Vol = double(height(results));
for j=1:height(results)
v1 = V(lm2==j);
Vol(j) = sum(v1);
end
Vol_total = [Vol_total; Vol'];
Thanks for the tip. It worked but I had to leave out the index from v1 as I was getting an error.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Colormaps에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by