Matrix manipulation from one to another one
古いコメントを表示
How to generate
A= [ 1 0 3 0 0; ...
0 7 0 0 10; ...
0 0 0 14 15]
from
B = [1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15]
[EDITED, Jan, Code formatted]
3 件のコメント
Akira Agata
2017 年 11 月 28 日
What is the rule to determine whether keeping the number (e.g 1 -> 1) or changing to zero (e.g 2 -> 0) ?
Prabha Kumaresan
2017 年 11 月 28 日
Jan
2017 年 11 月 28 日
@Prabha Kumaresan: Did you see, that your complete code appeared in one single line? Then the readers do not have any chance to see, that you are talking about matrices, because it looked like a vector.
I've selected your code with the mouse and hit the "{} Code" button. In addition I've inserted "; ..." for clarity. Please format the code by your own in future questions. And read your question after posting it to fix details, which cannot be understood by the readers. Thanks.
採用された回答
その他の回答 (2 件)
B = [1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15];
siz = size(B);
idx = sub2ind(siz, randi([1,3], 1, siz(2)), 1:siz(2));
A = zeros(siz);
A(idx) = B(idx)
5 件のコメント
Prabha Kumaresan
2017 年 11 月 29 日
Andrei Bobrov
2017 年 11 月 29 日
Prabha!
All work on my desktop:
>> B = [1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15];
siz = size(B);
idx = sub2ind(siz, randi([1,3], 1, siz(2)), 1:siz(2));
A = zeros(siz);
A(idx) = B(idx)
A =
1 0 3 0 5
0 0 0 9 0
0 12 0 0 0
>>
Andrei Bobrov
2017 年 11 月 29 日
Hi Jan!
+1.
Prabha Kumaresan
2017 年 11 月 29 日
Andrei Bobrov
2017 年 11 月 28 日
編集済み: Andrei Bobrov
2017 年 11 月 28 日
A = B;
s = size(A);
[~,ii] = sort(rand(s));
n = s(1)*(0:s(2)-1);
ii = bsxfun(@plus,ii,s(1)*(0:s(2)-1));
jj = zeros(s);
jj(bszfun(@plus,randi([2,s(1)],1,s(2)),n)) = 1;
ii(cumsum(jj)>0) = 0;
A(ii(ii>0)) = 0;
or
A = B;
s = size(A);
A(rand(s) < .5) = 0;
k = ~any(A);
if any(k)
ii = find(k);
jj = sub2ind(s,randi(s(1),1,numel(ii)),ii);
A(jj) = B(jj);
end
6 件のコメント
Prabha Kumaresan
2017 年 11 月 28 日
Andrei Bobrov
2017 年 11 月 28 日
編集済み: Andrei Bobrov
2017 年 11 月 28 日
I'm corrected.
Use second variant (after word "or").
Prabha Kumaresan
2017 年 11 月 29 日
Andrei Bobrov
2017 年 11 月 29 日
Hm! :)
s = size(B);
A = B;
[~,ii] = sort(rand(s));
A(sub2ind(s,ii(1:end-1,:),repmat(1:s(2),s(1)-1,1))) = 0;
Prabha Kumaresan
2017 年 11 月 29 日
Prabha Kumaresan
2017 年 11 月 29 日
カテゴリ
ヘルプ センター および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!