Randomly delete elements of a matrix
1 次查看(过去 30 天)
显示 更早的评论
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) = [];
1 个评论
回答(4 个)
Justace Clutter
2013-4-12
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
2013-4-12
编辑:Justace Clutter
2013-4-12
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
2013-4-12
编辑:Cedric
2013-4-12
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) ;
2 个评论
Justace Clutter
2013-4-12
I was thinking about this solution but I was not sure if that is what he was looking for exactly. I was building up to it but you beet me to it. :)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!