# How to find even positioned numbers in a vector or matrix.

4 views (last 30 days)
DJ V on 8 Nov 2016
Commented: Image Analyst on 8 Nov 2016
Hi, if I have a matrix, say, [1 2 3; 4 5 6] and I want the 2,2 position and all even number positions within it, I can write a line of code that will produce "5" as the answer. for a single row vector [1 2 3 4 5 6] there are no even numbered row and column positions, so nothing should be returned. I can send it a matrix M, and ask for M(2,2:2:end) but that won't work for the single row vector, I get an error, and it should return nothing. How do I do this?
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

Thorsten on 8 Nov 2016
Edited: Thorsten on 8 Nov 2016
if size(M,1) > 1 & size(M,2) > 1
res = M(2,2);
else
res = [];
end
##### 4 CommentsShow 2 older commentsHide 2 older comments
DJ V on 8 Nov 2016
Thanks but I can't use "if" statements. No tests.
Image Analyst on 8 Nov 2016
Huh? Why on earth not??? What a bizarre limitation you're putting on yourself!

Sign in to comment.

### More Answers (1)

Guillaume on 8 Nov 2016
M(2:2:end, 2:2:end)
will work for both vectors and matrices (and of course return empty for vectors).
To extend to any number of dimensions:
dimidx = arrayfun(@(dimsize) 2:2:dimsize, size(M), 'UniformOutput', false);
[dimidx{:}] = ndgrid(dimidx{:});
out = reshape(M(sub2ind(size(M), dimidx{:})), 1, [])
##### 1 CommentShow -1 older commentsHide -1 older comments
DJ V on 8 Nov 2016
Thanks! I

Sign in to comment.

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!