Filter löschen
Filter löschen

Adding more values to an array every loop

14 Ansichten (letzte 30 Tage)
Odysseas
Odysseas am 2 Dez. 2023
Kommentiert: Odysseas am 3 Dez. 2023
Im trying to add a new value to y, as the loop progresses, to create an array, in this instance y=[1,3,5,7]. Meanwhile, all I get is the final number of that array, y=7 as a result. I know that this happens because the values are not added one by one but are all added spontaneously, so the seven fits the criteria for the "if" , but I dont have a clue on how to fix this.
Any help or tip would be appreciated, I have been stuck with this for hours and I cant find any solution online...
clear
y=0;
for k=1:2:10;
x=[1:10];
if sum(y.^2)>30
break
end
y=x(k);
end
disp(y)

Akzeptierte Antwort

Matt J
Matt J am 2 Dez. 2023
Bearbeitet: Matt J am 2 Dez. 2023
One possibility,
y=nan(1,100);
s=0;
for k=1:numel(y)
y(k)=2*k-1;
s=s+y(k).^2;
if s>40,
y=y(1:k);
break;
end
end
y
y = 1×4
1 3 5 7
  1 Kommentar
Odysseas
Odysseas am 3 Dez. 2023
Thanks, this will do! I will try to compare it to my attempts to find other possible solutions.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

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!

Translated by