Problem 6. Select every other element of a vector
조회 수: 2 (최근 30일)
이전 댓글 표시
function x = everyOther(x)
n=length(x)
if mod(x,2)==1
i=1:2:n
expected=[x(i)]
else
i=1:2:n-1
expected=[x(i)]
end
end
This is the code I wrote
Why is this a mistake
댓글 수: 0
답변 (1개)
Matt J
2022년 4월 27일
편집: Matt J
2022년 4월 27일
It's wrong because you have assumed that IF statements on a vector distribute in some way across the elements of the vector. They don't. The implementation can be done in one line,
function x = everyOther(x)
x=x(1:2:end);
end
댓글 수: 3
Matt J
2022년 4월 27일
You are quite welcome, but please Accept-click the answer to indicate that it was what you needed.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!