How to remove elements from a matrix?

2 vues (au cours des 30 derniers jours)
John Mat
John Mat le 6 Juin 2017
Commenté : John Mat le 6 Juin 2017
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 commentaires
Adam
Adam le 6 Juin 2017
Stephen23
Stephen23 le 6 Juin 2017
Note that [] is a concatenation operator, so this
[ 't' 'h' 'e' 's' 't' 'r' 'i' 'n' 'g']
is simply identical to this:
'thestring'

Connectez-vous pour commenter.

Réponse acceptée

the cyclist
the cyclist le 6 Juin 2017
Modifié(e) : the cyclist le 6 Juin 2017
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 commentaires
the cyclist
the cyclist le 6 Juin 2017
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 le 6 Juin 2017
Thank u very much, u helped me a lot!

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 6 Juin 2017
Modifié(e) : Stephen23 le 6 Juin 2017
Use randperm (it has no repeats):
nkeep = 4;
str = 'thestring';
str(randperm(numel(str),nkeep))
  3 commentaires
Stephen23
Stephen23 le 6 Juin 2017
Modifié(e) : Stephen23 le 6 Juin 2017
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 le 6 Juin 2017
Thank you very much for the answers. You helped me a lot! :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by