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

3 次查看(过去 30 天)
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