How to remove elements from a matrix?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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
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))
更多回答(1 个)
Stephen23
2017-6-6
编辑:Stephen23
2017-6-6
nkeep = 4;
str = 'thestring';
str(randperm(numel(str),nkeep))
3 个评论
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!