How to set values to NaN when they AREN'T within the given indices

Hello,
I am attempting to set several values in a large matrix to NaN based on indices that I do not want to have NaN values. I attempted using logicals but matlab doesn't change anything (see photo). In this example, I expect every value but the bottom right to be set equal to NaN. I checked previous posts and this was how it was done in 2014.

Risposte (1)

a=ones(3);
[X,Y]=meshgrid(1:3);
a(~(X==3 & Y==3))=NaN;
which equals
a(X~=3 | Y~=3)=NaN;

4 Commenti

Is there a way to do this for a set of 3d matrices? I have 1000 matrices that are n x m (320x270). Lets say I have several row/colum pairs that I want keep in every single matrix (same x,y indices amongst every matrix). A vector (yind) representing the indices of the rows and a vector (xind) representing the indices of the columns.
n=320;
m=270;
matrix=ones(n,m,1000);
% Made up for example (row & colomn pairs that are not NaN)
xind=156:192; % column indices
yind=[117; 118];% row indices
How can I aschieve a new 3D matrix with the values at the given indices preserved for every matrix from 1 to 1000?
you could also use
newMat=nan(size(matrix));
newMat(yind,xind,:)=matrix(yind,xind,:);
assuming that you want to preserve the values at xind and yind. if you want to preserve all columns with xind and all rows of yind you should use
newMat(yind,:,:)=matrix(yind,:,:);
newMat(:,xind,:)=matrix(:,xind,:);
If there is an original matrix contains different values and you want to keep part of it, you may try the following:
DataKeep = matrix_original(yind(1):yind(end),xind(1):xind(end),:); % Keep the data from the original matrix
[n,m,k] = size(matrix_original); % k should be 1000 in your case
matrix=nan(n,m,k); % Create a new matrix with NaN only
matrix(yind(1):yind(end),xind(1):xind(end),:)=DataKeep; % Put the data you want to keep in the new matrix
@Simon ChanThat solution worked well. Sorry to both of ya for the poor explanation.

Accedi per commentare.

Prodotti

Release

R2020a

Richiesto:

il 17 Lug 2021

Commentato:

il 17 Lug 2021

Community Treasure Hunt

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

Start Hunting!

Translated by