Comparing Elements of two matrices if loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Esther Roosenbrand
am 20 Sep. 2017
Kommentiert: OCDER
am 22 Sep. 2017
Hi, I want to compare two matrices one with size m*n and the other 2*k. The second matrix (2*k) indicates values which need to be satisfied by the m*n matrix. Basically, I calculated a value in the second matrix for 360 degrees of a circle. In the first matrix measurements of these values for a circle. In the end I want to know how many times both values, the 360 degrees and the values are met.
7 Kommentare
Cedric
am 21 Sep. 2017
Bearbeitet: Cedric
am 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?
Akzeptierte Antwort
OCDER
am 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
2 Kommentare
Weitere Antworten (1)
Cedric
am 21 Sep. 2017
Bearbeitet: Cedric
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!