Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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"..

Risposta accettata

Voss
Voss il 13 Mag 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)
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 Commenti

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by