Reputation: 20345
I have been doing array indexing as follows
>> n=[1 2 3]
n =
1 2 3
>> idx=1
idx =
1
>> n([idx+1 idx])
ans =
2 1
without any problem. However, today I encounter this error in my following snippet. Please forgive me. I understand I should provide MWE, but I simply cannot reproduce the error!
>> %%% interpret tree
bitmap = zeros(pix_no_per_side, pix_no_per_side);
x_pixels = 1:1:pix_no_per_side;
y_pixels = 1:1:pix_no_per_side;
rule_set = {}; % cell to accommodate rows of diff. sizes
% parse branches
trav_iter = tr.depthfirstiterator;
while tr.get(trav_iter(end)) <= 0 % still have branch unparsed
branch = [1]; % contains the root
node_idx = 1;
while tr.get(branch(end)) > 0 % not bottom yet
node_idx = node_idx+1;
branch = [branch trav_iter(node_idx)];
end
rule_set{end+1} = branch; % one rule per cell
disp(node_idx) % DISPLAYING FOR DEBUGGING
if numel(rule_set) == 1 % only one branch found so far
trav_iter(node_idx) = []; % remove this leaf
else % more than one branches found so far
trav_iter([node_idx-1 node_idx]) = []; % remove this leaf and parent node
end
end
3
3
2
Subscript indices must either be real positive integers or logicals.
>>
Upvotes: 0
Views: 84
Reputation: 20345
It turns out that error message is triggered by
trav_iter(end)
where trav_iter
is possibly to be empty.
Reproducing the error then becomes.
>> a = []
a =
[]
>> a(end)
Subscript indices must either be real positive integers or logicals.
Hence, to fix that, I add one logical and to make sure that the trav_iter
is not empty. i.e.,
while numel(trav_iter) ~= 0 && tr.get(trav_iter(end)) <= 0
Upvotes: 0
Reputation: 7817
The problem with your debugging line is that it only displays the output of node_idx
at the end of the while loop. If it errors after setting node_idx
to 1 and before hitting disp
then you will not see the value of the index that caused the error.
Here's a simple way of understanding it:
x = 1:3
for n = 3:-1:0
y = x(n);
disp(n)
end
As you can probably guess, the above code will error when n
gets to 0,
However, when it runs, I get:
3
2
1
Attempted to access x(0); index must be a positive integer or logical.
i.e. disp
never shows 0
.
But from the command line:
>> n
n =
0
If this is within a function, use dbstop if error
and then check node_idx
when the code stops.
Upvotes: 0
Reputation: 4685
The index node_idx-1
is likely either 0
or -1
. The subscript error almost always indicates this problem. However, any empty, NaN
or other value can cause this as well.
Perhaps this is because the assignment node_idx = 1;
sets the value and in your last loop, it is never incremented yielding a 0
index.
Upvotes: 2