44 views (last 30 days)

Show older comments

Hi guys,

how would you, if you have an arbitrary matrix, randomly delete one element in each row and column of said matrix.

So, for example, you start with a matrix A of size 5x5 and you wanna end up with B of size 4x4.

Thanks!

Edit: I tried it like this, but it results in an error:

a = magic(5);

inRow = randperm(size(a,1));

inCol = randperm(size(a,2));

a(inRow,inCol) = [];

Mahdi
on 12 Apr 2013

Justace Clutter
on 12 Apr 2013

The problem with what you have tried is that you have to remove the entire column and the row and not just a single element. Try the following code instead

a = magic(5);

rowIndex = randi(size(a, 1), 1);

columnIndex = randi(size(a, 2), 1);

anew = a;

anew(rowIndex,:) = [];

anew(:,columnIndex) = [];

disp(a);

disp(anew);

The Result of this code is the following:

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

17 24 1 8

23 5 7 14

4 6 13 20

10 12 19 21

Justace Clutter
on 12 Apr 2013

Edited: Justace Clutter
on 12 Apr 2013

I have a few followup questions:

1: What do you do in the following case?

x o o x

x x x o

x x x o

Should it be:

x x x x

x x x

x

In the example you provided, it was clean, but I am not sure what to do in this case.

2: Does the order of the elements in the final matrix matter?

Cedric Wannaz
on 12 Apr 2013

Edited: Cedric Wannaz
on 12 Apr 2013

Look at the following and let me know if you have any question:

M = randi(10, 4, 5) ; % Random example.

[nr,nc] = size(M) ;

ind = sub2ind([nr,nc], randi(nr, 1, nc), 1:nc) ;

N = M(:) ;

N(ind) = [] ;

N = reshape(N, [], nc) ;

Running this gives e.g.:

>> M

M =

3 2 6 6 6

7 5 3 7 2

7 10 8 9 2

2 4 3 10 3

>> N

N =

3 2 6 7 6

7 10 3 9 2

7 4 8 10 2

PS: if you want to replace M with its reduced version, you don't need to build N; you can just have

[nr,nc] = size(M) ;

ind = sub2ind([nr,nc], randi(nr, 1, nc), 1:nc) ;

M = M(:) ;

M(ind) = [] ;

M = reshape(M, [], nc) ;

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

Start Hunting!