Please Help (Not sure on what kind of question this is)

So let's say I have a matrix [0 1; 1 0; 1 0]. I don't want to get in specifics but this matrix should result in [0 1; 2 ; 3 0]. I would like for the first number 1 to be equal to one but the rest of the numbers to be added by one following each iteration. My iteration goes from 1st row to the 1st column then to the next column followed by the next row and so on.
Thank you for your help.

Answers (2)

I'm assuming you're missing a 0 in row 2 column 2 of your example output. If so:
x = [0 1; 1 0; 1 0];
x = x';
x(x > 0) = 1:nnz(x);
x = x'
x =
0 1
2 0
3 0

2 Comments

Could you explain what the third line does? Thank you.
The third line says to find all values of x that are greater than 0, and replace these values with 1 through the number of non-zero values in the matrix (in this case, 3).
You might want to read up on logical indexing for more details.
The transposes are added in there because Matlab typically works down columns first, then across rows, and you want the opposite.
I’m not certain what you want.
See if this works:
M = [0 1; 1 0; 1 0];
Result = bsxfun(@times, M, [1:size(M,1)]')
Result =
0 1
2 0
3 0

This question is closed.

Asked:

on 2 Nov 2015

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!