MATLAB Answers

Delete number in two matrices with same indices/position

조회 수: 28(최근 30일)
lhyin5277
lhyin5277 3 Feb 2012
Hi... How can i delete numbers in two different matrices with same position? Example: A = [1 2 4 5;2 4 5 6; 3 7 8 2]; B = [3 4 5 6;0 10 4 1;4 12 34 56];
then if i want remove value 2 in matrix A, in the same time i need to delete the value at same position in matrix B.
the answer will get are: A = [1 4 5;4 5 6; 3 7 8]; B = [3 5 6;10 4 1;4 12 34];
Thank you...

답변(2개)

Walter Roberson
Walter Roberson 3 Feb 2012
At = A .';
Bt = B .';
pos = find(At(:) == 2);
At(pos) = [];
Bt(pos) = [];
A = reshape(At, size(A,2), []) .';
B = reshape(Bt, size(B,2), []) .';
And do not be surprised if the reshape step fails, as in the general case there is no reason to believe that their will be exactly the same number of matches per row.
Note: when you delete an element in MATLAB, MATLAB "pulls up" elements from below in the same column . You want to "pull over" from the same row. That is why the two transposes are needed.

Kevin Moerman
Kevin Moerman 3 Feb 2012
If A and B are the save size then instead of the "find" function (which produces linear or subscript indices) use logic indexing for speed e.g.:
L=A==2; A(L)=[]; B(L)=[];
Reshape is not required (and is slow for large arrays). The approach above and that of Mr. Roberson only work if the empty entries of [] lead to the removal of say always n colums or n rows. In other cases you'll get an error. You could use sparse arrays and set the entries to zero instead or use NaN.
Good luck, Kevin
  댓글 수: 2
Sean de Wolski
Sean de Wolski 3 Feb 2012
"Reshape is not required (and is slow for large arrays)."
This is VERY not true! RESHAPE() is one of the fastest functions around. All it does is change header information in the way a file is stored. The only time it is _at all_ time consuming is with large sparse arrays. Let's do an example:
A = rand(1000,1000,200);
tic
for ii =1:100;
A = reshape(A,numel(A),1);
A = reshape(A,200,1000,1000);
A = reshape(A,1000,200,1000);
A = reshape(A,100,100,[]);
end
toc
%{
Elapsed time is 0.001147 seconds.
Elapsed time is 0.001181 seconds.
%}
So it did 400 reshapes of 1.6Gb array in less than two thousands of a second!!
(I originally had an 8Gb array but it dumped my system ;) )

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by