How to write a 'for' loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi Everyone,
I can't seem to understand why this function using a for loop doesn't seem to work.
function y = get_kV(n,t)
for k = 1:(n-1)
y = [t(1) t t(end)];
end
I tried it out:
kV = [0 4];
kV = get_kV(3, kV);
The answer should be kv = [0 0 0 4 4 4]
But it only goes through the iteration once and stops. I've written the exact same code in the Command Window and that works but why doesn't it work when I save it as a .m file?
Thanks for any help or advice. Cheers!
댓글 수: 0
채택된 답변
Walter Roberson
2012년 8월 30일
You are overwriting "y" in every iteration of the loop. Only the final version of "y" is returned to the calling routine.
댓글 수: 2
추가 답변 (1개)
참고 항목
카테고리
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!