Append element to a cell

10 ビュー (過去 30 日間)
Afaf Arfaoui
Afaf Arfaoui 2018 年 7 月 9 日
編集済み: Afaf Arfaoui 2018 年 7 月 9 日
I am trying to loop over a cell array S and see if S{i,3} is equal to a j than add the elements of S{i,2} to X{j,1}
j = 1;
X = {};
while j < 29
X{j,1} = j;
for i = 1:length(S)
if S{i,3} == j
for k = 1:length(S{i,2})
X{j,2} =[X{j,2}, S{i,2}(k,1)];
end
end
end
j = j+1;
end
I get Index exceeds matrix dimensions for line 13.
Here is the cell array S:
And S{i,2} looks like this:

回答 (2 件)

Guillaume
Guillaume 2018 年 7 月 9 日
Index exceeds matrix dimensions
Well, then considering that the only indexing is of your cell array, either it doesn't have two columns or it doesn't have i rows. In any case, X{i, 2} is not valid. If X{i, 2} were valid your syntax is indeed correct.
  1 件のコメント
Afaf Arfaoui
Afaf Arfaoui 2018 年 7 月 9 日
I edited my question. Actually the indexing of my cell array is not the only one

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


Jan
Jan 2018 年 7 月 9 日
The message means, that X does not have either i rows or not 2 columns. You can check this easily using the debugger. Type this in the command window:
dbstop if error
Run the code again until stops at the error. Then check:
size(X)
  4 件のコメント
Jan
Jan 2018 年 7 月 9 日
編集済み: Jan 2018 年 7 月 9 日
This is not useful:
for k = 1:length(S{i,2})
X{j,2} = S{i,2}(k,1);
end
It overwrite X{j,2} in each iteration. Maybe you want:
x{j,2} = S{i,2}
or
x{j,2} = S{i,2}(:, 1)
without a loop.
NOTE: Using length is prone to bugs, because it replies the longest dimension. If you want to get the length of the first dimension, use:
size(S, 1)
A cleaned version of your code:
X = cell(29, 2); % Pre-allocate
For j = 1:29
X{j,1} = j;
for i = 1:size(S, 1)
if S{i,3} == j
X{j,2} = [X{i,2}, S{i,2}(:,1)];
end
end
end
The pre-allocation creates X{i, 2} implicitly as [].
Are you sure that [X{ i ,2}, S{i,2}(:,1)] is wanted, not j ?
Afaf Arfaoui
Afaf Arfaoui 2018 年 7 月 9 日
編集済み: Afaf Arfaoui 2018 年 7 月 9 日
Thank you. You're right it's X{j,2}. But I want to append elementS in the same row in each iteration of j and not in different columns:

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

カテゴリ

Help Center および File ExchangeCreating, Deleting, and Querying Graphics Objects についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by