[Effective Coding] for loop
Show older comments
Dear all,
I wrote a code (see end of post) which first creates a logical matrix in which non-zero values are put. Next I want to look at the data in the matrix and count the number of data 'islands' (subsequent 'ones' should be counted as 1 occurence , i.e. in the logical matrix
TIT2=[1 1 1 0 0 1 0 0 1 1]
should detect 3 'data islands'
For this I wrote the following code, however using the for loops seems to be a very ineffective way of coding this. Would anybody know a more effective way of encoding this?
With Regards, Gyasi
---Code below---
TIT2=(TIT~=0); %create logical matrix
[m,n]=size(TIT2);
for i=1:m
for j=1:n-1
if TIT2(i,j)==1
if TIT2(i,j+1)==1 %if the next value in row ==1 current value =0
TIT2(i,j)=0;
end
end
end
end
Answers (2)
Image Analyst
on 9 Apr 2013
Are your islands (regions) defined on a row by row basis, so that if two islands are adjacent and connected to each other but on different rows, that would be two regions, not one region? If it's one region, you can simply call bwlabel() in the Image Processing Toolbox:
[labeledImage, numberOfRegions] = bwlabel(TIT2);
If you need it on a row by row basis then you need to loop over rows doing that for every row:
TIT = randi(3, 7, 7)-1 % Sample data
TIT2=(TIT~=0) % Create logical matrix
[rows, columns] = size(TIT2)
numberOfRegions = zeros(rows, 1, 'int32'); % Preallocate column vector.
for row = 1 : rows
[labeledRow, numberOfRegions(row)] = bwlabel(TIT2(row, :));
end
% Display result:
numberOfRegions
Results in command window:
TIT2 =
1 1 0 1 1 0 0
1 1 1 1 0 1 1
1 1 1 1 1 0 0
1 1 1 0 1 0 1
1 1 1 0 0 0 1
0 0 1 1 1 0 1
1 1 1 1 1 0 1
numberOfRegions =
2
2
1
3
2
2
2
You could go for a variation of the following (EDITED):
>> TIT2(1) + sum(diff(TIT2) == 1)
ans =
3
PS: I assumed that you were treating your matrix linearly as you provided a 1D example, and this answer is invalid if you are looking for clusters in a 2D array.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!