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

조회 수: 2 (최근 30일)
DJ V
DJ V 2016년 11월 8일
댓글: Image Analyst 2016년 11월 8일
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?

채택된 답변

Thorsten
Thorsten 2016년 11월 8일
편집: Thorsten 2016년 11월 8일
if size(M,1) > 1 & size(M,2) > 1
res = M(2,2);
else
res = [];
end
  댓글 수: 4
DJ V
DJ V 2016년 11월 8일
Thanks but I can't use "if" statements. No tests.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2016년 11월 8일
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, [])

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by