Help about foor loops.
조회 수: 2 (최근 30일)
이전 댓글 표시
Hey, i have a small problem with a program i am writing in an mandatory task.
I am suppose to find the maximum value of one elemt minus the other elemt in a row vector, and do this for each element.
so far i have done this:
a = [2 8 9 5 4 9 7 6];
for j = 2:8
c = max(a(j-1) , a(j));
disp = c
end
What i further wish, is to make a new vector consisting of each of these maximums elements. How would i do that?
댓글 수: 0
채택된 답변
Laura Proctor
2011년 10월 19일
You can do this without using a FOR loop - keep it vectorized. I think that the following code achieves the results you're seeking:
c = max(a(1:end-1),a(2:end))
댓글 수: 0
추가 답변 (1개)
Steffen
2011년 11월 1일
The fast fix of your code (without removing the for loop)
c(j) = max(a(j-1) , a(j));
Inside the loop c will always be assigned the result of the last iteration of the loop. If you want to have a vector of the results you have to use indexing for the result vector as well.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!