How do I delete the zeros from the matrix?
Show older comments
I would like to delete all the zeros. I want that the non-zero number shift to the left, like this:
00100200300 --> 123--
10030050201 --> 13521
5 Comments
jakobjakob
on 10 Jun 2018
Image Analyst
on 10 Jun 2018
Even a cell array has to be rectangular. You can't have ragged edges. However you can have cells in the array that are empty. OR you can have row vector cell arrays and have as many of those as you have rows in your original matrix.
I don't see how any of those options are as convenient as just sticking with your original matrix. Why do you want to do this?
Rik
on 10 Jun 2018
Arrays in Matlab must be square. What data type do you want? A double array? A cell array? You can use find to find non-zero elements. You can also use eerste_kijkmoment(eerste_kijkmoment~=0)=[]; to remove all non-zero elements and convert the matrix to a vector.
Paolo
on 10 Jun 2018
@jakobjakob
x = {10030050201};
x = regexprep(string(x{:}),'0','');
x = str2double(x);
Accepted Answer
More Answers (2)
Your data is a numerical matrix - the upper left 5x5 submatrix is:
6.5600 0 0 0 0
0 9.1300 9.9200 10.2000 11.2400
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Then the explanation is not clear:
00100200300 --> 123--
10030050201 --> 13521
Maybe you want:
C = num2cell(eerste_kijkmoment, 2);
C = cellfun(@(a) a(a~=0), C, 'UniformOutput', 0);
Or less nice, but with double speed:
C = cell(size(eerste_kijkmoment, 1), 1);
for iC = 1:numel(C)
a = eerste_kijkmoment(iC, :);
C{iC} = a(a ~= 0);
end
Now the cell array C contains the row vectors with different lengths.
You can pre-allocate the output the avoid the time-consuming iterative growing. This simplifies the code:
s1 = size(A, 1);
s2 = max(sum(A ~= 0, 2)); % Maximum row width
B = nan(s1, s2); % Pre-allocation
for k = 1:s1
r = A(k, :); % Get non-zero values
r = r(r ~= 0);
B(k, 1:length(r)) = r; % Insert it in NaN matrix
end
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!