Set elements in center of matrix into NaN values
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2024-4-7
编辑:Voss
2024-4-7
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 个评论
更多回答(1 个)
Paul
2024-4-6
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!