How to replace all zeros in a matrix with a vector from 1 to 9 in the order of ascending indices?
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a matrix x
x =
0 4 9 9 -4 0
4 0 -3 -3 -1 0
0 0 9 9 3 -2
0 0 5 5 10 0
-3 9 -4 -4 10 9
0 0 -1 8 5 0
How can I replace all zeros with values 1 to 9 in the order of ascending indices?
댓글 수: 4
Image Analyst
2021년 5월 13일
So why didn't my answer below work for you? It does it columnwise. Please show what you need as the output so I can adjust my code below. Also, is this homework?
채택된 답변
Image Analyst
2021년 5월 13일
Try this. The replacements are in "column-major" order, since that's how MATLAB does things.
x = [
0 4 9 9 -4 0
4 0 -3 -3 -1 0
0 0 9 9 3 -2
0 0 5 5 10 0
-3 9 -4 -4 10 9
0 0 -1 8 5 0]
zeroMap = x == 0
numZeros = sum(zeroMap(:))
x(zeroMap) = 1 : numZeros
----------------------------------------------------------------------------------
x =
0 4 9 9 -4 0
4 0 -3 -3 -1 0
0 0 9 9 3 -2
0 0 5 5 10 0
-3 9 -4 -4 10 9
0 0 -1 8 5 0
zeroMap =
6×6 logical array
1 0 0 0 0 1
0 1 0 0 0 1
1 1 0 0 0 0
1 1 0 0 0 1
0 0 0 0 0 0
1 1 0 0 0 1
numZeros =
12
x =
1 4 9 9 -4 9
4 5 -3 -3 -1 10
2 6 9 9 3 -2
3 7 5 5 10 11
-3 9 -4 -4 10 9
4 8 -1 8 5 12
If, instead of 1-12, you want to go from 1-9 and then from 1-3, you can do this:
x = [
0 4 9 9 -4 0
4 0 -3 -3 -1 0
0 0 9 9 3 -2
0 0 5 5 10 0
-3 9 -4 -4 10 9
0 0 -1 8 5 0]
zeroMap = x == 0
numZeros = sum(zeroMap(:))
v = rem(0 : numZeros-1, 9) + 1
x(zeroMap) = v
v =
1 2 3 4 5 6 7 8 9 1 2 3
x =
1 4 9 9 -4 9
4 5 -3 -3 -1 1
2 6 9 9 3 -2
3 7 5 5 10 2
-3 9 -4 -4 10 9
4 8 -1 8 5 3
댓글 수: 4
Image Analyst
2021년 5월 14일
You're welcome. (Thanks for Accepting the answer to award reputation points.)
Tip: Did you know that you can click the double-page icon in the upper right corner of code sections to copy the code into the clipboard, then you can paste it into MATLAB editor window from the clipboard.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!