How to remove zeros from end of different sizes of rows of matrix?

조회 수: 3 (최근 30일)
Hajem Daham
Hajem Daham 2018년 1월 29일
편집: Jan 2018년 1월 29일
Hi,
Let say a result of array of different sizes of rwos:
array = 1 2 3 0 0
4 5 6 7 0 0
8 9 10 11 12 0
How to remove zeros from rows, so the array will be like this:
array = 1 2 3
4 5 6 7
8 9 10 11 12
  댓글 수: 1
Jan
Jan 2018년 1월 29일
편집: Jan 2018년 1월 29일
It depends on what you want as output. Your
array = 1 2 3
4 5 6 7
8 9 10 11 12
does not reveal this detail, because this is no valid Matlab syntax. There are no such objects in Matlab. The most similar thing would be:
array = {[1 2 3], ...
[4 5 6 7], ...
[8 9 10 11 12]}
If you want this, Matt J's answer is a solution. If you want a "matrix" with a different number of columns per row, Rik's answer is correct: This is impossible.
So please explain exactly, what you want as output. Prefer to use valid Matlab syntax, which produces the objects, if the readers inserts them by copy&paste in Matlab's command window.

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

답변 (3개)

Matt J
Matt J 2018년 1월 29일
편집: Matt J 2018년 1월 29일
array = {[1 2 3 0 0];
[4 5 6 7 0 0];
[8 9 10 11 12 0]};
fun=@(r) r(1:find(r,1,'last'));
arrayNoZeros=cellfun(fun, array, 'uni',0);
arrayNoZeros{:},
  댓글 수: 1
Jan
Jan 2018년 1월 29일
If a cell is wanted as output this works. Using a loop directly is faster than arrayfun with an expensive anonymous function:
n = size(X, 1);
Y = cell(n, 1);
for ix = 1:n
r = X(ix, :);
Y{ix} = r(1:find(r, 1, 'last'));
end
This is about 8 times faster than arrayfun on R2016b for the input data:
X = randi([0, 3], 1000, 8);

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


Rik
Rik 2018년 1월 29일
This impossible with matrices in Matlab. What you can do is using a cell vector where each cell contains to trailing zeros.

Star Strider
Star Strider 2018년 1월 29일
It will not look like you want it to because numeric arrays must have the same number of columns in each row. The best you can do is convert it to a cell array, then eliminate the zero values. You will be able to use each row as a double array in subsequent calculations.
The Code
array = [1 2 3 0 0 0
4 5 6 7 0 0
8 9 10 11 12 0];
carray = mat2cell(array, ones(1,size(array,1)), size(array,2)); % First, Create Cell Array
carray = arrayfun(@(x) x(x~=0), array, 'Uni',0); % Set ‘0’ To ‘[]’

카테고리

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