フィルターのクリア

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 件のコメント
Hearthy Tampol
Hearthy Tampol 2021 年 5 月 14 日
thanks! That's what I really need, I just need to change some elements I incorrectly typed haha
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 Center および File ExchangeLoops 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