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

5 次查看(过去 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
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?
Hearthy Tampol
Hearthy Tampol 2021-5-14
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!!

请先登录,再进行评论。

采纳的回答

Image Analyst
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by