Info

# How to find elements of two different matrices that meet multiple conditions and store those values in one matrix?

1 view (last 30 days)
shawn on 6 May 2018
Closed: shawn on 13 Jun 2018
I'm trying to use a loop with nested if-elseif-else statements to find which elements of a matrix meet a certain latitude and longitude. At the same time it should also meet the condition that it is within a certain date, which is stored in another matrix. The latitude should be greater than 60 and less than 80, and the longitude should be greater than 120 and less than 140. I want to store all the values that meet these conditions into a new matrix. How do I go about doing this?
Rik on 6 May 2018
Can you give a small example input and desired output? Also, please show the code you already tried. It is often much easier to suggest helpful changes, than to write new code.

Wick on 6 May 2018
Logical indexing is your friend. I don't know what your conditions are so I'm just going to make a few conditional statements below. You can change them as you see fit. I'm not solving your problem, exactly. I'm just showing you how logical indexing works and it certainly doesn't have to be inside of a 'for' loop. In fact, it's much, much faster if it's not.
X = rand(4,3);
Y = rand(4,3);
index1 = X > 0.5 & X < 0.7;
index2 = Y > 0.5 & Y < 0.7;
index3 = X > 0.5 & X < 0.7 & Y > 0.5 & Y < 0.7;
index4 = index1 & index2; % this is exactly the same as index3
index5 = X > 0.5 & Y < 0.2;
X1 = X(index1);
X2 = X(index2);
Y3 = Y(index3);
% etc.