Correct way of using if-Function

1 view (last 30 days)
Nick Volkmann
Nick Volkmann on 14 Oct 2021
Edited: Benjamin on 14 Oct 2021
Hello,
im using a for loop to iterate through a vector filled with n element from 1-6.
What i want it to do:
Iterate through all element and check for each of them:
IF the value is less than 3, save them in an new vector and add 3
Else just add the number to the new vector
The solution should be: x = [4 5 3 4 5 3 4 5 3 4]
right now this is what i get: x = [4 5 3 1 2 3 1 2 3 1]
Whenever the first if-statement is not current it breaks
clear
v1 = [1 2 3 1 2 3 1 2 3 1];
v2 = [1 2 3 1 2 3 1 2 3 1];
Stop = length(v1)
x = []
for i = 1: length(v1)
if (i < 3)
x(i) = v2(i) + 3
else
x(i) = v2(i)
end
end

Answers (1)

Benjamin
Benjamin on 14 Oct 2021
Edited: Benjamin on 14 Oct 2021
The problem is that you are using the index i instead of v1(i) (or maybe it should be v2(i) - no way to tell) in your comparison "if (i-3)". You want to compare the value, not the index of the value, so it should be "if (v1(i) < 3)".

Community Treasure Hunt

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

Start Hunting!