How to remove elements from a matrix?

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 日
doc randperm
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 日

2 投票

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 件のコメント

John Mat
John Mat 2017 年 6 月 6 日
Thanks u very much for the answer, how can i do the exact same thing without 'numberToKeep'? For instance, delete random elements without limit in numberToKeep.
Adam
Adam 2017 年 6 月 6 日
U = [];
would be the quickest way!
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 日

2 投票

Use randperm (it has no repeats):
nkeep = 4;
str = 'thestring';
str(randperm(numel(str),nkeep))

3 件のコメント

John Mat
John Mat 2017 年 6 月 6 日
編集済み: Stephen23 2017 年 6 月 6 日
Sorry for my silly questions but im new at Matlab. I tried this code but i cant find the solution of my error.
str = 'thestring';
nkeep = randperm(length(str));
str = str(randperm(numel(str),nkeep));
disp(str)
I want nkeep to have random number from the length of the string. For example if the length of str is 13 then nkeep will be randomly 8.
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! :)

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2017 年 6 月 6 日

コメント済み:

2017 年 6 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by