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
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
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
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
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.
0 件のコメント
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 ‘[]’
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!