MATLAB: How to properly write an if-else-statement such that if the condition is met, then the values in x-vector will be stored in the vector; or else the values in the x-vector will not be deleted?

columndataelseelseiffilterif conditionif elseif statementvaluesvector

Hello,
I am stuck on trying to write what I think should be a simple and easy if-else statement, but I just seem to be having trouble connecting the dots…Lets says I have a column vector,
x = [2300:8:2458]';
and I would like to write an if-statement where each row (or element) in the x-vector will be looked at to see if the value meets these two conditions, for example,
if x >= 1 & x <=2440
"some statement goes here"
if it is true, then I would like to keep those values in the column vector, x, (or maybe create a new vector that contains the values that meet the if-condition). If not, I would like to delete those values from the x-vector, for example something like this,
else
x = [];
end
My guess is that it has something to do with the if-statement returning a logical value and I'm supposed to somehow write a statement that uses that logical value to help determine what values to store and what values to delete, or something like that…Or do I have to write a for loop outside of the if-statement and run it as many times as the length(x)?? I read somewhere that by using a single &, the if-statement looks at each element in the vector…but I'm not entirely sure. Can anyone please help?? I am using 2015a btw. Thanks!

Best Answer

g = (x >= 1) & (x <= 2440); % Logical result of the elements you want to keep
x(~g) = []; % Delete the others (or you could make a new variable y = x(g) )
If you really want to use a loop for some reason, then my advice is to form g inside the loop, and then after the loop use g to delete the elements you don't want with the 2nd line shown above. Trying to delete elements inside the loop itself complicates things because the indexing is constantly changing and each element deletion causes a complete data copy which can seriously slow down that section of code.