How can I eliminate unwanted zeros from a matrix?

조회 수: 37 (최근 30일)
Mark
Mark 2014년 4월 24일
댓글: Mohamad Mossad 2020년 12월 16일
e.g I want to make this:
1,1,1,1,0,0
1,1,0,0,0,0
1,0,0,0,0,0
1,1,1,1,1,0
into this:
1,1,1,1
1,1
1
1,1,1,1,1
...
Thanks
  댓글 수: 3
Guillaume
Guillaume 2016년 6월 16일
Catherine, please start your own question rather than adding to somebody's else.
Roger Stafford
Roger Stafford 2016년 6월 17일
@Catherine: Let A be your original matrix. You can accomplish what you want with:
T = A~=0;
n = sum(T,2);
m = max(n);
B = nan(size(A,1),m);
for k = 1:size(A,1)
B(k,m-n(k)+1:m) = A(k,T(k,:)); % <-- B is the result
end

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

답변 (2개)

Justin
Justin 2014년 4월 24일
편집: per isakson 2016년 6월 17일
It depends on what you are trying to end up with exactly but a good approach would be to set all zero values to NaN. NaNs wont show up in plots and you can use nanmean() or other functions which ignore NaNs to work with your matrix. This will also retain the shape of your matrix.
arr = [1 1 0; 1 0 1; 0 0 1];
arr =
1 1 0
1 0 1
0 0 1
arr(arr==0) = nan
arr =
1 1 NaN
1 NaN 1
NaN NaN 1
Another option is to use a sparse matrix where the memory only retains information about the index of values.
sparse(arr)
ans =
(1,1) 1
(2,1) 1
(1,2) 1
(2,3) 1
(3,3) 1
You could even convert the array into a cell array and use cellfun to replace all the zeros with an empty array. It would be much more difficult to operate on the information then though.
What are you trying to accomplish with the data?
  댓글 수: 1
Mohamad Mossad
Mohamad Mossad 2020년 12월 16일
Thanks, setting up zeros to nan is a great idea. 6 years later.

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


per isakson
per isakson 2014년 4월 24일
Hint:
>> num = [ 1,1,1,1,0,0 ];
>> num( num == 0 ) = []
num =
1 1 1 1
  댓글 수: 6
Image Analyst
Image Analyst 2014년 4월 24일
Or the output could be a cell array where you can have different sized rows in each cell. But I don't know why you'd want to mess with that or even want what he's asking for in the first place. Chances are he won't need what he asked for once we learn what he plans on doing with the result.
per isakson
per isakson 2014년 4월 24일
편집: per isakson 2014년 4월 24일
Agree! I know, I should not try to answer questions like this one.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by