Randomly delete elements of a matrix
이전 댓글 표시
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
댓글 수: 1
Yueting Ding
2019년 6월 22일
Thank you for your answer! It helped!
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?
댓글 수: 1
Pascal Schulthess
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. :)
Cedric
2013년 4월 12일
Sorry for this, it happens to me as well occasionally ;-)
Pascal Schulthess
2013년 4월 12일
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!