フィルターのクリア

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

1 回表示 (過去 30 日間)
Teshome Kumsa
Teshome Kumsa 2022 年 5 月 13 日
コメント済み: Voss 2022 年 5 月 14 日
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!
Voss
Voss 2022 年 5 月 14 日
I appreciate it!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by