How to fill a vector and change its elements when reaching a specific element?

3 ビュー (過去 30 日間)
Maria
Maria 2022 年 11 月 17 日
コメント済み: Maria 2022 年 11 月 17 日
Hi all!
i want to fill a row vector X=1*3600 as x(j+1)=x(j)+20, and elements of X should be 0<=x<=1000.
for example :
x(1)=0
x(2)=20
x(3)=40,
.....
and when arriving x(j)=1000, x(j+1)=x(j)-20 as following :
x(j)=1000
x(j+1)=980
x(j+2)=960,
......
and when coming to "0" , it will start again x(j+1)=x(j)+20. i want to repeat that until arriving at the column 3600.
thanks in advance

採用された回答

Bruno Luong
Bruno Luong 2022 年 11 月 17 日
x = zeros(1, 3600);
x(1) = 0;
dx = 20;
for k=2:length(x)
xk = x(k-1) + dx;
if xk > 1000
dx = -20;
xk = x(k-1) + dx;
elseif xk < 0
dx = 20;
xk = x(k-1) + dx;
end
x(k) = xk;
end
plot(x,'o-')
  3 件のコメント
Bruno Luong
Bruno Luong 2022 年 11 月 17 日
A variant, avoid repeating code
x = zeros(1, 3600);
x(1) = 0;
dx = 20;
k = 1;
while k < length(x)
xk = x(k) + dx;
if xk > 1000
dx = -20;
elseif xk < 0
dx = 20;
else
k = k+1;
x(k) = xk;
end
end
Maria
Maria 2022 年 11 月 17 日
@Bruno Luong okay! thank you so much!

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 11 月 17 日
Try this:
maxx = 1000;
x = zeros(1, 3600);
index = 2;
while x(index-1) < maxx && index < length(x)
x(index) = x(index-1) + 20;
index = index + 1;
end
for k = index : length(x)
x(k) = x(k-1) - 20;
% Quit if x goes negative
if x(k) < 0
break;
end
end
% Show in command window
x
x = 1×3600
0 20 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400 420 440 460 480 500 520 540 560 580
  4 件のコメント
Maria
Maria 2022 年 11 月 17 日
編集済み: Maria 2022 年 11 月 17 日
@Image Analyst it is not a homework, just i'm asking for a simple way to don't repeat the while loop for many times. i posted my question not because i don't know how to write a code with loop but to find an easier manner .
i wrote that elements of x are between 0 and 1000 , i think that you understand that i want to fill all elements of x.
Image Analyst
Image Analyst 2022 年 11 月 17 日
OK, looks like you're going to use Bruno's answer so I won't bother. You can increase your skills by investing 2 hours here:

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

カテゴリ

Help Center および File ExchangeBig Data Processing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by