Error message "Index exceeds the number of array elements. Index must not exceed 3"

조회 수: 1 (최근 30일)
I have a vector of length 16384 in a cell. In some parts of my code I need up to half length, but I got an error message "Index exceeds the number of array elements." The index must not exceed 3".
Assume fsp is a 16384-length vector or length(fsp)=16384.
sp{1,1}=fsp(1:length(fsp{1,1})/2);
The above syntax looks correct, but unfortunately the result is "Index exceeds the number of array elements." "Index must not exceed 3"..

채택된 답변

Voss
Voss 2022년 5월 13일
fsp is the cell array, and fsp{1,1} is the vector contained in the first element (first cell) of fsp.
You are taking the length of the vector fsp{1,1}, divided by 2, which is 8192, and using that to try to index into the cell array fsp, which apparently has 3 elements (three cells).
If you want sp{1,1} to contain the first half of the vector fsp{1,1}, do this:
sp{1,1} = fsp{1,1}(1:numel(fsp{1,1})/2);
where I've used numel instead of length for clarity, but that does not affect the behavior if fsp{1,1} is a vector.
Or more simply:
sp{1,1} = fsp{1,1}(1:end/2);
Also, in case the vector fsp{1,1} had an odd number of elements, the above would give you a warning since numel(fsp{1,1})/2 (or length(fsp{1,1})/2) would not be an integer, so to handle that case as well, you could do:
sp{1,1} = fsp{1,1}(1:floor(end/2)); % don't include the middle element in case there's an odd number of elements
or:
sp{1,1} = fsp{1,1}(1:ceil(end/2)) % do include the middle element in case there's an odd number of elements
depending on how you want it to work.
A concrete example:
fsp = {1:7};
fsp{1,1}(1:end/2)
Warning: Integer operands are required for colon operator when used as index.
ans = 1×3
1 2 3
fsp{1,1}(1:floor(end/2))
ans = 1×3
1 2 3
fsp{1,1}(1:ceil(end/2))
ans = 1×4
1 2 3 4
  댓글 수: 4
Teshome Kumsa
Teshome Kumsa 2022년 5월 14일
편집: Teshome Kumsa 2022년 5월 14일
I have accepted it. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by