How to get this into a loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mark Loui
am 18 Mär. 2021
Kommentiert: Jan
am 18 Mär. 2021
Hi there i like to ask how can i get this into a for loop
x=rand(1,20)
h1=(x(2,1)-x(1,1));%First interval
h2=(x(3,1)-x(2,1)); %second interval
h3=(x(4,1)-x(4,1));%Third interval
h4=(x(5,1)-x(4,1));
I like the interval to run for another 20 times
i get it as
for i=1:20
h=( x(1,n) -x(1,(n-1)
iter=iter+1
end
Through this method, i can get 20 iterations but the h is remain the same value, can i know why and how can i change it to get the right way
1 Kommentar
Jan
am 18 Mär. 2021
x = rand(1, 20)
h1 = x(2,1) - x(1,1); %First interval
This must fail: x has one row only, than x(2,1) does not exist. Please post some working code.
Akzeptierte Antwort
David Hill
am 18 Mär. 2021
x=rand(1,20);
for k=1:19
h(k)=x(k+1)-x(k);
end
Or without loop
x=rand(1,20);
h=diff(x);
2 Kommentare
David Hill
am 18 Mär. 2021
You do not need a loop to set h=x
x=rand(1,20);
h=x;%h is an array
Weitere Antworten (1)
Jan
am 18 Mär. 2021
Bearbeitet: Jan
am 18 Mär. 2021
Why do you want a loop? It is working without a loop also - guessing that you mean x(1, 2) and not x(2, 1) as in the code in the question:
x = rand(20, 20)
h1 = x(:, 2) - x(:, 1); % First interval
h2 = x(:, 3) - x(:, 2); % second interval
h3 = x(:, 4) - x(:, 4); % Third interval
h4 = x(:, 5) - x(:, 4);
3 Kommentare
Jan
am 18 Mär. 2021
What do you want your "diag function with a loop" to do? The explanation " matrix is depending on the nxn size" is not clear enough yet.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!