csg
csg

Reputation: 8186

Swap two elements of a 3*3*1 Matrix in Matlab

I have a 3-dimensional (3*3*1) matrix, when I try to swap 0 with on of the elements next to it (e.g. the element on the right) it swaps the two elements but somehow all the other elements become 0 (shown by Result 1).

clear all
clc

count=1;
node=[4,0,3;7,5,6;8,1,2];

[m,n,~]=find(~node);

node(m,n,count+1)=node(m,n+1,count);
node(m,n+1,count+1)=0;
count=count+1;
disp(node(:,:,count))

Result 1:

 0     3     0
 0     0     0
 0     0     0

However when I try the same thing with a 2-dimensional (3*3) matrix the result is what I expected (shown by Result 2).

clear all
clc

count=1;
node=[4,0,3;7,5,6;8,1,2];

[m,n,~]=find(~node);

node(m,n)=node(m,n+1,count);
node(m,n+1)=0;
count=count+1;
disp(node)

Result 2:

 4     3     0
 7     5     6
 8     1     2

Why is this the case and how can I fix it? Thanks.

Upvotes: 0

Views: 76

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

3*3*1 is not a 3D matrix. It is 2D. 3*3*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1* is also 2D. Any matrix has infinite singleton higher dimensions.

With this line node(m,n,count+1)=node(m,n+1,count);, you change it to 3D.
node(m,n+1,count); equals 3
m=1 (1st row), n=2+1=3 (3rd column), and count=1 (1st 3D slice)

and you save it at node(m,n,count+1)
m=1 (1st row), n=2 (2nd column), count+1=2 (2nd 3D slice)

but you display only the 2nd 3D slice with count=count+1; disp(node(:,:,count))
Note that count equals 2 now.

The remaining elements being initialised at zero is the default behavior. e.g. a(10) = 9 will make 1st 9 elements of a to be zero (if a doesn't exist in workspace before).


There is one more problem with your code which is that if zero exists in the third column then your code tries to replace it with the corresponding value in the 4th column which doesn't exist and hence you will get:

Index exceeds matrix dimensions.

So you need to discard values of the 3rd column or define the desired behavior for such a case.

Upvotes: 2

Related Questions