I am trying to select all BUT certain index pairs in a multi-dimensional array. i.e. I have a set of paired indices (e.g. [1,2] and [4,5]). I want to set all BUT those indexed pairs to 0.
The closest I have come to this is:
A(setdiff(1:length(A(:,1)),lon),setdiff(1:length(A(1,:)),lat)) = 0;
, where A is the matrix and lon and lat are the index pairs I want to keep. However, that also leaves all the intersecting rows and columns of those pairs.
Any ideas?
Here is some example code:
A = ones([5,5])
A =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
lon = [1];
lat = [4];
A(setdiff(1:length(A(:,1)),lon),setdiff(1:length(A(1,:)),lat)) = 0
A =
1 1 1 1 1
0 0 0 1 0
0 0 0 1 0
0 0 0 1 0
0 0 0 1 0
What I want is:
A =
0 0 0 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
The easiest thing to do is actually the opposite of what you have tried. First you want to start with a matrix of zeros and then only fill in those pairs that you have stored in lat
and lon
. Also because you have paired subscripts, you will want to convert those to a linear index using sub2ind
%// Convert subscripts to a linear index
inds = sub2ind(size(A), lon, lat);
%// Start off with a matrix of zeros
B = zeros(size(A));
%// Fill in the values at the specified lat/lon from A
B(inds) = A(inds);