Effacer les filtres
Effacer les filtres

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

5 vues (au cours des 30 derniers jours)
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 commentaires
Image Analyst
Image Analyst le 13 Mai 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 le 14 Mai 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!!

Connectez-vous pour commenter.

Réponse acceptée

Image Analyst
Image Analyst le 13 Mai 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 commentaires
Hearthy Tampol
Hearthy Tampol le 14 Mai 2021
thanks! That's what I really need, I just need to change some elements I incorrectly typed haha
Image Analyst
Image Analyst le 14 Mai 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by