How do I delete the zeros from the matrix?

조회 수: 7 (최근 30일)
jakobjakob
jakobjakob 2018년 6월 10일
댓글: Monika Jaskolka 2018년 6월 11일
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
Rik
Rik 2018년 6월 10일
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
Paolo 2018년 6월 10일
@jakobjakob
You can remove 0s with regexprep .
x = {10030050201};
x = regexprep(string(x{:}),'0','');
x = str2double(x);

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

채택된 답변

Monika Jaskolka
Monika Jaskolka 2018년 6월 10일
Instead of "-" the following function uses NaN.
function B = removeMatZeros(A)
B = [];
for i = 1: size(A, 1)
r = A(i,:);
r(r==0) = []; % remove zeros
% handle expansion
ncolR = size(r, 2);
ncolB = size(B, 2);
diffcol = ncolR - ncolB;
if (diffcol > 0) % previous rows need more cols
for j = ncolB+1:ncolR
B(:,j) = NaN;
end
elseif (diffcol < 0) % this row needs more cols
r = [r, NaN(1, abs(diffcol))];
end
B(i,:) = r;
end
end
Example:
A =
0 0 1 0 0 2 0 0 3 0 0
1 0 0 3 0 0 5 0 2 0 1
>> removeMatZeros(A)
ans =
1 2 3 NaN NaN
1 3 5 2 1
  댓글 수: 2
Jan
Jan 2018년 6월 11일
편집: Jan 2018년 6월 11일
See my second answer for a simplified version of your code. With a pre-allocation of B with NaN values, the iterative filling can be omitted.
Monika Jaskolka
Monika Jaskolka 2018년 6월 11일
Thanks!

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

추가 답변 (2개)

Jan
Jan 2018년 6월 10일
편집: Jan 2018년 6월 10일
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.

Jan
Jan 2018년 6월 11일
편집: Jan 2018년 6월 11일
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

카테고리

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