How to form new meshgrid based on output condition of the vectorization of original meshgrid?

3 views (last 30 days)
I apply a function to a meshgrid. If the output of the function f_nml2 is greater than say 20e3 I need to get rid of the value. Easy enough.
[N1,M1,L1]=meshgrid(0:N,0:M,0:L_1);
f_nml2=0.5*c_o*sqrt((N1./L).^2+(M1./W).^2+((2.*L1+1)./(2*H)).^2);
f_nml2=f_nml2(f_nml2<20e3)
However I required a new meshgrid N2,M2,L2 which has the corresponding indexes removed from N1,M1,L1 if the condition f_nml2>20e3 is met.
How to I remove combinations from the original meshgrid N1,M1,L1 which cause f_nml2 to be greater than 20e3?
Many thanks for you help
  10 Comments
Guillaume
Guillaume on 23 Jan 2018
And in fact, keeping N1, M1, L1 together as a Nx3 matrix would also simplify all these equations. e.g.:
NML = [N(:), M(:), L(:)];
epsilon = (NML ~= 0) + 1; %just one line instead of 6!
psi_xyz = sqrt(prod(epsilon, 2)) .* prod(cos((NML .* [1 1 2] + [0 0 1]) .* [a b c]), 2);

Sign in to comment.

Accepted Answer

Matt J
Matt J on 22 Jan 2018
keep=(f_nml2<20e3);
N2=N1(keep);
M2=M1(keep);
L2=L1(keep);
  1 Comment
Henry Way
Henry Way on 23 Jan 2018
Thank you. However I need N2,M2,L2 to remain a 3D matrix, so I would need to do a reshape and fill in the unwanted indices with something that will reduce memory and computational time.

Sign in to comment.

More Answers (2)

Matt J
Matt J on 23 Jan 2018
Edited: Matt J on 23 Jan 2018
You can save about a factor of 6 in memory consumption by converting N1,M1,L1 to integer types
>> M1=cast(M1,'uint8'); N1=cast(N1,'uint16'); L1=cast(L1,'uint8');
Name Size Kilobytes Class Attributes
L1 3727x164x96 57303 uint8
M1 3727x164x96 57303 uint8
N1 3727x164x96 114606 uint16
  2 Comments
Henry Way
Henry Way on 23 Jan 2018
Thank you. However i do not think you can sqrt or cos an uint type. I would have to convert back to double before sqrt and cos, which brings me back to the same memory and performance problem.
Matt J
Matt J on 23 Jan 2018
Edited: Matt J on 23 Jan 2018
Well, you can achieve some savings by converting to 'single', if you can tolerate the reduced precision. That would be a factor of 2 on top of the factor of 2 you save by discarding elements, assuming you now agree that you don't need 3D arrays for N,M,L.

Sign in to comment.


Matt J
Matt J on 23 Jan 2018
None of the computations you've shown in fact require that you use meshgrid at all, assuming you have R2016b or higher. Just define N1, M1, L1 as vectors:
N1=0:N;
M1=(0:M).';
L1=reshape(0:L,1,1,[]);
and all your computations are still valid. Even if you don't have R2016b, you can still achieve the same with bsxfun() albeit more tediously.

Categories

Find more on Linear Algebra 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!