MATLAB: Replace non-zero elements in array with output of a calculation on them nonzero Hi, I have an array, A = [2 3 0 7 0 0 9]. How can I replace the non-zero elements of A with thier original value minus one? I want to generate B = [ 1 2 0 6 0 0 8] Any help would be appreciated! Thanks, DB Best Answer mask = A~=0;A(mask) = A(mask) - 1;You can code it as a single expression, but that risks evaluating the comparison twice:A(A~=0) = A(A~=0) - 1; Related SolutionsMATLAB: How to transpose certain elements in a matrix B = A.*(A<0) + (A.*(A>0)).' ; MATLAB: Non-zero column value Try eye(), any(), and find():A=[1,0,0,0;0,1,1,1;0,0,1,0;0,0,1,1]diagonalElements = logical(eye(length(A)))% Make copy of A so we don't change % the original A (which could be bad).Acopy = A;% Set diagonal elements = 0.Acopy(diagonalElements) = 0rowsWith1s = find(any(Acopy, 2)) Related QuestionChange the certain element after comparison of two arraysNumber of non-zero elementHow to find the elements in a matrix that follow a certain patternFind common non-zero indexesGenerate matrices with non-zero submatricesSum all successive values in matrix row
Best Answer