using a while loop to add one to a vector

I am supposed to use a while loop to add one to a vector. when i use this code it goes on for infinity but my bounds are set for when i is less than or equal to the length of the vector.
function [vec] = addOne(vec)
vec = [2 1 5 2]
l = length(vec)
i = 1:l
while i <= l
vec(i) = vec(i)+1
end
addOne = vec;
end

 Akzeptierte Antwort

David Hill
David Hill am 20 Okt. 2022

0 Stimmen

function vec = addOne(vec)
i=1;
while i<=length(vec)
vec(i) = vec(i)+1;
i=i+1;
end
end

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 20 Okt. 2022

Beantwortet:

am 20 Okt. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by