Set elements in center of matrix into NaN values

33 次查看(过去 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?

采纳的回答

Voss
Voss 2024-4-7,0:38
编辑:Voss 2024-4-7,2:31
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

更多回答(1 个)

Paul
Paul 2024-4-6,23:06
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
A = 10x5
0.9484 0.0105 0.5620 0.9706 0.2287 0.6631 0.5854 0.2387 0.9701 0.6311 0.2513 0.6862 0.8084 0.9329 0.3017 0.9508 0.4300 NaN 0.2184 0.6723 0.3862 NaN NaN NaN 0.7173 0.6273 0.2573 NaN 0.3533 0.6479 0.2821 0.1550 0.6533 0.0905 0.9538 0.4071 0.6005 0.6478 0.1312 0.1005 0.7805 0.6410 0.8942 0.0034 0.3871 0.3880 0.2638 0.7514 0.3010 0.8023
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
If that really means a rectangular selection, the more simply
A(4:6,2:4) = NaN
A = 10x5
0.9484 0.0105 0.5620 0.9706 0.2287 0.6631 0.5854 0.2387 0.9701 0.6311 0.2513 0.6862 0.8084 0.9329 0.3017 0.9508 NaN NaN NaN 0.6723 0.3862 NaN NaN NaN 0.7173 0.6273 NaN NaN NaN 0.6479 0.2821 0.1550 0.6533 0.0905 0.9538 0.4071 0.6005 0.6478 0.1312 0.1005 0.7805 0.6410 0.8942 0.0034 0.3871 0.3880 0.2638 0.7514 0.3010 0.8023
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by