Using logical array to extract data without reshape
Mostra commenti meno recenti
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 Commenti
So far you have not told us some very important information: are the lat and lon data gridded?
Judging by your expected output size, they are gridded... but is this really the case? And if so, are they in NDGRID or MESHGRID format?
"Is there easier way to do it?"
If the data are gridded, then of course there are easier ways to do this: simple logical indexing. But how to define those logical indices will depend on if they are in MESHGRID or NDGRID format. Or perhaps they are not gridded at all... we simply do not know, becaue you have not told us.
Amit Kallush
il 11 Mag 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.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!