MATLAB Answers

A way to extract values based on the value of their neighbor?

2 views (last 30 days)
pm4
pm4 on 21 Nov 2016
Edited: James Tursa on 22 Nov 2016
Hi everyone,
I have a large matrix that looks similar to this:
g = [1 90 0 22;
0 80 0 30;
1 60 0 90;
0 12 1 22;
0 40 1 21;
0 12 0 30]
I'd like to extract the values that have a 1 directly beside them such that I'm left with:
g1 = [1 90 1 60;
1 22 1 21]
I thought about removing all rows that contain more than one zero but that will not work on a large matrix whose dimensions will vary between each other. I also tried to do a nearest neighbor analysis using the euclidean distance following an example that I thought might work but this will not differentiate between where the neighbor is located and in my particular example the only neighbor that matters is the 1 on the left of the value.
I am fairly new to this but if someone can point me in the right direction with this problem I would be very grateful. Thank you.

Answers (2)

James Tursa
James Tursa on 22 Nov 2016
Edited: James Tursa on 22 Nov 2016
This picks off the items with a 1 to the left (in columns 1 or 3) for your 4-column example:
G = [g(:,1:2);g(:,3:4)];
G = G(G(:,1)==1,:);
This could be manipulated into your shown result format, but it is not clear to me what you want to happen if the number of items per column does not match up. Are you always guaranteed that the number of 1's in column 1 is the same as the number of 1's in column 3? Also, could g have more columns than 4? E.g., a more generic version might be this depending on what you really have for g:
G = reshape([g(:,1:2:end),g(:,2:2:end)],[],2);
G = G(G(:,1)==1,:);
In your example, did you really want the 1st column results of g to be in the 1st row of g1? And the next set of column results to be in the next row? etc.

Image Analyst
Image Analyst on 22 Nov 2016
Edited: Image Analyst on 22 Nov 2016
There might be an easier way, but this is what I came up with. It works.
g = [1 90 0 22;
0 80 0 30;
1 60 0 90;
0 12 1 22;
0 40 1 21;
0 12 0 30]
gColVec = reshape(g', [], 1)
indexes = [find(gColVec==1), find(gColVec==1)+1]
indexes = sort(indexes(:))
% Make into 4 columns.
g2 = gColVec(indexes)'
out = reshape(g2, 4, [])'
However there may be certain patterns where it doesn't work, like if the lower right element is 1 or things like that.

Community Treasure Hunt

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

Start Hunting!