필터 지우기
필터 지우기

How can I change all numbers in matrix to 1? except for 0

조회 수: 26 (최근 30일)
Chris
Chris 2022년 12월 3일
답변: Walter Roberson 2022년 12월 3일
How can I change all numbers in matrix to 1? except for 0
I want to make the matrix which has 1(all the numbers) or 0.

채택된 답변

Voss
Voss 2022년 12월 3일
편집: Voss 2022년 12월 3일
One way:
M = randi(4,[5 5])-2 % a matrix with zero and non-zero elements
M = 5×5
-1 0 0 1 2 -1 -1 2 1 2 -1 1 -1 1 0 2 0 -1 1 2 0 0 1 2 1
M(M ~= 0) = 1 % replace non-zero elements with ones
M = 5×5
1 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 0 0 1 1 1
Another way:
M = randi(4,[5 5])-2 % a matrix with zero and non-zero elements
M = 5×5
-1 2 1 1 2 -1 2 2 0 -1 2 -1 0 2 -1 1 -1 1 -1 -1 -1 -1 0 0 -1
M(logical(M)) = 1 % replace non-zero elements with ones
M = 5×5
1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1

추가 답변 (2개)

Image Analyst
Image Analyst 2022년 12월 3일
Try this
outputMatrix = inputMatrix ~= 0

Walter Roberson
Walter Roberson 2022년 12월 3일
logical(inputMatrix)
However this will fail if the input includes nan

카테고리

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