# Comparing the entries of matrix in pairs

11 views (last 30 days)

Show older comments

Problem: I have a matrix A (of n by m dimension) which for this example is 10 by 3. Now I want to compare the entries of the matrix which are at unit distance apart like A(1,1) and A(1,2), then A(1,2) and A(1,3), and so on till A(1,m-1) and A(1,m) . I want to do this for each row till 10 in this case. I check if the A(1,m) -th entry is greater than or equal to 1 and if it is I store that index and the value of the matrix.

Example: This is the my matrix A. Now A(1,1) = 0 and A(1,2) = 0. I check A(1,2) is not greater/equal to 1 and hence I skip and go ahead. A(1,2)=0 and A(1,3) = 3 and A(1,3) is greater/equal to 1 and hence I store the row index , pair (2,3) and value of the matrix 3 in an separate array. So my array would show (1,2,3,3).

(row, pair, value)

| | |

1 (2,3) 3

If I now go to second row, A(2,1) = 0 and A(2,2) = 1 (>=) 1 and hence I have in array (2,1,2,1)

(row, pair, value)

| | |

2 (1,2) 1

In the same row, I have A(2,2)=1 and A(2,3) = 2 >= 1 and hence I have in array (2,2,3,2)

(row, pair, value)

| | |

2 (2,3) 2

My attempt:

N = 3;

M = 3;

%making matrix A

a = nchoosek(1:M+N-1,N-1);

s = size(a,1);

b = [zeros(s,1) a (M+N)*ones(s,1)];

A = diff(b,[],2)-1;

D = nchoosek(N+M-1, N);

% making arrays

arr = zeros();

for v=1:D %v is basically running till 10 in this case

for i= 1:M

for j= 2:M

if A(i,j)-A(1,j-1) >=1

arr(v,1) = v;

arr(v,2) = j-1;

arr(v,3) = j;

arr(v,4) = A(v,j);

end

end

end

end

The above code seems to miss several of the values and doesn't seem to work. One thing I tried was using nchoosek to make pairs beforehand and check for those pairs in the matrix A. This didn't pan out. Any help would helpful.

Thank You.

##### 0 Comments

### Accepted Answer

Jonas
on 3 May 2021

i hope i understood you correctly, first index is row index, the pair is the pair of compared column index and the last value is the bigger of the two values if at least one of them is 1 or bigger

data=[0 0 1; 1 8 2; 2 3 3; 3 1 1]

greaterOrEqual=(data(:,2:3)+data(:,1:2))>=1;

[rowIdx,colIdx]=find(greaterOrEqual);

pairsOfColumnIdx=[colIdx colIdx+1];

respectiveBiggerValue=nan(numel(colIdx),1);

for valNr=1:numel(rowIdx)

respectiveBiggerValue(valNr)=data(rowIdx(valNr),colIdx(valNr)+1);

end

[rowIdx pairsOfColumnIdx respectiveBiggerValue]

##### 2 Comments

Jonas
on 3 May 2021

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!