elimination of the chosen elements and rearranging the matrix

1 view (last 30 days)
a=[1 2 3 4 5 6 7 8 nan nan nan nan nan];
for i=1:length(a)
b(i)=a(i)+1;
if b(i)< 4
b(i)=[];
elseif b(i)>6
b(i)=[];
end
end
it gives ans:
a =
1 2 3 4 5 6 7 8 NaN NaN NaN NaN NaN
>> b
b =
0 0 4 5 6 0 0 0 NaN NaN NaN NaN NaN
well, i want to eliminate the elements instead of replacing it by zeros as:
4 5 6 nan nan nan nan nan nan nan nan nan nan

Accepted Answer

Guillaume
Guillaume on 10 Jul 2019
Deleting elements of an array while you iterate over elements of an array is never going to work.
In any case, a loop is not needed for what you're doing:
a=[1 2 3 4 5 6 7 8 nan nan nan nan nan];
b = a + 1
b(b < 4 | b > 6) = [];
  1 Comment
Alchemist
Alchemist on 10 Jul 2019
what if the length of 'b' needs to be length of 'a', with remaining elements value as 'nan'

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!