Como incrementar un vector cada n filas

2 ビュー (過去 30 日間)
Isabel Aldana Benavides
Isabel Aldana Benavides 2020 年 4 月 20 日
Hola,
Tengo este script
x = zeros(10,1);
a = 1;
for k = 1:2:21;
if mod(a,4)==0;
x(a)= k+4;
else
x(a)= k+2;
end
a=a+1;
end
y obtengo esto:
3
5
7
11
11
13
15
19
19
21
23
y yo quiero obtener
3
5
7
11
13
15
19
21
23
es decir, sin que se me repita el 11 y 19.
Gracias

採用された回答

Geoff Hayes
Geoff Hayes 2020 年 4 月 20 日
Isabel - why
if mod(a,4)==0; % <----- a
instead of
if mod(k,4)==0; % <----- k
? And so your code would be
x = zeros(11,1); % <------ 11
a = 1;
for k = 1:2:21;
if mod(k,4)==0; % <------ k
x(a)= k+4;
else
x(a)= k+2;
end
a=a+1;
end
with result
3
5
7
9 % <----- 9
11
13
15
17 % <------ 17
19
21
23
Note that k = 1:2:21 means that k is always odd: k = 1, 3,5,7,9,11,13,15,17,19,21 and so the condition mod(k,4)==0; will NEVER be true. Is this what you expect?
  4 件のコメント
Geoff Hayes
Geoff Hayes 2020 年 4 月 20 日
x = zeros(10,1);
a = 1;
for k = 1:10
if k == 1
x(k) = k + 2;
else
if mod(a,4) == 0;
x(k)= x(k-1) + 4;
a = a + 1; % <----- since skipping, add extra 1 to a
else
x(k)= x(k-1) + 2;
end
end
a=a+1;
end
with results
x =
3
5
7
11
13
15
19
21
23
27
Isabel Aldana Benavides
Isabel Aldana Benavides 2020 年 4 月 20 日
me salvaste la vida literal, mil gracias, soy algo nueva en esto

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by