Question

I have a tensor T

T=ones(2,2,2)

T(:,:,1) =

 1     1
 1     1

T(:,:,2) =

 1     1
 1     1

Now I want to add an element by doing

T(3,3,3)=100

and I get the following result

T(:,:,1) =

 1     1     0
 1     1     0
 0     0     0

T(:,:,2) =

 1     1     0
 1     1     0
 0     0     0

T(:,:,3) =

 0     0     0
 0     0     0
 0     0   100

As you can see matlab automatically inserts 0 for the new row and column elements. I know that I can convert the zeros using T(T==0)=NaN. But I'm looking for a way where NaN is inserted immediately so I won't have to do the additional conversion.

  • Is there a way that matlab automatically inserts NaN instead of 0 for those elements?

Desired result:

T(:,:,1) =

 1     1    NaN
 1     1    NaN
NaN   NaN   NaN

T(:,:,2) =

 1     1    NaN
 1     1    NaN
NaN   NaN   NaN

T(:,:,3) =

NaN   NaN   NaN
NaN   NaN   NaN
NaN   NaN   100

Appreciate your help.

Was it helpful?

Solution

Code

T=ones(2,2,2)
T(3,3,3)=100
T(T==0)=NaN 
%%// T(~T)=NaN would work too, but not a good practice as T is not logical 

Or

T=ones(2,2,2)
T1 = NaN(3,3,3)
T(1:2,1:2,1:2) = T;
T1(3,3,3)=100

Or

T1 = NaN(3,3,3)
T1(1:2,1:2,1:2)=1;
T1(3,3,3)=100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top