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!