iterating array over for loop

4 次查看(过去 30 天)
Drew
Drew 2024-2-24
编辑: DGM 2024-2-24
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?

回答(1 个)

DGM
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)

类别

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