I can I do logical indexing on a column

Hello everyone,
I have a column which is 840 in length. It contains value s from -12 to 12. I need only values < -8 and >8. I need to keep the length 840. I tried the following. but it says " 0x1 empty double column vector".
v = zeros (size (data)); % Pre-allocate!
v=data(data <-8 & data>8)
thank you for helping.
Chane

 Accepted Answer

Birdman
Birdman on 20 Jul 2018
Edited: Birdman on 20 Jul 2018
Is it possible for a value to be smaller than -8 and greater than 8 at the same time? Check your logical operator. You need OR operator instead of AND.
v=data(data <-8 | data>8)
You can not keep the length same. If you want that, fill the other values with a specific value, like zero.

5 Comments

In addition to what birdman said, note that in your case, your preallocation line is not a preallocation and will actually slow your code down as you create a matrix that is immediately destroyed and replaced by another one on the next line.
Preallocation is when you create a matrix and then assign values to it elements by elements using indexing. In your case, the v = data... replace the whole matrix.
Guillaume
Guillaume on 20 Jul 2018
Edited: Guillaume on 20 Jul 2018
If you want that, fill the other values with a specific value, like zero
Considering that the aim is to keep elements whose absolute value is greater than 8, replacing the other elements by 0 might be counterproductive, they're still smaller than 8. Replacing them by +/-Inf or NaN would make more sense.
Birdman and Guillaume, Thank you for your swift replay. the solution works fine.I am working on a time-series data. so I need to keep the values to the month they belong. the remaining months can be zero. but how can fill the zeros?
Well, if you want to replace values less than absolute 8 by 0, then:
v(abs(v) < 8) = 0;
You may want <= instead of <
Birdman and Guillaume, Thank you!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!