Little Index Problem in filling a cell array iteratively
2 次查看(过去 30 天)
显示 更早的评论
I'm really new to Matlab so I'm having a certain number of issues that surely may be avoided with experience like this
T=cell(numel(Sequence_ref),20);
w=15;
sum=0;
for i=1:numel(Sequence_ref)
sum=sum+1
for j=1:20
T{i,j}=zeros(1,floor(numel(Sequence_ref{i,1})./w));
end
end
When it has to start the second iteration MATLAB responds saying that "INDEX EXCEEDS ARRAY BOUNDS". Sequence_ref is a cell array containing nucleotide (5515x1) sequences so each i will score along this gigantic column cell array. Anyone can help me to fix it?
2 个评论
回答(1 个)
Jan
2018-12-5
编辑:Jan
2018-12-5
Do not use "sum" as name of a variable, because this causes confusion frequently, when you try to use the function sum() afterwards. Avoid such shadowing in general.
In addition sum is not used inside the loops, so simply omit it.
T = cell(numel(Sequence_ref), 20);
w = 15;
for i = 1:numel(Sequence_ref)
for j = 1:20
width = floor(numel(Sequence_ref{i, 1}) ./ w)
T{i,j} = zeros(1, width);
end
end
width does not depend on the inner loop, so it is more efficient to move it before the loop. You can replace the innerloop also by a vectorized version:
T = cell(numel(Sequence_ref), 20);
w = 15;
for i = 1:numel(Sequence_ref)
width = floor(numel(Sequence_ref{i, 1}) ./ w);
T(i, :) = {zeros(1, width)};
end
You mention, that the cell is filled with empty arrays. Then width is 0. Maybe you want to define it differently, but I cannot know how.
Now the error "INDEX EXCEEDS ARRAY BOUNDS" (prefer to post a copy of the complete message instead of cropping a short part only):
Either Sequence_ref is not a column cell, as you expect, or you have redefined one of the functions as a variable before: numel or floor. Check this by using the debugger:
dbstop if error
Then run the code again until it stops. Now check:
which numel
which floor
size(Sequence_ref)
3 个评论
Jan
2018-12-6
编辑:Jan
2018-12-6
I mention it every time I see it:
Length = cellfun('length', Sequence_ref);
% Or:
Length = cellfun('prodofsize', Sequence_ref); % This should be called 'numel'
is much faster than using a function handle @length.
I suggested to use the debugger already. You will find out easily, what the problem is, while the readers in the forum have to guess it.
dbstop if error
Then run the code again. Then check the size:
% Failing: Z{1,1}(1,c)=count(Sequence_ref{i,1},'A');
size(Sequence_ref)
i
c
size(Z)
This should reveal the problem already. The debugger is the best friend of the programmer.
By the way: The posted code cannot run due to a misplaced parenthesis:
count(Sequence_ref{i,1),'M')
% ^ ^ One is curly brace, one is round parenthesis
Please post exactly the code you run.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!