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

4 Ansichten (letzte 30 Tage)
Hajem Daham
Hajem Daham am 29 Jan. 2018
Bearbeitet: Jan am 29 Jan. 2018
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 Kommentar
Jan
Jan am 29 Jan. 2018
Bearbeitet: Jan am 29 Jan. 2018
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.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Matt J
Matt J am 29 Jan. 2018
Bearbeitet: Matt J am 29 Jan. 2018
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 Kommentar
Jan
Jan am 29 Jan. 2018
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);

Melden Sie sich an, um zu kommentieren.


Rik
Rik am 29 Jan. 2018
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 am 29 Jan. 2018
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 ‘[]’

Community Treasure Hunt

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

Start Hunting!

Translated by