Matrix manipulation from one to another one
Afficher commentaires plus anciens
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 commentaires
Akira Agata
le 28 Nov 2017
What is the rule to determine whether keeping the number (e.g 1 -> 1) or changing to zero (e.g 2 -> 0) ?
Prabha Kumaresan
le 28 Nov 2017
Jan
le 28 Nov 2017
@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.
Réponse acceptée
Plus de réponses (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 commentaires
Prabha Kumaresan
le 29 Nov 2017
Andrei Bobrov
le 29 Nov 2017
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
le 29 Nov 2017
Hi Jan!
+1.
Prabha Kumaresan
le 29 Nov 2017
Andrei Bobrov
le 28 Nov 2017
Modifié(e) : Andrei Bobrov
le 28 Nov 2017
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 commentaires
Prabha Kumaresan
le 28 Nov 2017
Andrei Bobrov
le 28 Nov 2017
Modifié(e) : Andrei Bobrov
le 28 Nov 2017
I'm corrected.
Use second variant (after word "or").
Prabha Kumaresan
le 29 Nov 2017
Andrei Bobrov
le 29 Nov 2017
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
le 29 Nov 2017
Prabha Kumaresan
le 29 Nov 2017
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!