Set elements in center of matrix into NaN values
6 views (last 30 days)
Show older comments
I have different matrices of 288x96 for values changing with time in a for loop. I want certain elements in the center within a radius to be set to NaN for all the different matrices. For simplicity let's say I have A=rand(288,96). The center would be A(145, 49) with a diameter of 13 elements. I know I can manually make them equal to NaN myself like A(145,49)=NaN. However, that is quite time consuming with long lines of code. Is there a workaround?
0 Comments
Accepted Answer
Voss
on 7 Apr 2024
Edited: Voss
on 7 Apr 2024
Something like this, for a single matrix:
A = rand(288,96);
D = 13;
figure
surface(A,'EdgeColor','none')
axis image
[M,N] = size(A);
C = floor([M,N]/2)+1;
[I,J] = ndgrid(1:M,1:N);
idx = (I-C(1)).^2+(J-C(2)).^2<=(D/2)^2;
A(idx) = NaN;
figure
surface(A,'EdgeColor','none')
axis image
Something like this, for all matrices at once:
A1 = rand(288,96);
A2 = rand(288,96);
A3 = rand(288,96);
A4 = rand(288,96);
T = cat(3,A1,A2,A3,A4);
figure
tiledlayout(2,2)
for ii = 1:4
nexttile
surface(T(:,:,ii),'EdgeColor','none')
axis image
end
[M,N,P] = size(T);
C = floor([M,N]/2)+1;
[I,J] = ndgrid(1:M,1:N);
[r,c] = find((I-C(1)).^2+(J-C(2)).^2<=(D/2)^2);
q = repelem((1:P).',numel(r),1);
r = repmat(r,P,1);
c = repmat(c,P,1);
idx = sub2ind([M,N,P],r,c,q);
T(idx) = NaN;
figure
tiledlayout(2,2)
for ii = 1:4
nexttile
surface(T(:,:,ii),'EdgeColor','none')
axis image
end
0 Comments
More Answers (1)
Paul
on 6 Apr 2024
Not sure what diameter means in this context. But, if it can be defined in terms of row and column indices, then maybe something like this using sub2ind
A = rand(10,5);
row = [5 5 5 4 6]; col = [2 3 4 3 3];
A(sub2ind(size(A),row,col)) = NaN
If that really means a rectangular selection, the more simply
A(4:6,2:4) = NaN
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!