Mahsa Ghaffari
Mahsa Ghaffari

Reputation: 33

Deleting zero after final number

I have a question about how to delet extra zero from a matrix after final number.

A= [5 4 0 2 3 8 9 0 0 0 0 0 0]

Result:

B= [5 4 0 2 3 8 9];

Upvotes: 1

Views: 66

Answers (2)

Divakar
Divakar

Reputation: 221564

find based approach -

A(1:find(A,1,'last')) %// find the last nonzero index and index A until that

nonzeros + find based approach for A with at least one non-zero entry -

nnzA = nonzeros(A) %// Get all non zero entries 
A(1:find(A==nnzA(end))) %// Get the index of last nonzero entry and keep A until that

strfind based approach for A with at least one non-zero entry -

pattern_start = strfind([A~=0 0],[1 0])%//indices of all patterns of [nonzero zero]
A(1:pattern_start(end)) %// Index A until the last pattern

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112679

If A is assured to contain at least one nonzero value, you can do it using max:

[~, ind] = max(A(end:-1:1)~=0);
A(end-ind+2:end) = [];

Or

[~, ind] = max(cumsum(A~=0));
A(ind+1:end) = [];

Or, in the general case, if you don't mind a warning :-)

A = deblank(A);

Upvotes: 1

Related Questions