フィルターのクリア

Problem using for loop

2 ビュー (過去 30 日間)
Juan Ruiz Osorio
Juan Ruiz Osorio 2020 年 2 月 10 日
コメント済み: Juan Ruiz Osorio 2020 年 2 月 12 日
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
JESUS DAVID ARIZA ROYETH 2020 年 2 月 10 日
qué quieres hacer específicamente?
what do you want to do specifically?
Juan Ruiz Osorio
Juan Ruiz Osorio 2020 年 2 月 12 日
Estoy tratando de hacer un código para encontrar la cantidad de barras de acero suficientes para cubrir la demanda de acero de un elemento de concreto reforzado. El código combina los tipos de barras que existen y me dice cuántas de cada una son necesarias para lograr el objetivo. Adicionalmente, la combinación de barras se hace solamente con aquellas que están dos posiciones por encima o por debajo. Por ejemplo:
Se tienen barras No.2, No.3,No.4... hasta No.18
Si quiero combinar barras No.4 solo puedo hacerlo con barras No.2,No.3,No.4,No.5 y No.6. El problema está cuando debo combinar las barras No.2 ya que en este caso solo puedo hacerlo con No.2, No.3 y No.4.

サインインしてコメントする。

採用された回答

Stephen23
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 件のコメント
Juan Ruiz Osorio
Juan Ruiz Osorio 2020 年 2 月 12 日
Thanks a lot, that is what I was looking for

サインインしてコメントする。

その他の回答 (1 件)

Akira Agata
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
  1 件のコメント
Juan Ruiz Osorio
Juan Ruiz Osorio 2020 年 2 月 12 日
This is a partial solution to the problem but in that case i won't have the first two iterations and the last two ones. For the first iteration the internal for loop must be:
for k=1:lenght(a)
for kk=k:k+2
end
The second iteration:
for k=1:lenght(a)
for kk=k-1:k+2
end
The same logic applies to the last two iterations

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by