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!