Using logical array to extract data without reshape
10 views (last 30 days)
Show older comments
Hi all,
I managed to solve the problem, but the solution seemed so unelegant that I'm sure there is a better way.
I have a 3500X7000 matrix called "Values" I also have two other matrices named "lats" and "lons" that are the same size and contain the longitude and latitude values corresponding to each cell in "Values."
Now I want the lon and lat limits of the data to be:
lat_min = 33.97757;
lat_max = 34.22959;
lon_min = -106.9664;
lon_max = -106.6382;
And I used the following to create logical matrices that contain one only in the cells that are within range:
lat_mask = (lats >= lat_min) & (lats <= lat_max);
lon_mask = (lons >= lon_min) & (lons <= lon_max);
mask = lat_mask & lon_mask;
Here I got stuck. I wanted to extract the data from "Values" using the mask array, but I couldn't do it while preserving the mask array shape (which should be 25X33). I had to look for the row and columns within "mask" sum them and look for the sum value and then reshape it, and the whole thing looks very unelegant:
rowind = (find(sum(mask),1,'first'));
colind = (find(sum(mask,2),1,'first'));
r = sum(mask); c = sum(mask,2);
rr = r(rowind); cc = c(colind);
R = reshape(Values(mask), rr, cc);
Is there easier way to do it?
I wanted to attach the lons lats and Values, but unfortunately, they are too large.
Thanks!
Amit
3 Comments
Stephen23
on 11 May 2023
Edited: Stephen23
on 11 May 2023
"I mentioned in the original post that the lons and lats are in the same size of Values, meaning that they are also gridded."
Yes you wrote that they are the same size, but that does NOT mean that they are gridded: you are confusing the size of an array with the arrangement of data within that array. Not the same thing at all.
For example, here are some lat and lon arrays that are not gridded:
lat = rand(3,5)
lon = rand(3,5)
Do those arrays have some particular size? Of course. Are they gridded? No.
"The lons and lats are in MESHGRID format."
Thank you, that is the statement we needed.
Accepted Answer
Stephen23
on 11 May 2023
Edited: Stephen23
on 11 May 2023
Note that saving those huge lats&lons matrices is rather waste of space: you actually only need the first row/column.
"Is there easier way to do it?"
Yes, you are overthinking this:
latV = lats(:,1);
lonV = lons(1,:);
assert(all(diff(latV)),'not MESHGRID format')
assert(all(diff(lonV)),'not MESHGRID format')
lat_mask = (latV >= lat_min) & (latV <= lat_max);
lon_mask = (lonV >= lon_min) & (lonV <= lon_max);
R = Values(lat_mask,lon_mask)
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!