change special elements of matrix without making the other elements a gain

47 Views Asked by At

I want to know if it is possible to change the element of matrix without enumerate all other elements of that matrix.

for example I have a matrix (D) with 1900 rows and 1500 columns and 5 in third dimension. for example when I write the code:

D(1,2,[2,4])=[1 0];

It again makes new matrix D with a little change that I wanted. Is it possible that it changes just in those elements without making the other elements again.

2

There are 2 best solutions below

2
Divakar On

Here's one way with linear indexing -

dim1_idx = 1;
dim2_idx = 2;
dim3_idx = [2,4];

[m,n,r] = size(D);
D( dim1_idx+(dim2_idx-1)*m + (dim3_idx-1)*m*n ) = [0,1]

You can introduce sub2ind for a bit more readability -

D( sub2ind([m,n],dim1_idx,dim2_idx) + (dim3_idx-1)*m*n ) = [0,1]

Verify output -

>> D = rand(5,4,4);

dim1_idx = 1;
dim2_idx = 2;
dim3_idx = [2,4];

[m,n,r] = size(D);
D( dim1_idx+(dim2_idx-1)*m + (dim3_idx-1)*m*n ) = [0,1];
>> D(1,2,2)
ans =
     0
>> D(1,2,4)
ans =
     1
0
Daniel On

Your understanding how matlab behaves is wrong.

Take the example:

D=rand(1900,1500,5);
D(1,2,[2,4])=[1 0]; %Here the original data structure is updated, no new copy of D is created.

There is only one exception, when you still keep the original matrix in another variable:

M=rand(1900,1500,5);
D=M; %Typically, such calls only cause a shallow copy not actually replicating M
D(1,2,[2,4])=[1 0]; %Now a copy has to be created, because you are still holding the unmodified original