# Comparing Elements of two matrices if loop

4 views (last 30 days)

Show older comments

##### 7 Comments

Cedric Wannaz
on 21 Sep 2017

Edited: Cedric Wannaz
on 21 Sep 2017

By counting, do you mean checking if there was one match?

For a given day you have on row of B, which is a single pair of elevation and azimuth. Then for the same day in A you have 24 pairs. How is it possible that you get twice (or more) the same pair of values from A when pair are given hourly?

### Accepted Answer

OCDER
on 21 Sep 2017

Hi Esther, this is one of many ways to do this.

%Reshape A into 2-columns matrix (called Ar) to avoid having to use nested for loops later

Ar = reshape([A(:, 1:2:end) A(:, 2:2:end)], numel(A)/2, 2);

%R will store value = 1 if conditions are met, value = 0 if conditions fail

R = zeros(size(Ar, 1), 1);

for k = 1:size(Ar, 1)

%if azimuth and elevation in Ar is greater than ANY from B, change R(k) to 1

if any( Ar(k, 1) >= B(:, 1) & Ar(k, 2) >= B(:, 2))

R(k) = 1;

end

end

%Number of times conditions are met per hour (row) for all day (col)

R = reshape(R, size(A, 1), size(A, 2)/2);

R =

0 0

0 0

0 0

0 0

0 0

0 0

0 0

0 0

0 0

0 0

0 0

%Number of times conditions are met per day

Rday = sum(R, 1);

Rday =

0 0

%Number of times conditions are met per year

Ryear = sum(Rday);

Ryear =

0

### More Answers (1)

Cedric Wannaz
on 21 Sep 2017

Edited: Cedric Wannaz
on 21 Sep 2017

Or you can operate in 3D:

A = [-10, 2, -8, 4; ...

-4, 6, -3, 7; ...

2, 5, 3, 6] ;

B = [ 3, 6; ...

-8, 4] ;

dayHasMatch = squeeze(any(all(reshape(A, size(A, 1), 2, []) - permute(B, [3,2,1]) == 0, 2)))

with that you get

dayHasMatch =

2×1 logical array

0

1

which indicates that there was a match on day 2.

PS: and if you have an old version of MATLAB, the expansion must be performed using BSXFUN, and you can use a test of equality directly instead of checking that the difference is null:

dayHasMatch = squeeze(any(all(bsxfun(@eq, reshape(A, size(A, 1), 2, []), permute(B, [3,2,1])), 2)))

##### 0 Comments

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!