Error message "Index exceeds the number of array elements. Index must not exceed 3"
1 view (last 30 days)
Show older comments
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"..
0 Comments
Accepted Answer
Voss
on 13 May 2022
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)
fsp{1,1}(1:floor(end/2))
fsp{1,1}(1:ceil(end/2))
4 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!