Matrix manipulation from one to another one
Mostrar comentarios más antiguos
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 comentarios
Akira Agata
el 28 de Nov. de 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
el 28 de Nov. de 2017
Jan
el 28 de Nov. de 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.
Respuesta aceptada
Más respuestas (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 comentarios
Prabha Kumaresan
el 29 de Nov. de 2017
Andrei Bobrov
el 29 de Nov. de 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
el 29 de Nov. de 2017
Hi Jan!
+1.
Prabha Kumaresan
el 29 de Nov. de 2017
Andrei Bobrov
el 28 de Nov. de 2017
Editada: Andrei Bobrov
el 28 de Nov. de 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 comentarios
Prabha Kumaresan
el 28 de Nov. de 2017
Andrei Bobrov
el 28 de Nov. de 2017
Editada: Andrei Bobrov
el 28 de Nov. de 2017
I'm corrected.
Use second variant (after word "or").
Prabha Kumaresan
el 29 de Nov. de 2017
Andrei Bobrov
el 29 de Nov. de 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
el 29 de Nov. de 2017
Prabha Kumaresan
el 29 de Nov. de 2017
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!