How to fill a vector and change its elements when reaching a specific element?
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
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
4 Kommentare
Maria
am 17 Nov. 2022
Image Analyst
am 17 Nov. 2022
You did not say that originally that it should restart once it hit zero. But I'm sure you'll realize (or maybe not) that you just have to add another while and for until you get to the last, 3600th, element of x. Or you could wrap the for and a while in an outer while loop. If you really don't know how to copy the code and append it, let me know.
What's the use case for this anyway? Why not use sawtooth (in the Signal Processing Toolbox) instead? Why do you need to do it? If it's homework, then unfortunately you can't turn in my code as your own or you could get into trouble with your instructor.
Image Analyst
am 17 Nov. 2022
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:
Kategorien
Mehr zu Big Data Processing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
