필터 지우기
필터 지우기

Stop for-loop at the second last column

조회 수: 4 (최근 30일)
HYZ
HYZ 2019년 4월 17일
편집: Adam Danz 2019년 4월 17일
E.g. I have a vector a = [1 1 5 1 1 1 10 2]; Error appeared when the loop reached the last column. I am writing to stop at end-1, but kinda lost. Please help solve this. thanks in advance.
function z = findpeaks(a)
for i = 2:[a(:,end-1)]
z = a(a(i)>a(i-1) & a(i)>a(i+1))
end
  댓글 수: 2
Dennis
Dennis 2019년 4월 17일
I think your loop has a creative synthax (not wrong though).
What bothers me is that your loop runs from 2 to the 2nd last value in a, so the amount of iterations depend on your vector entry:
a = [1 1 5 1 1 1 10 2]; %10 iterations
a = [1 1 5 1 1 1 1 2]; %1 iteration
a = [1 1 5 1 1 1 -10 2]; %does nothing
a = [1 1 5 1 1 1 0.5 2]; %does nothing
I am not sure if this is intentional.
Also i recommened to rename your function since findpeaks() is already implemented in matlab.
Maybe you should check the Matlab version out, i guess you want to try something similar:
[peakval,peakloc]=findpeaks(a)
peakval =
5 10
peakloc =
3 7
HYZ
HYZ 2019년 4월 17일
Sorry I didn't explain my problem well. Basically I would like to get values which are larger than the value before and after. That's why I tried to put something like i=2:end-1. The loop has problem when it reached '2' as it has no vlaue after it.

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

채택된 답변

Adam Danz
Adam Danz 2019년 4월 17일
편집: Adam Danz 2019년 4월 17일
Here's how to start at the 2nd column and stop at the second to last column
for i = 2 : size(a,2)-1 %or for i = 2 : length(a)-1 if a is a vector
...
end
Also, matlab already has a function named findpeaks() so you might want to rename your function.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by