Problem using for loop
1 次查看(过去 30 天)
显示 更早的评论
Hi, I need to do something like this:
a=[1 2 3 4 5 6 7 8 9 10];
for i=1:lenght(a)
for ii=i-2:i+2
x=a(ii);
end
end
I found a solution doing something like this:
a=[1 2 3 4 5 6 7 8 9 10];
for i=1:lenght(a)
if i==1
elseif i==2
elseif i=>3&&i<length(a)-2
elseif i==9
elseif i==10
end
end
I need to do the iteration only in the range +- 2 of i.The problem is that a(-1) ,a(0),a(11) and a(12) doesn't exist . . Is there any simple way to solve that problem without using the if conditions?
2 个评论
JESUS DAVID ARIZA ROYETH
2020-2-10
qué quieres hacer específicamente?
what do you want to do specifically?
采纳的回答
Stephen23
2020-2-12
a = 1:10;
n = numel(a);
for kk = 1:n
for ii = max(1,kk-2):min(n,kk+2)
x = a(ii);
end
end
更多回答(1 个)
Akira Agata
2020-2-10
How about limiting the loop from 3 to length(a)-2, like the following?
Also, if your calculation process in the inner loop can be re-written without using for-loop, I would strongly recommend doing so.
for k = 3:lenght(a)-2
for kk = k-2:k+2
% Your calculation process
end
end
另请参阅
类别
在 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!