Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector-based elimination zeros from Matrix

I have a matrix like

frequencyarray =

    697    697    697    697    697    697      0      0    697
      0      0      0      0      0      0    770    770      0
      0      0      0      0      0      0      0      0      0
      0      0      0      0      0      0      0      0      0
   1209   1209   1209   1209   1209   1209   1209   1209   1209
      0      0      0      0      0      0      0      0      0
      0      0      0      0      0      0      0      0      0

I'd now like to eliminate all the zeros on a vector base from it and get this

frequencyarray2 =

    697    697    697    697    697    697    770    770    697
   1209   1209   1209   1209   1209   1209   1209   1209   1209

I only want to do this if exactly two non-zero numbers are in a vector. If a vector has more or less than two non-zero numbers, they should be replaced with zeros.

Therefore, if I have something like:

frequencyarray =

      0      0    697    697
      0      0    770    770
      0      0      0      0
      0      0      0      0
   1209   1209   1209   1209
      0      0      0      0
      0      0      0      0

the response should be:

frequencyarray2 =

      0      0      0      0

Using find, this doesn't work, it just does everything in on single vector. I thought about using find and then reshape. But that does only work if exactly two numbers are non-zero per vector.

If possible, I'd like to avoid loops. The columns don't have any relation between them.

Any idea is appreciated

like image 509
Atmocreations Avatar asked Apr 19 '26 05:04

Atmocreations


1 Answers

You can use sum and find together. Something like:

frequencyarray(sum(frequencyarray==0)==2)
like image 125
Ali Avatar answered Apr 20 '26 17:04

Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!