Reputation: 1492
I have a 3d matrix of size(7,24,7) , what I am trying to do is find all the indexes of matrix(:,:,2)
which are less 1 and replace those indexes in matrix(:,:,7)
as 1
The matrix(:,:,2)
looks somethings like this
Columns 1 through 13
NaN NaN NaN NaN NaN NaN NaN NaN 0 3.2146 3.4017 4.1404 4.1567
NaN NaN NaN NaN NaN NaN NaN 12.7279 NaN 0 3.5119 3.4034 4.0415
NaN NaN NaN NaN NaN NaN 0.5000 0 13.4483 13.0618 11.4976 12.7435 12.0439
NaN NaN NaN NaN NaN NaN 0.5175 0 NaN 2.7080 5.9442 4.5981 14.4535
0 0 NaN NaN NaN NaN 0.5774 NaN 12.0000 10.7083 14.5308 15.5869 14.1067
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN 0 NaN NaN NaN NaN NaN
Columns 14 through 24
3.7342 3.0119 2.8785 2.0736 1.4142 2.8284 0 NaN NaN NaN NaN
3.1623 3.8173 3.8297 6.8981 9.1788 9.1287 8.5781 7.8951 3.7859 NaN NaN
9.2402 6.8328 6.8874 11.2933 16.5555 17.5816 16.9247 14.8052 9.0701 NaN NaN
15.3199 13.0767 12.2584 10.8546 11.5016 11.1679 10.7414 7.5572 7.1201 NaN NaN
13.1808 11.8533 7.2023 11.7163 12.9769 12.3000 10.7779 10.6315 5.1769 NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
What I tried was
[I,J] = ind2sub([7,24],find(matrix(:,:,2) <=1))
The I
and J
values I received are accurate
I =
5
5
3
4
5
3
4
7
1
2
1
J =
1
2
7
7
7
8
8
8
9
10
20
but when I convert these indices to values 1 I get the 1s at the wrong indices, does anyone have any idea what am I doing wrong ?
matrix(I,J,7) = 1
matrix(:,:,7) =
Columns 1 through 22
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0
Columns 23 through 24
0 0
0 0
0 0
0 0
0 0
0 0
0 0
Upvotes: 1
Views: 30
Reputation: 528
Just try
[I,J] = ind2sub([7,24],find(matrix(:,:,2) <=1));
matrix(sub2ind([7,24,7],I,J,7*ones(length(I),1))) = 1;
You need to access the table with linear indexing.
Upvotes: 2
Reputation: 35525
This is how indexing works in MATLAB. Read more here.
To circumvent that problem you can use linear indices.
You can get the linear indices of the subscripts that you want by:
linind=sub2ind(size(matrix),I,J,7*ones(size(I)));
And access those ones (and replace by 1
) by:
matrix(linind)=1;
Upvotes: 4