iterating array over for loop
조회 수: 4 (최근 30일)
이전 댓글 표시
Tempxy = [0:0.125:2;10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30];
lengthX = length(Tempxy);
for x = 2:lengthX-1
TempUpdated = (Tempxy(2,x+1)+Tempxy(2,x-1))./2;
break
end
Hello, I am using the above for loop to try and take an average of each value from array elements 2:16 for array Tempxy. I have stored the output in a variable called TempUpdated, I expected this variable to return output such as
TempUpdated =
10 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 30
because I am under the impression the above code will iterate over the 2nd row of Tempxy, take the first and 3rd column elements, average them, and then continue repeating this process till it reaches the 16th column element (The second to last).
Instead I am getting an output of
TempUpdated =
5
which seems to me like the function is only operating on the 2nd value and not repeating to fill in the rest of the values. I have already made sure Tempxy is stored as a 2x17 (I saw some issues concerning iterating column vectors). Could anyone help me understand why this loop isn't looping?
댓글 수: 0
답변 (1개)
DGM
2024년 2월 24일
편집: DGM
2024년 2월 24일
Two things.
1: you're breaking out of the loop immediately by using the break keyword.
2: you're not addressing the output as a vector, so TempUpdated is just a scalar that's overwritten repeatedly.
The loop isn't necessary, but whatever it is that you're trying to do isn't what the math gives.
Tempxy = [0:0.125:2;10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30];
% this does the same thing as your code
TempUpdated = (Tempxy(2,3:end) + Tempxy(2,1:end-2))./2
% maybe?
TempUpdated = [Tempxy(2,1) (Tempxy(2,3:end) + Tempxy(2,1:end-2))./2 Tempxy(2,end)]
% or maybe?
TempUpdated = movmean(Tempxy(2,[1:end end]),2)
댓글 수: 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!