Cross validation: Loop with unbalanced length
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi all,
it might be a simple question but I would like to ask for a neat way how to write a loop for the following problem:
Let's say I have an array A=A(1), A(2).. A(n) and B=B(1), B(2).. B(m). I first want to do some calculations in a way that:
- First iteration: A(1) with B(1), B(2).. B(m)
- Second iteration: A(2) with B(1), B(2).. B(m)
- till: A(n) with B(1), B(2).. B(m)
Explanation of the problem: I have 2 binary images, let us name them A and B. The centroid coordinates were obtained from A and I want to know if it is inside a given area in image B. The number of centroid and area are unbalanced (e.g. 10 centroids, and 6 area). Each centroid can be assigned to a specific polygon and delete those centroids that could not determine within any polygon.
My starting code:
numA = 10;
numB = 5;
for u=1:numA
coordinate = imageA(u).Centroid;
xCentroid = coordinate(:, 2);
yCentroid = coordinate(:, 1);
for v=1:numB
area = imageB(v).PixelList;
xArea = area(:, 2);
yArea = area(:, 1);
% Check if centroid is within area
[in, out] = inpolygon(xCentroid, yCentroid, xArea, yArea);
end
end
1 comentario
Stephen23
el 29 de Abr. de 2017
Editada: Stephen23
el 29 de Abr. de 2017
The simplest solution would be to put all of the "some operations" into a function, and then call it using bsxfun. It would require just one simple line of code:
bsxfun(fun,A(:),B(:).')
After all, repeated code should be put into functions anyway:
Respuestas (2)
Geoff Hayes
el 29 de Abr. de 2017
Kamu - you could try something like
N = 42;
M = 84;
A = randi(255,N,1);
B = randi(255,M,1);
for u=1:N
a = A(u);
for v=1:M
b = B(v);
% do some calculation with a and b
end
end
In the above, the outer loop iterates over each element of A and the inner loop over each element of B which should satisfy your requirements of fixing an element of A and using it with all elements of B.1
1 comentario
Image Analyst
el 29 de Abr. de 2017
I'll bet anything you got imageA(u) from doing this:
imageA = regionprops(labeledImage, 'Centroid');
Am I right? And you want to find out if the centroid is in the shape, like it's an O shape, or outside the shape, like a "C" shape. If you're willing to round the centroid to the nearest pixel, then you can use ismember or intersect(). Untested code:
imageA = regionprops(labeledImage, 'Centroid', 'PixelList);
for k = 1 : length(imageA)
if ~isempty(intersect(imageA(k).Centroid, imageA(k).PixelList, 'rows'))
% Centroid is one of the blob pixels.
else
% Centroid is not one of the blob pixels.
end
end
1 comentario
Ver también
Categorías
Más información sobre Matrices and Arrays 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!