mask a matrix based on values in two arrays
Show older comments
I am looking for a more effective means of masking a matrix based on values held in two arrays. Ultimately I'm looking to mask off chunks of a surface to alter their values. I have been able to achieve this based on the logic in the following loop, but for my actual model runs, which typically have meshgrid sizes in the millions of elements, and array lengths in the 1000's I feel like there could be a less memory intensive (and read/write intensive) solution.
[x y]=meshgrid(0:1:100,0:1:100);
u=floor(rand(10,1)*100);
v=floor(rand(10,1)*100);
padu=5; padv=5;
for i=1:size(u,1)
if i==1
mask=1*(x>u(i)-padu & x<u(i)+padu & y>v(i)-padv & y<v(i)+padv);
else
maskh=(x>u(i)-padu & x<u(i)+padu & y>v(i)-padv & y<v(i)+padv);
mask(maskh==1)=1;
end
end
surf(x,y,mask)
is there a more effective solution? I've searched but perhaps using the wrong terms, as I don't have an answer.
Thank you.
Accepted Answer
More Answers (1)
Catalytic
on 20 Nov 2022
A=accumarray([u,v],1,[100,100]);
k=ones(2*padu,2*padv);
mask=conv2(A,k,'same');
Categories
Find more on Matrix Indexing 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!