How to remove elements from a matrix?

조회 수: 7 (최근 30일)
John Mat
John Mat 2017년 6월 6일
댓글: John Mat 2017년 6월 6일
I would like to delete random elements from this matrix: U = [ 't' 'h' 'e' 's' 't' 'r' 'i' 'n' 'g']
How can i do it?
  댓글 수: 2
Adam
Adam 2017년 6월 6일
Stephen23
Stephen23 2017년 6월 6일
Note that [] is a concatenation operator, so this
[ 't' 'h' 'e' 's' 't' 'r' 'i' 'n' 'g']
is simply identical to this:
'thestring'

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2017년 6월 6일
편집: the cyclist 2017년 6월 6일
If you have the Statistics and Machine Learning Toolbox, you can do
numberToKeep = 4;
U = U(sort(randsample(length(U),numberToKeep)));
If you do not have that toolbox, you can accomplish the same thing using a different random function, like randi, but you'll need to guard against repeated elements. Let us know if you get stuck.
  댓글 수: 4
the cyclist
the cyclist 2017년 6월 6일
John, are you saying that you don't even want to specify the number of elements to be removed at random ahead of time? You want that to be random, also?
If that is the case, then you can just define
numberToKeep = randi(length(U))
John Mat
John Mat 2017년 6월 6일
Thank u very much, u helped me a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2017년 6월 6일
편집: Stephen23 2017년 6월 6일
Use randperm (it has no repeats):
nkeep = 4;
str = 'thestring';
str(randperm(numel(str),nkeep))
  댓글 수: 3
Stephen23
Stephen23 2017년 6월 6일
편집: Stephen23 2017년 6월 6일
If you want to keep the same order, and have random number of characters removed, then you could do this:
>> str = 'thestring';
>> N = numel(str);
>> str(randperm(N,randperm(N,1))) = []
str = teting
or use randi instead:
>> str = 'thestring';
>> N = numel(str);
>> str(randperm(N,randi(N,1))) = []
str = ttrin
John Mat
John Mat 2017년 6월 6일
Thank you very much for the answers. You helped me a lot! :)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by