Reputation: 173
I have an array of 13x14 double. I want to extract few elements which are not in any particular order and make rest of the elements NaN.
eg, if
A = [ 0.2 0.3 0.6 0.4
0.1 0.5 0.2 0.8
0.7 0.1 0.5 0.9
0.2 0.5 0.6 0.7]
I want to extract element having index (2,1), (2,3) (3,3) and (4,2) and make rest as NaN. So the final output should be :
[ NaN NaN NaN NAN
0.1 NaN 0.2 NaN
NaN NaN 0.5 NaN
NaN 0.5 NaN NaN ]
I tried logical indexing but it gives me a vector which I don't want because then you cannot reshape it and make it 2-D array. I want a 2-D array. Thanks.
Upvotes: 0
Views: 118
Reputation: 4311
You can do this by creating a matrix of the same size of A full of NaNs and then use linear indexing to overwrite the NaNs by the values wanted:
A = [ 0.2 0.3 0.6 0.4
0.1 0.5 0.2 0.8
0.7 0.1 0.5 0.9
0.2 0.5 0.6 0.7 ]
%(2,1), (2,3) (3,3) and (4,2) % // reads as...
rows = [2, 2, 3, 4];
cols = [1, 3, 3, 2];
idx = sub2ind(size(A), rows, cols) % // pair of indices as linear indices
out = NaN(size(A)); % // Matrix full of NaN (same size as A)
out(idx) = A(idx); % // Overwriting with values from A at given indices
Upvotes: 2
Reputation: 45752
Preallocate first:
result = NaN(size(A))
result(2,1) = A(2,1)
result(2,3) = A(2,3)
or if you have your subscripts as an n-by-2 matrix then you can use sub2ind
to do it in one shot:
result = NaN(size(A))
subs = [2,1
2,3
3,3
4,2];
ind = sub2ubd(size(A), subs(:,1), subs(:,2));
result(ind) = A(ind)
Upvotes: 0