Indexing should be displayed last in the index expression

I have a CD1 vector (120-on-1) and I am splitting CD1 into 6 parts. For example, the first part is extracted from line 1 to line 20 in CD1 , and the second part is extracted from line 21 to line 40 in CD1, etc. For each part, I need to calculate the means of the absolute values โ€‹โ€‹of the second data differences .

 for PartNo = 1:6 % extract data Y(PartNo) = CD1(1 + 20*(PartNo-1):20*(PartNo),:); % find the second difference Z(PartNo) = Y(PartNo)(3:end) - Y(PartNo)(1:end-2); % mean of absolute value MEAN_ABS_2ND_DIFF_RESULT(PartNo) = mean(abs(Z)); end 

However, the above commands cause an error:

 ()-indexing must appear last in an index expression for Line:2 

Any ideas on modifying the code so that it does what I want?

+4
source share
3 answers

This error often occurs when Y is an array of cells. For cell arrays

 Y{1}(1:3) 

is legal. Curly braces ( {} ) mean data retrieval, so this means that you are retrieving an array stored at location 1 in an array of cells, and then referring to elements 1 through 3 of this array.

Designation

 Y(1)(1:3) 

differs in that it does not retrieve data, but refers to the location of cell 1. This means that the first part ( Y(1) ) returns an array of cells, which in your case contains one array. This way you will not have direct access to the regular array as before.

This is a notorious limitation in Matlab that you cannot do indirect or double references, which actually means what you are doing here.

Hence the error.

Now, to solve: I suspect that replacing a few normal curly braces with curly ones will do the trick:

 Y{PartNo} = CD1(1+20*(PartNo-1):20*PartNo,:); % extract data Z{PartNo} = Y{PartNo}(3:end)-Y{PartNo}(1:end-2); % find the second difference MEAN_ABS_2ND_DIFF_RESULT{PartNo} = mean(abs(Z{PartNo})); % mean of absolute value 
+7
source

I could suggest a different approach

 Y = reshape(CD1, 20, 6); Z = diff(y(1:2:end,:)); MEAN_ABS_2ND_DIFF_RESULT = mean(abs(Z)); 
+3
source

This is not a valid statement in matlab:

 Y(PartNo)(3:end) 

You must either make Y two-dimensional and use this indexing

 Y(PartNo, 3:end) 

or cut out vector parts and use them directly if you use a loop, as you showed

 for PartNo = 1:6 % extract data Y = CD1(1 + 20*(PartNo-1):20*(PartNo),:); % find the second difference Z = Y(3:end) - Y(1:end-2); % mean of absolute value MEAN_ABS_2ND_DIFF_RESULT(PartNo) = mean(abs(Z)); end 

Also, since CD1 is a vector, you do not need to index the second dimension. Remove :

 Y = CD1(1 + 20*(PartNo-1):20*(PartNo)); 

Finally, you do not need a loop. You can reshape vector CD1 to a two-dimensional array Y size 20x6 , in which the columns are your parts and work directly with the resulting matrix:

 Y = reshape(CD1, 20, 6); Z = Y(3:end,:)-Y(1:end-1,:); MEAN_ABS_2ND_DIFF_RESULT = mean(abs(Z)); 
+3
source

All Articles