How to compare matrix elements with their neighbors?

7 vues (au cours des 30 derniers jours)
EB
EB le 24 Nov 2016
Commenté : EB le 25 Nov 2016
Hi, I have a matrix A (50x1). I have to compare each element of matrix A with its two neighbors. The element of the matrices are organized in a circular way and the neighbors definition is as follows: Element "i" has two neighbors: element "i+1" and element "i-1", For instance element 2 has neighbors 1 and 3, element 50 has neighbors 49 and 1, element 1 has neighbors 50 and 2. If the value of element "i" from matrix A is smaller than value of element "i+1" and element "i-1" from matrix A,then I build another matrix B which element "i" is equal to element "i" from A matrix.
Any advice how to write this is very appreciated.

Réponse acceptée

Image Analyst
Image Analyst le 24 Nov 2016
You can use imregionalmin() from the Image Processing Toolbox, but you'll have to pad your array
% Create sample data.
A = uint8(randi(255, 1, 50))
% Pad A and create temporary vector paddedA
% so that we don't alter A (we might need the original A later).
paddedA = [A(end), A, A(1)];
minLocations = imregionalmin(paddedA)
% Create B
B = zeros(1, length(paddedA));
% Assign in the values of A
B(minLocations) = paddedA(minLocations);
% Crop back down.
B = B(2:end-1)
  1 commentaire
EB
EB le 25 Nov 2016
Thank you. Your code is doing exactly what I need.

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 24 Nov 2016
Modifié(e) : Guillaume le 24 Nov 2016
That's extremely easy using simple indexing or, if you want to be a bit more fancy, using circshift
A = randi(20, 50, 1); %demo matrix
%using simple indexing
tocopy = A < [A(2:end); A(1)] & A < [A(end); A(1:end-1)];
%using circshift
tocopy = A < circshift(A, 1) & A < circshift(A, -1);
%now copy the selected values
B = zeros(size(A)); %create B first
B(tocopy) = A(tocopy); %copy

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by