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

3 次查看(过去 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 个评论

请先登录,再进行评论。

更多回答(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