0

I'm migrating my MATLAB code to phyton with numpy and scipy.

And I'm looking for a simple order to short a MxM matrix (or 2D array)

Example, I whish to remove all "0" from matrix at column 3 and row 3

[[a a 0 a]
 [a a 0 a]
 [0 0 0 0]
 [a a 0 a]]

And take this matrix

[[a a a]
[a a a]
[a a a]]

With only one line of code in numpy or scipy, if possible.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
JPS
  • 1
  • What one liner are you using in MATLAB? – hpaulj Jan 11 '20 at 17:21
  • Read this [post](https://stackoverflow.com/questions/5927180/how-do-i-remove-all-zero-elements-from-a-numpy-array) maybe it's useful, @JPS. – Sido4odus Jan 11 '20 at 17:27
  • The code I used is simple in MATLAB, to delete the 3rd row is: A(3,:)=[] Then to delete the 3rd column A(:,3)=[] – JPS Jan 11 '20 at 17:35
  • Thanks Sidou, but I don't want to remove the values equals to 0, I wish to cut specific rows and columns of a 2D matrix – JPS Jan 11 '20 at 17:48
  • That's two lines! That style of indexed delete works on lists, but not arrays. There is a `np.delete` function that could be applied in the same way. It could even be chained to fit on one line. It doesn't operate in-place. – hpaulj Jan 11 '20 at 17:58
  • Alternatively `np.block` could be used to build a new array from 4 2d slices. – hpaulj Jan 11 '20 at 17:58

1 Answers1

0

I found the answer from this post:

How to delete columns in numpy.array

The instruction is numpy.delete, for a A nxn array to delete any "i" row (axis=0)

A=np.delete(A,i,0)

To delete any "j" column (axis=1)

A=np.delete(A,j,1)

I tried and works in Spyder.

JPS
  • 1