How to replace all zeros in a matrix with a vector from 1 to 9 in the order of ascending indices?

5 views (last 30 days)
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 Comments
Image Analyst
Image Analyst on 13 May 2021
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?
Hearthy Tampol
Hearthy Tampol on 14 May 2021
Yes this is homework. I now realized where I lost it haha, there are elements that I incorrectly typed, my bad. But, thanks for the code, I was able to manipulate it to get the right answer I need. Thanks!!

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 13 May 2021
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 Comments
Image Analyst
Image Analyst on 14 May 2021
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!